code stringlengths 38 801k | repo_path stringlengths 6 263 |
|---|---|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: conda_python3
# language: python
# name: conda_python3
# ---
# # Contextual Bandits with Parametric Actions - ์คํ ๋ชจ๋
# ์ด ๋
ธํธ๋ถ์ Amazon SageMaker์์ contextual bandits ์๊ณ ๋ฆฌ์ฆ์ผ๋ก ๋ณ๋ํ๋ ํ๋(action) ๊ฐ์์ ๋ํ ์ฌ์ฉ ์์๋ฅผ ๋ณด์ฌ์ค๋๋ค. ์ด ๋
ธํธ๋ถ์ ๊ณ ์ ๋ ์์ ํ๋๋ค์ ์ฌ์ฉํ๋ [Contextual Bandits ์์ ๋
ธํธ๋ถ](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/reinforcement_learning/bandits_statlog_vw_customEnv/bandits_statlog_vw_customEnv.ipynb)์ ๊ธฐ๋ฐ์ผ๋ก ํฉ๋๋ค. Contextual bandits์ ๋ํ ๊ธฐ๋ณธ์ ์ธ ๋ด์ฉ์ ํด๋น ๋
ธํธ๋ถ์ ์ฐธ์กฐํด ์ฃผ์ธ์.
#
# Contextual bandit ์ค์ ์์ ์์ด์ ํธ๋ ์ํ(state)๊ฐ ์ฃผ์ด์ง ํ๋์ ์ถ์ฒํฉ๋๋ค. ์ด ๋
ธํธ๋ถ์์๋ ์ข ๋ ๊ด๋ฒ์ํ ์ค์ ๋ฌธ์ ์ ์ ์ฉํ๊ธฐ ์ํด ์ํ ์ถ์ฒ ๋ฌธ์ ๋ฅผ ์์๋ก ํ์ฌ ์ธ ๊ฐ์ง์ ์ถ๊ฐ ์ํฉ๋ค์ ๋์ดํด ๋ณด๊ฒ ์ต๋๋ค.
#
# 1. ์์ด์ ํธ๊ฐ ์ฌ์ฉํ ์์๋ ํ๋ ๊ฐ์๋ ์๊ฐ์ด ์ง๋จ์ ๋ฐ๋ผ ๋ณ๊ฒฝ๋ ์ ์์ต๋๋ค. ์๋ฅผ ๋ค์ด, ์นดํ๋ก๊ทธ์ ๋์์๋ค์ ์๊ฐ์ด ์ง๋จ์ ๋ฐ๋ผ ๋ณ๊ฒฝ๋ฉ๋๋ค.
# 2. ๊ฐ ํ๋์๋ ๊ด๋ จ ํผ์ฒ๋ค์ด ์์ ์ ์์ต๋๋ค. ์ํ ์ถ์ฒ ๋ฌธ์ ์ ๊ฒฝ์ฐ ๊ฐ ์ํ์๋ ์ฅ๋ฅด, ๋ฐฐ์ฐ ๋ฑ์ ํผ์ฒ๋ค์ด ์์ ์ ์์ต๋๋ค.
# 3. ์์ด์ ํธ๋ ํ๋/์์ดํ
์ ๋ญํฌ๋(ranked) ๋ฆฌ์คํธ๋ฅผ ์์ฑํ ์ ์์ต๋๋ค. ์ํ๋ฅผ ์ถ์ฒ ํ ๋๋ ํ ๋ฒ์ ์ฌ๋ฌ ์ํ๋ฅผ ์ถ์ฒํ๋ ๊ฒ์ด ๋น์ฐํฉ๋๋ค.
#
# Contextual bandit ์์ด์ ํธ๋ exploitation์ exploration ์ฌ์ด์ ๊ท ํ์ ์ ์งํ์ฌ, ์ฌ์ฉ์ ์ ํธ๋(user preferences)๋ฅผ ๋น ๋ฅด๊ฒ ๋ฐฐ์ฐ๊ณ ์ข์ง ์์ ๊ถ์ฅ ํญ๋ชฉ๋ค์ ์ต์ํํฉ๋๋ค. Bandit ์๊ณ ๋ฆฌ์ฆ์ ์นดํ๋ก๊ทธ์ ๋ง์ ์ฝ๋ ํญ๋ชฉ(์ํธ ์์ฉ ๋ฐ์ดํฐ๊ฐ ์๊ฑฐ๋ ๊ฑฐ์ ์๋ ํญ๋ชฉ)์ด ์๊ฑฐ๋ ์๊ฐ์ด ์ง๋จ์ ๋ฐ๋ผ ์ฌ์ฉ์ ๊ธฐ๋ณธ ์ค์ ์ด ๋ณ๊ฒฝ๋๋ ๊ฒฝ์ฐ ์ถ์ฒ ๋ฌธ์ ์ ์ฌ์ฉํ๊ธฐ์ ์ ํฉํฉ๋๋ค.
# ### ์คํ ๋ชจ๋๋ ๋ฌด์์ธ๊ฐ์?
#
# Contextual bandits์ ์ข
์ข
์ค์ ์ธ๊ณ์ ์ํธ ์์ฉํ์ฌ ๋ชจ๋ธ์ ํ๋ จ์ํค๋ ๋ฐ ์ฌ์ฉ๋ฉ๋๋ค. ์ํ ์ถ์ฒ์์ bandit์ ๊ณผ๊ฑฐ์ ์ํธ ์์ฉ์ ๋ํ ํผ๋๋ฐฑ์ ๋ฐํ์ผ๋ก ์ฌ์ฉ์ ์ ํธ๋๋ฅผ ๋ฐฐ์๋๋ค. Bandit ์๊ณ ๋ฆฌ์ฆ์ด ์ค์ฌ์ฉ ์ฌ๋ก์ ์ ์ฉ ๊ฐ๋ฅํ์ง ํ
์คํธํ๊ธฐ ์ํด, ๋ค๋ฅธ ์๊ณ ๋ฆฌ์ฆ์ ํ
์คํธํ๊ณ ๋ค๋ฅธ ํผ์ฒ๋ค๊ณผ ํ์ดํผํ๋ผ๋ฉํฐ์ ๋ฐ๋ฅธ ๋ณ๋ ์ฌํญ์ ํ
์คํธํ ์ ์์ต๋๋ค. ํ์ง๋ง, ์ค์ ์ฌ์ฉ์๋ค๋ก ์คํํ๋ฉด ์๊ธฐ์น ์์ ๋ฌธ์ ๋ ์ฑ๋ฅ ์ ํ๋ก ์ธํด ์ฌ์ฉ์์ ๋ง์กฑ๋๊ฐ ์ ํ๋ ์ ์์ต๋๋ค. ๋ํ, ํ๋ก๋์
ํ๊ฒฝ์์๋ ๊ท๋ชจ์ ๋ง๊ฒ ์ค๊ณ๋ ์ธํ๋ผ ๊ตฌ์ฑ ์์(์: ์น ์๋น์ค, ๋ฐ์ดํฐ ์์ง, ๋ฐ์ดํฐ๋ฒ ์ด์ค)๋ก ์์
ํ๊ธฐ๊ฐ ๋ณต์กํฉ๋๋ค. ์ด ๋, ์คํ ๋ชจ๋(Experimentation Mode)๋ฅผ ์ฌ์ฉํ๋ฉด ์์ ๋ฐ์ดํฐ์
๋๋ ์๋ฎฌ๋ ์ดํฐ๋ก ์์ํ์ฌ ์ฌ์ฉ ์ฌ๋ก์ ๊ฐ์ฅ ์ ํฉํ ์๊ณ ๋ฆฌ์ฆ, ํผ์ณ ๋ฐ ํ์ดํผํ๋ผ๋ฏธํฐ๋ฅผ ์๋ณํ ์ ์์ต๋๋ค. ์คํ์ ํจ์ฌ ๋น ๋ฅด๋ฉฐ ์ค์ ์ฌ์ฉ์์๊ฒ ์ํฅ์ ๋ฏธ์น์ง ์์ผ๋ฉฐ ์์
ํ๊ธฐ๋ ์ฝ์ต๋๋ค. ์๊ณ ๋ฆฌ์ฆ ์ฑ๋ฅ์ด ๋ง์กฑ์ค๋ฌ์ฐ๋ฉด [๋ฐฐ์น ๋ชจ๋](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/reinforcement_learning/bandits_statlog_vw_customEnv/bandits_statlog_vw_customEnv.ipynb)๋ก ์ ํํ์ฌ ํ๋ก๋์
์๊ตฌ ์ฌํญ์ ๋ง๊ฒ ์ธํ๋ผ ์ง์์ ์ ๊ณตํ ์ ์์ต๋๋ค.
# <p align="center">
# <img src="workflow.png">
# </p>
# ## ์ ์ ์กฐ๊ฑด(Pre-requisites)
#
# ### ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ํฌํธ
#
# ์์ํ๊ธฐ ์ํด, ํ์ํ Python ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๊ฐ์ ธ์์ ๊ถํ ๋ฐ ๊ตฌ์ฑ์ ์ํ ๋ช ๊ฐ์ง ์ ์ ์กฐ๊ฑด์ผ๋ก ํ๊ฒฝ์ ์ค์ ํฉ๋๋ค.
import sagemaker
import boto3
import sys
import os
import json
import glob
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import HTML
import time
from time import gmtime, strftime
from misc import get_execution_role, wait_for_s3_object
from sagemaker.rl import RLEstimator
# %matplotlib inline
# ### S3 ๋ฒํท ์ค์
#
# ๋ฐ์ดํฐ ๋ฐ ๋ชจ๋ธ ์ถ๋ ฅ์ ์ฌ์ฉํ๋ ค๋ S3 ๋ฒํท์ ๋ํ ์ฐ๊ฒฐ ๋ฐ ์ธ์ฆ์ ์ค์ ํฉ๋๋ค.
sage_session = sagemaker.session.Session()
s3_bucket = sage_session.default_bucket()
s3_output_path = 's3://{}/'.format(s3_bucket)
print("S3 bucket path: {}".format(s3_output_path))
# Check AWS Region
aws_region = sage_session.boto_region_name
if aws_region not in ["us-west-2"]:
raise Exception(
"""
This notebook can currently run only in us-west-2. Support for other regions
will be added soon.
""")
# ### ํ๋ จ์ด ์งํ๋๋ ์์น ๊ตฌ์ฑ
#
# ์ด ๋
ธํธ๋ถ์ `SageMaker ๋
ธํธ๋ถ ์ธ์คํด์ค` ๋๋ ์ฌ๋ฌ๋ถ์ ์ปดํจํฐ์์ ์คํํ ์ ์์ต๋๋ค. ์ด ๋ ์๋๋ฆฌ์ค ๋ชจ๋ ๋ก์ปฌ ๋๋ SageMaker ๋ชจ๋์์ ํ๋ จ/์ถ๋ก ์ ์ํ ํ ์ ์์ต๋๋ค. ๋ก์ปฌ ๋ชจ๋๋ SageMaker Python SDK๋ฅผ ์ฌ์ฉํ์ฌ ์ฝ๋๋ฅผ ๋์ปค(docker) ์ปจํ
์ด๋์์ ๋ก์ปฌ๋ก ์คํํฉ๋๋ค. ์ด๋ ๊ฒ ํ๋ฉด ์ต์ํ Python SDK ์ธํฐํ์ด์ค๋ฅผ ์ฌ์ฉํ๋ฉด์ ๋ฐ๋ณต ํ
์คํธ ๋ฐ ๋๋ฒ๊น
์๋๋ฅผ ๋์ผ ์ ์์ต๋๋ค. ๊ฐ๋จํ `local_mode = True` ๋ง ์ค์ ํ๋ฉด ๋ฉ๋๋ค.
#
# ๋ก์ปฌ ๋ชจ๋๊ฐ `False`์ด๋ฉด, SageMaker ์์คํ
์์ ํ๋ จ/์ถ๋ก ์ด ์คํ๋ฉ๋๋ค.
# +
# run in local mode?
local_mode = True
if local_mode:
instance_type = 'local'
else:
instance_type = "ml.c5.2xlarge"
# -
# ### IAM ์ญํ ์์ฑ
#
# SageMaker ๋
ธํธ๋ถ `role = sagemaker.get_execution_role()`์ ์คํํ ๋ ์คํ ์ญํ (execution role)์ ์ป๊ฑฐ๋ ๋ก์ปฌ ์์คํ
์์ ์คํํ ๋ utils ๋ฉ์๋ `role = get_execution_role()`์ ์ฌ์ฉํ์ฌ ์คํ ์ญํ ์ ์์ฑํ์ธ์.
# +
try:
role = sagemaker.get_execution_role()
except:
role = get_execution_role()
print("Using IAM role arn: {}".format(role))
# -
# ### ์๋ฎฌ๋ ์ด์
ํ๊ฒฝ (MovieLens ๋ฐ์ดํฐ)
#
#
# ์๋ฎฌ๋ ์ด์
ํ๊ฒฝ `src/env.py`๋ SageMaker bandit ํ๋ จ๊ณผ ์ํธ ์์ฉํ์ฌ ์ถ์ฒ ์์ด์ ํธ(๋๋ ์ ์ฑ
)๋ฅผ ์์ฑํ ์ ์๋ ์ค์ ํ๊ฒฝ์ ์๋ฎฌ๋ ์ด์
ํฉ๋๋ค. ๋ณด์ ์์ฑ์ ๋
ผ๋ฆฌ๋ ์๋ฎฌ๋ ์ดํฐ ์์ฒด์ ์์ต๋๋ค. ์ฐ๋ฆฌ๋ ํ๋ จ ์์
์์ฒด ๋ด์์ ์ด ํ๊ฒฝ์ ์ฌ์ฉํ์ฌ ํผ๋๋ฐฑ์ผ๋ก ์จ๋ผ์ธ ํ์ต ๋ฃจํ๋ฅผ ์๋ฎฌ๋ ์ด์
ํฉ๋๋ค. ์๋ฎฌ๋ ์ดํฐ๋ MovieLens 100k ๋ฐ์ดํฐ์
์ ์ฌ์ฉํฉ๋๋ค.
#
# ํ๋ จ ์ํฌํ๋ก์ฐ๋ ์๋์ ๊ฐ์ต๋๋ค.
#
# - **์ฌ์ฉ์ ์ํ๋ง ๋ฐ ํ๋ณด ๋ชฉ๋ก ์์ฑ**: ์๋ฎฌ๋ ์ดํฐ๋ ์์๋ก ์ฌ์ฉ์ `u`์ 100๊ฐ์ ํญ๋ชฉ ๋ชฉ๋ก(`item_pool_size`๋ก ์ ์๋จ)์ ์ ํํ์ฌ ์ถ์ฒ ๊ฒ์์ ์ํด SageMaker ์์ด์ ํธ๋ก ์ ์ก๋ฉ๋๋ค. ์ด ๋ชฉ๋ก์ ๊ณผ๊ฑฐ์ ์ฌ์ฉ์ `u`๊ฐ ํ๊ฐํ ์ํ๋ก ๊ตฌ์ฑ๋์ด ์๊ณ , ๊ฐ ์ํ์ ๋ํ ์ค์ ์ฌ์ฉ์ ๊ธฐ๋ณธ ์ค์ (๋ฑ๊ธ)์ ์๊ณ ์์ต๋๋ค. ์ด ์๋ฎฌ๋ ์ดํฐ์์๋ `user_id`๋ฅผ ์ฌ์ฉํ์ฌ ์ฌ์ฉ์๋ฅผ ์๋ณํ๊ณ ์ํ ์ฅ๋ฅด ํผ์ฒ๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ ์ํ๋ฅผ ๋ํ๋
๋๋ค.
# - **Bandit Slate ์ถ์ฒ**: SageMaker bandit ์์ด์ ํธ๋ ์ถ์ฒ(top-k ํญ๋ชฉ๋ค์ ๋ชฉ๋ก) ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํฉ๋๋ค.
# - **์ฌ์ฉ์ ํ๋์ ์๋ฎฌ๋ ์ด์
ํ์ฌ ํผ๋๋ฐฑ ์์ฑ**: ๋ณด์์ ๋ฐ์ดํฐ์
์ ์ฌ์ฉ์ ๋ฑ๊ธ์ ๋ฐ๋ผ ์์ด์ ํธ์๊ฒ ์ ๊ณต๋ฉ๋๋ค. ์ฌ์ฉ์๊ฐ ๋ชฉ๋ก์ ์์์ ์๋๋ก ์ค์บํ๊ณ ์ํ๋ ํญ๋ชฉ์ ํด๋ฆญํ๋ ์บ์ค์ผ์ด๋ ํด๋ฆญ(Cascade Click) ๋ชจ๋ธ์ ๊ฐ์ ํฉ๋๋ค. ํด๋ฆญํ ํญ๋ชฉ ์์ ๋ชจ๋ ํญ๋ชฉ์ ๋ํด 0์ ๋ณด์์, ํด๋ฆญํ ํญ๋ชฉ์ ๋ํด 1์ ๋ณด์์ ์ ๊ณตํฉ๋๋ค. ํด๋ฆญ ํ ํญ๋ชฉ ์๋์ ํญ๋ชฉ์ ๋ํด์๋ ํผ๋๋ฐฑ์ด ์์ฑ๋์ง ์์ต๋๋ค.
# - **ํผ๋๋ฐฑ ์ฒ๋ฆฌ**: ํด๋น ๋ณด์ ๋ฐ ํ๋์ด ํ์ต์ ์ํด ์์ด์ ํธ์๊ฒ ๋ณด๊ณ ๋ฉ๋๋ค.
# ํ๋ จ ์์
์ `src` ํด๋์ ํ์ผ์ ์ฌ์ฉํฉ๋๋ค. ์ค์ํ ํ์ผ์ ๋ํ ์ค๋ช
์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
#
# - `src/train.py` - ํ๋ จ ์์
์ ์ํธ๋ฆฌ ํฌ์ธํธ์
๋๋ค. ์ด ํ์ผ์๋ ํ๋ จ์ ์ํ ์ฃผ์ ๋ก์ง์ด ํฌํจ๋์ด ์์ต๋๋ค.
# - Bandit ์์ด์ ํธ๋ฅผ ์ด๊ธฐํํฉ๋๋ค.
# - ์์ด์ ํธ๊ฐ ํ๊ฒฝ๊ณผ ์ํธ ์์ฉํ๊ณ ์ผ๋ถ ํ๋์ ๊ถ์ฅํ๋ฉฐ, ํผ๋๋ฐฑ์ ์์งํ๊ณ , ์๊ฐ์ด ์ง๋จ์ ๋ฐ๋ผ ๊ฐ์ ๋๋ ์ํธ ์์ฉ ๋ฃจํ๋ฅผ ์์ํฉ๋๋ค.
# - ์์ด์ ํธ๋ ํ๋ จ์ด ์๋ฃ๋ ํ S3์ ์ ์ฅ๋๋ฉฐ ์ถ๋ก ์ ์ํด ๋์ค์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
# - `src/env.py` - ์ด ํ์ผ์ MovieLens 100K ๋ฐ์ดํฐ์
์ ์ฌ์ฉํ์ฌ ์๋ฎฌ๋ ์ด์
ํ๊ฒฝ์ ๊ตฌํํฉ๋๋ค. ์บ์ค์ผ์ด๋ ํด๋ฆญ ๋ชจ๋ธ์ ์ฌ์ฉํ ๋ณด์ ์์ฑ ๋ก์ง๋ ํฌํจ๋์ด ์์ต๋๋ค.
# - `src/vw_agent.py` - ๋ฐฑ์๋์์ VW C++ ํ๋ก์ธ์ค์ ํต์ ํ๋ bandit ์์ด์ ํธ ์ธํฐํ์ด์ค๋ฅผ ํ์ด์ฌ์ผ๋ก ๊ตฌํํฉ๋๋ค.
# #### MovieLens 100K ์ฌ์ฉ ๋ผ์ด์ผ์ค
#
# [๋ฐ์ดํฐ์
์ค๋ช
ํ์ด์ง](http://files.grouplens.org/datasets/movielens/ml-100k-README.txt)์์ ์ธ์ฉ๋ ์น์ธ, ์ ์๊ถ ๋ฐ ๊ฐ์ฉ์ฑ์ ๊ดํ ๋ค์ ์๊ตฌ ์ฌํญ์ ์ ์ํ์ญ์์ค.
#
# ๋ฐ์ดํฐ์
์ ๋ค์ ์กฐ๊ฑด๋ค ํ์์ ๋ชจ๋ ์ฐ๊ตฌ ๋ชฉ์ ์ผ๋ก ์ฌ์ฉ๋ ์ ์์ต๋๋ค.
#
# * ์ฌ์ฉ์๋ ๋ฏธ๋ค์ํ ๋ํ๊ต(University of Minnesota) ๋๋ GroupLens Research Group์ ๋ณด์ฆ์ ์ง์ ํ๊ฑฐ๋ ์์ํด์๋ ์๋ฉ๋๋ค.
# * ์ฌ์ฉ์๋ ๋ฐ์ดํฐ์
์ฌ์ฉ ์, ๋
ผ๋ฌธ์์ ๋ฐ์ดํฐ์
์ฌ์ฉ์ ์ธ์ ํด์ผ ํฉ๋๋ค (์ธ์ฉ ์ ๋ณด๋ ์๋ ์ฐธ์กฐ).
# * ์ฌ์ฉ์๋ ๋ณ๋์ ํ๊ฐ ์์ด ๋ฐ์ดํฐ๋ฅผ ์ฌ๋ฐฐํฌํ ์ ์์ต๋๋ค.
# * ์ฌ์ฉ์๋ ๋ฏธ๋ค์ํ ๋ํ๊ต์ ์๋ GroupLens ์ฐ๊ตฌ ํ๋ก์ ํธ์ ๊ต์์ง์ ํ๊ฐ๋ฅผ ๋ฐ์ง ์๊ณ ๋ ์์
์ ๋๋ ์์
์ ๋ชฉ์ ์ผ๋ก ์ด ์ ๋ณด๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค.
#
# ์ถ๊ฐ ์ง๋ฌธ์ด๋ ์๊ฒฌ์ด ์์ผ์๋ฉด GroupLens (<EMAIL>)์ ๋ฌธ์ํ์ญ์์ค.
# #### MovieLens 100K ๋ค์ด๋ก๋ ๋ฐ S3 ์
๋ก๋
# + language="bash"
# curl -o ml-100k.zip http://files.grouplens.org/datasets/movielens/ml-100k.zip
# unzip ml-100k.zip
# -
movielens_data_s3_path = sage_session.upload_data(path="ml-100k", bucket=s3_bucket, key_prefix="movielens/data")
# ## Python SDK ์คํฌ๋ฆฝํธ ๋ชจ๋๋ฅผ ์ฌ์ฉํ์ฌ Bandit ๋ชจ๋ธ ํ๋ จ
#
# ๋ก์ปฌ ๋ชจ๋๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ ๋
ธํธ๋ถ ์ธ์คํด์ค/๋ก์ปฌ ์ปดํจํฐ์์ ๊ต์ก์ด ์คํ๋ฉ๋๋ค. ํ๋ จ์ ์ํด SageMaker๋ฅผ ์ฌ์ฉํ ๋ CPU ์ธ์คํด์ค๋ฅผ ์ ํํ ์ ์์ต๋๋ค. RLEstimator๋ bandit ์์ด์ ํธ ํ๋ จ์ ์ฌ์ฉ๋ฉ๋๋ค.
#
# 1. Bandit ์๊ณ ๋ฆฌ์ฆ ๋ฐ ํ๊ฒฝ ๊ตฌ์ฑ์ ๋ํ ํ์ดํผํ๋ผ๋ฏธํฐ๋ฅผ ์ง์ ํ์ธ์.
# 2. ํ๊ฒฝ, ํ๋ จ ์ฝ๋ ๋ฐ ์์กด์ฑ ํจํค์ง๋ค์ด ์๋ ์์ค ๋๋ ํ ๋ฆฌ๋ฅผ ์ง์ ํ์ธ์. - `src` ํด๋
# 3. ํ๋ จ ์ํธ๋ฆฌ ํฌ์ธํธ๋ฅผ ์ง์ ํ์ธ์. - `train.py`
# 4. ์ปจํ
์ด๋ ์ด๋ฏธ์ง๋ฅผ ์ง์ ํ์ธ์.
# 5. ์ธ์คํด์ค ์, ์์
์ด๋ฆ, ์ถ๋ ฅ์ ๋ํ S3 ๊ฒฝ๋ก ๋ฐ ์์
์ด๋ฆ๊ณผ ๊ฐ์ ํ๋ จ ํ๋ผ๋ฉํฐ๋ฅผ ์ ์ํ์ธ์.
# 6. `.fit` ํธ์ถ์์ ์
๋ ฅ ๋ฐ์ดํฐ์
๊ฒฝ๋ก(`movielens_data_s3_path`)๋ฅผ ์ง์ ํ์ธ์.
# #### ํ์ดํผํ๋ผ๋ฏธํฐ ๋ฐ ํ๋ จ ์์
์ด๋ฆ ์ ๋์ฌ(prefix) ์ ์
# +
hyperparameters = {
# Algorithm params
"arm_features": True,
"exploration_policy": "regcbopt",
"mellowness": 0.01,
# Env params
"item_pool_size": 100,
"top_k": 5,
"total_interactions": 2000,
"max_users": 100,
}
job_name_prefix = "testbed-bandits-1"
# -
vw_image_uri = "462105765813.dkr.ecr.us-west-2.amazonaws.com/sagemaker-rl-vw-container:adf"
# +
estimator = RLEstimator(entry_point="train.py",
source_dir='src',
image_name=vw_image_uri,
role=role,
train_instance_type=instance_type,
train_instance_count=1,
output_path=s3_output_path,
base_job_name=job_name_prefix,
hyperparameters = hyperparameters
)
estimator.fit(inputs={"movielens": movielens_data_s3_path}, wait=True)
# -
# #### ํผํฌ๋จผ์ค plotting์ ์ํ ํ๋ จ ๊ฒฐ๊ณผ ๋ค์ด๋ก๋
# ํ๋ จ์ด ์๋ฃ๋๋ฉด regret ๋ฐ์ดํฐ๋ฅผ ๋ค์ด๋ก๋ํ์ฌ bandit ์์ด์ ํธ์ ํผํฌ๋จผ์ค๋ฅผ plotํ ์ ์์ต๋๋ค.
job_name = estimator.latest_training_job.job_name
# SageMaker๋ ๋ชจ๋ธ์ `model.tar.gz`์ ์ ์ฅํ๊ณ ๋ค๋ฅธ ์์
์ถ๋ ฅ์ `output.tar.gz`์ ์ ์ฅํฉ๋๋ค
# +
if local_mode:
output_path_prefix = f"{job_name}/output.tar.gz"
model_path = f"{job_name}/model.tar.gz"
else:
output_path_prefix = f"{job_name}/output/output.tar.gz"
model_path = f"{job_name}/output/model.tar.gz"
sage_session.download_data(path="./output", bucket=s3_bucket, key_prefix=output_path_prefix)
# + language="bash"
# tar -C ./output -xvzf ./output/output.tar.gz
# -
if local_mode:
output_path_local = "output/data/output.json"
else:
output_path_local = "output/output.json"
# +
with open(output_path_local) as f:
all_regrets = json.load(f)
all_regrets = {key: np.cumsum(val) for key,val in all_regrets.items()}
df = pd.DataFrame(all_regrets)
df.plot(title="Cumulative Regret")
# -
# Regret์ ์์ด์ ํธ๊ฐ ์ป์ ์ ์๋ ์ต์ ์ ๋ณด์๊ณผ ์์ด์ ํธ๊ฐ ์ป์ ์ค์ ๋ณด์์ ์ฐจ์ด๋ก ์ ์๋ฉ๋๋ค.
#
# ์์ ๋ํ์์ ๋ณผ ์ ์๋ฏ์ด, bandit ์์ด์ ํธ๋ ๋๋ค์ผ๋ก ํ๋์ ์ ํํ๋ ๊ฒ์ ๋นํด ๋์ regret์ด ํจ์ฌ ์ ์ต๋๋ค.
# ์ฐ๋ฆฌ๊ฐ ๋ ๋ง์ ํ๋ จ์ ์ค์ํ๋ฉด ์ํธ ์์ฉ(`total_interactions`)์ ๊ฒฝ์ฐ regret ๊ณก์ ์ด ํํํด์ง๋ ๊ฒ์ ๊ด์ฐฐ ํ ์ ์์ต๋๋ค.
# ์ด๋ ์์ด์ ํธ๊ฐ ์ฌ์ฉ์์ ์ ํธ๋๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ํ์ตํ์ผ๋ฉฐ ํ๋ จ์ด ์๋ ด๋์์์ ์๋ฏธํฉ๋๋ค.
#
# ์ด์ ํ๋ จ๋ ๋ชจ๋ธ์ ์ฌ์ฉํ์ฌ ์ ๊ท ๋ฐ์ดํฐ์ ๋ํ ์ถ๋ก ์ ์ํํ๋ ๋ฐฉ๋ฒ์ ์ดํด ๋ณด๊ฒ ์ต๋๋ค.
# ### ์ถ๋ก ์ ์ํ SageMaker ๋ชจ๋ธ ์์ฑ
sage_session = sagemaker.local.LocalSession() if local_mode else sage_session
bandit_model = sagemaker.model.Model(image=vw_image_uri,
role=role,
name="vw-model-1",
model_data=f"s3://{s3_bucket}/{model_path}",
sagemaker_session=sage_session)
# SageMaker์ ๋ํ ์ถ๋ก ์ ๋ค์ ๋ ๊ฐ์ง ๋ชจ๋๋ฅผ ์ฌ์ฉํ์ฌ ์ํํ ์ ์์ต๋๋ค.
#
# - **[๋ฐฐ์น ๋ณํ(Batch Transform](https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform.html)**: 1์ด ๋ฏธ๋ง์ ์ง์ฐ ์๊ฐ์ด ์๋ ์ง์์ ์ธ ์๋น ์๋ํฌ์ธํธ๊ฐ ํ์ํ์ง ์์ ์๋๋ฆฌ์ค์ ์ ์ฉํฉ๋๋ค. ์ด๋ฆ์์ ์ ์ ์๋ฏ์ด ๋ฐฐ์น ๋ณํ ์์
์ ๋ฐฐ์น ๋ฐ์ดํฐ๋ฅผ ์ฒ๋ฆฌํ๋ฉฐ ๋๋์ ์
๋ ฅ ๋ฐ์ดํฐ์์ ๋์ ์ฒ๋ฆฌ๋์ ์ถ๋ก ์ ์ํํ๋ ๋ฐ ์ ์ฉํฉ๋๋ค.
# - **์ค์๊ฐ ์ถ๋ก (Real-time Inference)**: ์ด ๋ชจ๋๋ SageMaker HTTP ์น ์๋ฒ ์๋ ํฌ์ธํธ๋ฅผ ๊ฐ๋ํ์ฌ ์์ธก์ ์ค์๊ฐ์ผ๋ก ์ ๊ณตํ ์ ์์ต๋๋ค.
#
# ์๋์ ์ฝ๋ ์
์์ ๋ ๊ฐ์ง ๋ชจ๋๋ฅผ ๋ชจ๋ ํ์ธํด ๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค.
# ### 1. ๋ฐฐ์น ๋ณํ
# +
# setup input data prefix and output data prefix for batch transform
# S3 prefix where we will upload the test dataset
batch_input = f's3://{s3_bucket}/{job_name}/batch_input/'
# S3 prefix where the batch transformation job will store the output
batch_output = f's3://{s3_bucket}/{job_name}/batch_output/'
print("Input path for batch transform: {}".format(batch_input))
print("Output path for batch transform: {}".format(batch_output))
# +
# Let's create a transformer object that can launch batch transformation jobs
batch_transformer = bandit_model.transformer(instance_count=1,
instance_type=instance_type,
output_path=batch_output,
assemble_with = 'Line',
accept = 'application/jsonlines',
max_payload=5,
max_concurrent_transforms=4,
strategy='MultiRecord'
)
# -
# ### ์ถ๋ก ์ ์ํ ํ
์คํธ ๋ฐ์ดํฐ ์์ฑ
# ์ฌ๊ธฐ์ MovieLens ์๋ฎฌ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ์ฌ ํ
์คํธ ๋ฐ์ดํฐ ์ธ์คํด์ค๋ฅผ ์์ฑํฉ๋๋ค.
from src.env import MovieLens100KEnv
top_k = 5
env = MovieLens100KEnv(data_dir='./ml-100k', item_pool_size=10, top_k=5, max_users=100)
obs = env.reset()
with open("test_data_batch.jsonlines", "w") as f:
for i in range(100):
user_features, items_features = obs
data_instance = {"shared_context": user_features,
"actions_context": items_features.tolist(),
"top_k": 5,
"user_id": env.current_user_id}
f.write(json.dumps(data_instance))
f.write("\n")
# Step env with random actions to get next user and candidate items
obs, _, done, _ = env.step(actions=np.arange(top_k))
# + language="bash"
# head -n2 test_data_batch.jsonlines
# -
# ์ด ๋ฐ์ดํฐ๋ฅผ S3์ ์
๋ก๋ํฉ๋๋ค. ํ์ผ ํ์์ `jsonlines` ์ด์ด์ผ ํฉ๋๋ค. ์ฆ, ํ์ผ์ ๊ฐ ์ค์ JSON ๋์
๋๋ฆฌ์
๋๋ค.
sage_session.upload_data(path="test_data_batch.jsonlines", bucket=s3_bucket, key_prefix=f"{job_name}/batch_input")
batch_transformer.transform(data=batch_input,
data_type='S3Prefix',
content_type='application/jsonlines',
split_type='Line',
join_source='Input')
batch_transformer.wait()
# ### ๋ฐฐ์น ๋ณํ ๊ฒฐ๊ณผ ๋ค์ด๋ก๋
job_name
batch_transformer._current_job_name
# +
if local_mode:
batch_output_prefix = f"{job_name}/batch_output/{batch_transformer._current_job_name}/"
else:
batch_output_prefix = f"{job_name}/batch_output/"
sage_session.download_data(path="./output", bucket=s3_bucket, key_prefix=batch_output_prefix)
# -
# ๊ฒฐ๊ณผ์ ์ผ๋ถ๋ฅผ ํ์ธํด ๋ณด๊ฒ ์ต๋๋ค.
# + language="bash"
# head -n5 ./output/test_data_batch.jsonlines.out
# -
# ### 2. ์ค์๊ฐ ์ถ๋ก
# ์ค์๊ฐ ์ถ๋ก ์ ์ํํ๋ ค๋ฉด SageMaker ์๋ํฌ์ธํธ ๋ค์ ๋ชจ๋ธ์ ๋ฐฐํฌํ๊ณ ์๋์ ๊ฐ์ด ์์ฒญ์ ํ ์ ์์ต๋๋ค.
bandit_model.deploy(initial_instance_count=1, instance_type=instance_type, endpoint_name="bandit")
predictor = sagemaker.predictor.RealTimePredictor(endpoint="bandit",
sagemaker_session=bandit_model.sagemaker_session,
serializer=sagemaker.predictor.json_serializer,
deserializer=sagemaker.predictor.json_deserializer,
)
predictor.predict({"shared_context": None, "actions_context": [[0, 0, 1], [1, 0, 0], [1, 1, 1]], "top_k": 2})
# ### ์๋ํฌ์ธํธ ์ญ์
if "predictor" in locals():
predictor.delete_endpoint()
| bandits_recsys_movielens_testbed/bandits_movielens_testbed.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # insert_sphere
# ## Import packages
import numpy as np
import porespy as ps
import scipy.ndimage as spim
import matplotlib.pyplot as plt
import skimage
ps.visualization.set_mpl_style()
# ## Create image and variables
# +
im = ps.generators.blobs([100, 100,100])
fig, ax = plt.subplots(figsize=[7, 7]);
ps.visualization.imshow(im);
plt.axis(False);
#default values:
c=[50,50,50]
r=50
v=False
overwrite=True
# -
# ## Apply tool
im = ps.tools.insert_sphere(im=im, c=c, r=r, v=v, overwrite=overwrite)
fig, ax = plt.subplots(figsize=[7, 7]);
ps.visualization.imshow(im);
plt.axis(False);
| examples/tools/howtos/insert_sphere.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Assignment 3
# ### 1) Plot a scatter plot for x = [5,7,8,7,2,17,2,9,4,11,12,9,6] and y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
import matplotlib.pyplot as plt
import numpy as np
x1 = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y1 = [99,86,87,88,111,86,103,87,94,78,77,85,86]
plt.scatter(x1, y1)
plt.xlabel("x")
plt.ylabel("y")
plt.show()
# ### 2) Plot a scatter plot for log(x) for x= 1 to 10
x2 = [ i for i in range(1,11)]
y2 = np.log10(x2)
plt.scatter(x2, y2)
plt.xlabel("x")
plt.ylabel("y=log10(x)")
plt.show()
| Assingment 3.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
from scipy import ndimage, misc
import numpy as np
import os
import cv2
import imutils
import random
l=[]
for i in range(2028):
l.append([])
t=[]
for i in range(2025):
t.append([])
y_train=[]
y_test=[]
blurValue=5
threshold=250
path = "dataset/gt/"
c=0
for image_path in os.listdir(path):
input_path = os.path.join(path, image_path)
image = cv2.imread(input_path)
angle = 90
image = imutils.rotate(image, angle)
# image = cv2.resize(image, (28,28), interpolation = cv2.INTER_AREA)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (blurValue, blurValue), 0)
ret, thresh = cv2.threshold(blur, threshold, 255, cv2.THRESH_BINARY_INV)
if c<2000:
outPath = "dataset/grt/"
fullpath = os.path.join(outPath, image_path)
misc.imsave(fullpath, thresh)
# elif c<3500:
# outPath = "mvalid/divs/"
# fullpath = os.path.join(outPath, image_path)
# misc.imsave(fullpath, thresh)
else:
break
c+=1
| creating data.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# +
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
model = Sequential()
model.add(Conv2D(16, kernel_size=(3,3), activation='relu', padding='same', input_shape=(512, 512, 1)))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(Conv2D(32, kernel_size=(3,3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(Conv2D(64, kernel_size=(3,3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(GlobalAveragePooling2D())
model.add(Dense(100, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(5, activation='softmax'))
model.summary()
# -
from keras.utils import plot_model
plot_model(model, to_file='model.png')
import pydot
print pydot.find_graphviz()
| network_diagram.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Implement fibonacci recursively, dynamically, and iteratively.
class Math(object):
def fib_iterative(self, n):
if n < 2: return n
first, second = 0, 1
for i in range(2, n+1):
result = first + second
first = second
second = result
return result
def fib_recursive(self, n):
if n<2: return n
return self.fib_recursive(n-1) + self.fib_recursive(n-2)
def fib_dynamic(self, n):
"""
This includes memoization
"""
if n<2: return n
memo = {}
if n not in memo:
memo[n] = self.fib_recursive(n-1) + self.fib_recursive(n-2)
return memo[n]
# +
import unittest
class TestFib(unittest.TestCase):
def setUp(self):
self.math = Math()
def test_fib_recursive_works(self):
result = []
expected = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
for i in range(len(expected)):
result.append(self.math.fib_recursive(i))
self.assertEqual(result, expected)
def test_fib_iterative_works(self):
result = []
expected = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
for i in range(len(expected)):
result.append(self.math.fib_iterative(i))
self.assertEqual(result, expected)
# + jupyter={"outputs_hidden": true}
unittest.main(argv=[''], verbosity=2, exit=False)
| Recursion/fibonacci.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# ---
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "4dbe6cdb-ac47-4a8c-8416-375904b4be14", "showTitle": true, "title": "Download the file with curl"}
# %sh curl -O 'https://raw.githubusercontent.com/bsullins/bensullins.com-freebies/master/CogsleyServices-SalesData-US.csv'
# saves file to file:/databricks/driver/CogsleyServices-SalesData-US.csv
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "0e653715-6139-4740-908f-c8ab32a52053", "showTitle": false, "title": ""}
# %fs ls
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "d1cb50f7-8bce-4b1f-afb6-1e7b016ecd8d", "showTitle": true, "title": "Read in and Cleanse Data"}
path = 'file:/databricks/driver/CogsleyServices-SalesData-US.csv'
# path = "/databricks-datasets/samples/population-vs-price/data_geo.csv"
# Use the Spark CSV datasource with options specifying:
# - First line of file is a header
# - Automatically infer the schema of the data
data = sqlContext.read.format('csv')\
.option('header', True)\
.option('inferSchema', True)\
.load(path)
# # Cache data for faster reuse
data.cache()
# drop rows with missing values
data = data.dropna()
# # Register table so it is accessible via SQL Context
# # For Apache Spark = 2.0
# # data.createOrReplaceTempView("data_geo")
display(data)
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "593b57c4-85af-40ed-945d-265347149008", "showTitle": true, "title": "Aggregate and Convert"}
# Get monthly sales totals
summary = data.select('OrderMonthYear', 'SaleAmount').groupBy('OrderMonthYear').sum().orderBy('OrderMonthYear').toDF('OrderMonthYear', 'SaleAmount')
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "7d558075-877c-4041-92f2-ff4501f80d98", "showTitle": false, "title": ""}
summary.show(2)
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "1b9886f4-a1a2-42cd-9fc8-aa855f3c0eac", "showTitle": false, "title": ""}
# Convert OrderMonthYear to integer type
# map is like python loop
results = summary.rdd.map(lambda r: (int(r.OrderMonthYear.replace('-','')), r.SaleAmount)).toDF(["OrderMonthYear","SaleAmount"])
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "90c31625-cc18-44c6-9e97-29bcfd930a83", "showTitle": false, "title": ""}
results.show(2)
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "4bfc2c6a-5f91-46da-aea3-4e6ed1a61441", "showTitle": true, "title": "Convert DataFrame to Features and Labels"}
# convert dataframe to features and labels
# OrderMonthYear is feature and SaleAmount is label
from pyspark.mllib.regression import LabeledPoint
data = results.select('OrderMonthYear', 'SaleAmount')\
.rdd.map(lambda r: LabeledPoint(r[1], [r[0]]))\
.toDF()
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "34fe0898-6f3f-433d-a0e0-e818a94f0b93", "showTitle": false, "title": ""}
display(data)
# + application/vnd.databricks.v1+cell={"inputWidgets": {}, "nuid": "02930e6a-80fa-45db-86b8-0561e46d2a79", "showTitle": false, "title": ""}
| Spark - Apache Spark Essential Training/04.Running Machine Learning Algorithms using MLlib/4.2 Preparing Data for Machine Learning.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .r
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernel_info:
# name: ir
# kernelspec:
# display_name: R
# language: R
# name: ir
# ---
# +
library(IRdisplay)
data <- list(list(x=c(1999, 2000, 2001, 2002), y=c(10, 15, 13, 17), type='scatter'))
figure <- list(data=data)
mimebundle <- list('application/vnd.plotly.v1+json'=figure)
#mimebundle[[]] <- figure
IRdisplay::publish_mimebundle(mimebundle)
# + outputHidden=false inputHidden=false
| r/plotlyr.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# (1) Lihat Petunjuk di bawah ini
# +
# Luas ruangan dalam meter persegi
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50
# Buatlah list dengan nama area berdasarkan variabel diatas dan print area
# Jawab disini
# -
# (2)
# - Buatlah list dengan nama variabel area_2 kemudian sisipkan "Hallway", "Kitchen", "Living Room", "Bed Room", dan "Bath Room" sesuai dengan ukuran masing masing
# - contoh ['hallway', hall, ..., ..., ...]
# +
# Jawab disini
# -
# (3)
# - A. [1, 3, 4, 2] B. [[1, 2, 3], [4, 5, 7]] C. [1 + 2, "a" * 5, 3]
# - Manakah yang bisa dikatakan membuat list yang benar?
# - A, B, C
# - B
# - B dan C
# - C
# +
# Jawab disini dengan comment
# -
# (4) Selesaikan list of list dari rumah di bawah ini, kemudian print rumah serta tipe data dari rumah
rumah = [['hallway', hall],
[...,...],
]
# (5) Selesaikan permasalahan di bawah ini
# +
area_3 = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Print elemen kedua dari area_3
# Print elemen terakhir dari area_3
# Print area dari "living room
# -
# (6) Selesaikan permasalah di bawah ini
# +
area_3 = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Jumlahkan area kitchen dan bedroom kedalam variabel area_makan_favorit
# Print the variable area_makan_favorit
# -
# (7) Selesaikan permasalahan di bawah ini
# +
area_3 = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Guanakan slicing untuk menyimpan 6 elemen pertama dari area_3 simpan pada variabel lantai_1
# Gunakan slicing untuk menyimpan 4 elemen terakhir dari area_3 simpan pada variabel lantai_2
# Print lantai_1 dan lantai_2
# -
# (8) Lihat contoh di bawah ini silahkan eksekusi hasilnya
# +
x = [["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]]
print(x[2][0])
print(x[2][:2])
# -
# (9) Selesaikan permasalahan di bawah ini
# +
area_3 = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Ganti nilai dari "bathroom" menjadi 10.8
# Ganti "living room" menjadi "ruang tamu"
# -
# (10) Selesaikan permasalahan di bawah ini
# +
area_3 = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0,
"bedroom", 10.75, "bathroom", 10.50]
# Tambahkan list ['poolhouse', 24.5] kedalam area_3 beri nama variabel baru area_3_1
# Tambahkan list dari ['garage', 15.45] ke dalam area_3_1 beri nama variabel baru area_3_2
# -
# (11) Selesaikan permasalahan di bawah ini
# +
area_3 = ["hallway", 11.25, "kitchen", 18.0,
"chill zone", 20.0, "bedroom", 10.75,
"bathroom", 10.50, "poolhouse", 24.5,
"garage", 15.45]
# Silahkan hapus 4 elemen terakhir
# -
| Bagian 1 - Pengenalan Python untuk Data Science/Latihan 2 List Python.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] colab_type="text" id="1Z6Wtb_jisbA"
# ##### Copyright 2019 The TensorFlow Authors.
# + cellView="form" colab={} colab_type="code" id="QUyRGn9riopB"
#@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.
# + [markdown] colab_type="text" id="H1yCdGFW4j_F"
# # Premade Estimators
# + [markdown] colab_type="text" id="PS6_yKSoyLAl"
# <table class="tfo-notebook-buttons" align="left">
# <td>
# <a target="_blank" href="https://www.tensorflow.org/tutorials/estimator/premade"><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/tutorials/estimator/premade.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/tutorials/estimator/premade.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/docs/site/en/tutorials/estimator/premade.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
# </td>
# </table>
# + [markdown] colab_type="text" id="R4YZ_ievcY7p"
# This tutorial shows you
# how to solve the Iris classification problem in TensorFlow using Estimators. An Estimator is TensorFlow's high-level representation of a complete model, and it has been designed for easy scaling and asynchronous training. For more details see
# [Estimators](https://www.tensorflow.org/guide/estimator).
#
# Note that in TensorFlow 2.0, the [Keras API](https://www.tensorflow.org/guide/keras) can accomplish many of these same tasks, and is believed to be an easier API to learn. If you are starting fresh, we would recommend you start with Keras. For more information about the available high level APIs in TensorFlow 2.0, see [Standardizing on Keras](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a).
#
# + [markdown] colab_type="text" id="8IFct0yedsTy"
# ## First things first
#
# In order to get started, you will first import TensorFlow and a number of libraries you will need.
# + colab={} colab_type="code" id="jPo5bQwndr9P"
import tensorflow as tf
import pandas as pd
# + [markdown] colab_type="text" id="c5w4m5gncnGh"
# ## The data set
#
# The sample program in this document builds and tests a model that
# classifies Iris flowers into three different species based on the size of their
# [sepals](https://en.wikipedia.org/wiki/Sepal) and
# [petals](https://en.wikipedia.org/wiki/Petal).
#
#
# You will train a model using the Iris data set. The Iris data set contains four features and one
# [label](https://developers.google.com/machine-learning/glossary/#label).
# The four features identify the following botanical characteristics of
# individual Iris flowers:
#
# * sepal length
# * sepal width
# * petal length
# * petal width
#
# Based on this information, you can define a few helpful constants for parsing the data:
#
# + colab={} colab_type="code" id="lSyrXp_He_UE"
CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth', 'Species']
SPECIES = ['Setosa', 'Versicolor', 'Virginica']
# + [markdown] colab_type="text" id="j6mTfIQzfC9w"
# Next, download and parse the Iris data set using Keras and Pandas. Note that you keep distinct datasets for training and testing.
# + colab={} colab_type="code" id="PumyCN8VdGGc"
train_path = tf.keras.utils.get_file(
"iris_training.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv")
test_path = tf.keras.utils.get_file(
"iris_test.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv")
train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)
test = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0)
# + [markdown] colab_type="text" id="wHFxNLszhQjz"
# You can inspect your data to see that you have four float feature columns and one int32 label.
# + colab={} colab_type="code" id="WOJt-ML4hAwI"
train.head()
# + [markdown] colab_type="text" id="jQJEYfVvfznP"
# For each of the datasets, split out the labels, which the model will be trained to predict.
# + colab={} colab_type="code" id="zM0wz2TueuA6"
train_y = train.pop('Species')
test_y = test.pop('Species')
# The label column has now been removed from the features.
train.head()
# + [markdown] colab_type="text" id="jZx1L_1Vcmxv"
# ## Overview of programming with Estimators
#
# Now that you have the data set up, you can define a model using a TensorFlow Estimator. An Estimator is any class derived from `tf.estimator.Estimator`. TensorFlow
# provides a collection of
# `tf.estimator`
# (for example, `LinearRegressor`) to implement common ML algorithms. Beyond
# those, you may write your own
# [custom Estimators](https://www.tensorflow.org/guide/custom_estimators).
# We recommend using pre-made Estimators when just getting started.
#
# To write a TensorFlow program based on pre-made Estimators, you must perform the
# following tasks:
#
# * Create one or more input functions.
# * Define the model's feature columns.
# * Instantiate an Estimator, specifying the feature columns and various
# hyperparameters.
# * Call one or more methods on the Estimator object, passing the appropriate
# input function as the source of the data.
#
# Let's see how those tasks are implemented for Iris classification.
# + [markdown] colab_type="text" id="2OcguDfBcmmg"
# ## Create input functions
#
# You must create input functions to supply data for training,
# evaluating, and prediction.
#
# An **input function** is a function that returns a `tf.data.Dataset` object
# which outputs the following two-element tuple:
#
# * [`features`](https://developers.google.com/machine-learning/glossary/#feature) - A Python dictionary in which:
# * Each key is the name of a feature.
# * Each value is an array containing all of that feature's values.
# * `label` - An array containing the values of the
# [label](https://developers.google.com/machine-learning/glossary/#label) for
# every example.
#
# Just to demonstrate the format of the input function, here's a simple
# implementation:
# + colab={} colab_type="code" id="nzr5vRr5caGF"
def input_evaluation_set():
features = {'SepalLength': np.array([6.4, 5.0]),
'SepalWidth': np.array([2.8, 2.3]),
'PetalLength': np.array([5.6, 3.3]),
'PetalWidth': np.array([2.2, 1.0])}
labels = np.array([2, 1])
return features, labels
# + [markdown] colab_type="text" id="NpXvGjfnjHgY"
# Your input function may generate the `features` dictionary and `label` list any
# way you like. However, we recommend using TensorFlow's [Dataset API](https://www.tensorflow.org/guide/datasets), which can
# parse all sorts of data.
#
# The Dataset API can handle a lot of common cases for you. For example,
# using the Dataset API, you can easily read in records from a large collection
# of files in parallel and join them into a single stream.
#
# To keep things simple in this example you are going to load the data with
# [pandas](https://pandas.pydata.org/), and build an input pipeline from this
# in-memory data:
#
# + colab={} colab_type="code" id="T20u1anCi8NP"
def input_fn(features, labels, training=True, batch_size=256):
"""An input function for training or evaluating"""
# Convert the inputs to a Dataset.
dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
# Shuffle and repeat if you are in training mode.
if training:
dataset = dataset.shuffle(1000).repeat()
return dataset.batch(batch_size)
# + [markdown] colab_type="text" id="xIwcFT4MlZEi"
# ## Define the feature columns
#
# A [**feature column**](https://developers.google.com/machine-learning/glossary/#feature_columns)
# is an object describing how the model should use raw input data from the
# features dictionary. When you build an Estimator model, you pass it a list of
# feature columns that describes each of the features you want the model to use.
# The `tf.feature_column` module provides many options for representing data
# to the model.
#
# For Iris, the 4 raw features are numeric values, so we'll build a list of
# feature columns to tell the Estimator model to represent each of the four
# features as 32-bit floating-point values. Therefore, the code to create the
# feature column is:
# + colab={} colab_type="code" id="ZTTriO8FlSML"
# Feature columns describe how to use the input.
my_feature_columns = []
for key in train.keys():
my_feature_columns.append(tf.feature_column.numeric_column(key=key))
# + [markdown] colab_type="text" id="jpKkhMoZljco"
# Feature columns can be far more sophisticated than those we're showing here. You can read more about Feature Columns in [this guide](https://www.tensorflow.org/guide/feature_columns).
#
# Now that you have the description of how you want the model to represent the raw
# features, you can build the estimator.
# + [markdown] colab_type="text" id="kuE59XHEl22K"
# ## Instantiate an estimator
#
# The Iris problem is a classic classification problem. Fortunately, TensorFlow
# provides several pre-made classifier Estimators, including:
#
# * `tf.estimator.DNNClassifier` for deep models that perform multi-class
# classification.
# * `tf.estimator.DNNLinearCombinedClassifier` for wide & deep models.
# * `tf.estimator.LinearClassifier` for classifiers based on linear models.
#
# For the Iris problem, `tf.estimator.DNNClassifier` seems like the best choice.
# Here's how you instantiated this Estimator:
# + colab={} colab_type="code" id="qnf4o2V5lcPn"
# Build a DNN with 2 hidden layers with 30 and 10 hidden nodes each.
classifier = tf.estimator.DNNClassifier(
feature_columns=my_feature_columns,
# Two hidden layers of 30 and 10 nodes respectively.
hidden_units=[30, 10],
# The model must choose between 3 classes.
n_classes=3)
# + [markdown] colab_type="text" id="tzzt5nUpmEe3"
# ## Train, Evaluate, and Predict
#
# Now that you have an Estimator object, you can call methods to do the following:
#
# * Train the model.
# * Evaluate the trained model.
# * Use the trained model to make predictions.
# + [markdown] colab_type="text" id="rnihuLdWmE75"
# ### Train the model
#
# Train the model by calling the Estimator's `train` method as follows:
# + colab={} colab_type="code" id="4jW08YtPl1iS"
# Train the Model.
classifier.train(
input_fn=lambda: input_fn(train, train_y, training=True),
steps=5000)
# + [markdown] colab_type="text" id="ybiTFDmlmes8"
# Note that you wrap up your `input_fn` call in a
# [`lambda`](https://docs.python.org/3/tutorial/controlflow.html)
# to capture the arguments while providing an input function that takes no
# arguments, as expected by the Estimator. The `steps` argument tells the method
# to stop training after a number of training steps.
#
# + [markdown] colab_type="text" id="HNvJLH8hmsdf"
# ### Evaluate the trained model
#
# Now that the model has been trained, you can get some statistics on its
# performance. The following code block evaluates the accuracy of the trained
# model on the test data:
#
# + colab={} colab_type="code" id="A169XuO4mKxF"
eval_result = classifier.evaluate(
input_fn=lambda: input_fn(test, test_y, training=False))
print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
# + [markdown] colab_type="text" id="VnPMP5EHph17"
# Unlike the call to the `train` method, you did not pass the `steps`
# argument to evaluate. The `input_fn` for eval only yields a single
# [epoch](https://developers.google.com/machine-learning/glossary/#epoch) of data.
#
#
# The `eval_result` dictionary also contains the `average_loss` (mean loss per sample), the `loss` (mean loss per mini-batch) and the value of the estimator's `global_step` (the number of training iterations it underwent).
#
# + [markdown] colab_type="text" id="ur624ibpp52X"
# ### Making predictions (inferring) from the trained model
#
# You now have a trained model that produces good evaluation results.
# You can now use the trained model to predict the species of an Iris flower
# based on some unlabeled measurements. As with training and evaluation, you make
# predictions using a single function call:
# + colab={} colab_type="code" id="wltc0jpgng38"
# Generate predictions from the model
expected = ['Setosa', 'Versicolor', 'Virginica']
predict_x = {
'SepalLength': [5.1, 5.9, 6.9],
'SepalWidth': [3.3, 3.0, 3.1],
'PetalLength': [1.7, 4.2, 5.4],
'PetalWidth': [0.5, 1.5, 2.1],
}
def input_fn(features, batch_size=256):
"""An input function for prediction."""
# Convert the inputs to a Dataset without labels.
return tf.data.Dataset.from_tensor_slices(dict(features)).batch(batch_size)
predictions = classifier.predict(
input_fn=lambda: input_fn(predict_x))
# + [markdown] colab_type="text" id="JsETKQo0rHvi"
# The `predict` method returns a Python iterable, yielding a dictionary of
# prediction results for each example. The following code prints a few
# predictions and their probabilities:
# + colab={} colab_type="code" id="Efm4mLzkrCxp"
for pred_dict, expec in zip(predictions, expected):
class_id = pred_dict['class_ids'][0]
probability = pred_dict['probabilities'][class_id]
print('Prediction is "{}" ({:.1f}%), expected "{}"'.format(
SPECIES[class_id], 100 * probability, expec))
| site/en/tutorials/estimator/premade.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Logistic Regression
# <h6>How to generate dataset</h6>
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
mu1 = np.array([1, 2])
mu2 = np.array([6, 8])
cov1 = np.array([[.4, .1], [.1, .8]])
cov2 = np.array([[1, .4], [.4, 1]])
cov1
cov2
X1 = np.random.multivariate_normal(mu1, cov1, 100)
X2 = np.random.multivariate_normal(mu2, cov2, 100)
X1
X1.shape
X2
X2.shape
plt.scatter(X1[:,0], X1[:,1])
plt.scatter(X2[:,0], X2[:,1])
y1 = np.ones((100,))
y2 = np.zeros((100,))
y1
y2
y1.shape
y2.shape
data = np.zeros((200, 3))
data[:100,2].shape
data.shape
data
data[:100, :-1] = X1
data[100:, :-1] = X2
data[:100, 2] = y1
data
data.shape
np.random.shuffle(data)
data
X = data[:,:-1]
Y = data[:,-1]
X
X.shape
Y
Y.shape
X.shape, Y.shape
data[:5]
# <h4> Logistic Regression </h4>
def Sigmoid(z):
return 1 / (1 + np.exp(-z))
def Hypothesis(X, theta):
return Sigmoid(X.dot(theta))
X
Hypothesis(X, theta=np.random.rand(X.shape[1], 1))
# $$
# J_{\theta}(x) = - \frac{1}{m} \Sigma y^{(i)} log(h(x^{(i)})) + (1 - y^{(i)}) log(1 - h(x^{(i)}))
# $$
def Error(X, theta, Y):
hx = Hypothesis(X, theta)
err = (Y * np.log(hx) + (1 - Y) * np.log(1 - hx)).mean()
return -err
Error(X, [1, 2], Y)
def gradient(X, Y, hx, m):
return np.dot(X.T, (hx - Y)) / m
def gradient_descent(X, Y, lr=0.5, max_itr=1000):
err_list = []
m, n = X.shape
theta = np.zeros((n, 1))
for i in range(max_itr):
err = Error(X, theta, Y)
err_list.append(err)
hx = Hypothesis(X, theta)
grad = gradient(X, Y, hx, m)
theta -= lr * grad
if i % 400 == 0:
print(f'Iteration no {i} and cost {err}')
return theta, err_list
X = np.hstack((np.ones((X.shape[0],1)), X))
X
X.shape
theta, err_list = gradient_descent(X, Y.reshape((-1,1)), max_itr=20_000, lr=10)
theta
plt.plot(err_list)
x_test = np.arange(10)
x2 = -(theta[0] + theta[1] * x_test) / theta[2]
x2
x_test
plt.ylim((-1,13))
plt.plot(x_test, x2)
plt.scatter(X1[:,0],X1[:,1])
plt.scatter(X2[:,0],X2[:,1])
Hypothesis(np.array([1, 2, 6.44]), theta)
Hypothesis(np.array([1, 1, 4]), theta) > 0.5
(Hypothesis(X, theta) > 0.5).sum()
y_pred = Hypothesis(X, theta) > 0.9
y_pred = np.array(y_pred, dtype=np.int).ravel()
y_pred
Y = np.array(Y, dtype=np.int)
Y
y_pred == Y
(y_pred == Y).sum()
y_actual = Y == 1
y_actual
correct = (y_pred.ravel() == y_actual).sum()
correct
X.shape
accuracy = 100 * correct / Y.shape[0]
accuracy
# # Using SkLearn
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
X = cancer.data
Y = cancer.target
cancer
cancer.feature_names
X.shape
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.2)
X_train.shape
Y_train.shape
X_test.shape
Y_test.shape
lr = LogisticRegression()
lr.fit(X_train, Y_train)
lr.score(X_train, Y_train)
lr.score(X_test, Y_test)
Y_pred = lr.predict(X_test)
(Y_pred == Y_test).mean()
(Y_pred == Y_test).sum()
Y_pred.shape
lr.predict_proba(X_test) > 0.6
from sklearn.metrics import confusion_matrix
matrix = confusion_matrix(Y_test,Y_pred)
matrix
people_without_cacer_and_we_dont_predict_cancer = matrix[0][0]
people_without_cacer_and_we_predict_cancer = matrix[0][1]
people_with_cacer_and_we_predict_no_cancer = matrix[1][0]
people_with_cacer_and_we_predict_no_cancer = matrix[1][1]
| notebooks/logistic-regression/Logistic_Regression.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Trading Report Card : Your Tear Sheet
# ## Select Environment & Start Date
env = "PAPER" # PAPER / PROD / BACKTEST
start_date = "2021-01-01"
# #### Imports
# +
# silence warnings
import warnings
from datetime import datetime
import liualgotrader.analytics.analysis as ana
from liualgotrader.models.gain_loss import GainLoss, TradeAnalysis
import matplotlib.pyplot as plt
import nest_asyncio
import numpy as np
import pandas as pd
from empyrical import roll_max_drawdown
from scipy.stats import kurtosis, skew
from IPython.display import HTML, display, Markdown
# %matplotlib inline
warnings.filterwarnings("ignore")
nest_asyncio.apply()
# -
# #### Load Portfolio data from database
returns, investments, percentages = ana.portfolio_return(env, start_date)
gl_df = await GainLoss.load(env, datetime.strptime(start_date, "%Y-%m-%d"))
print(f"loaded {len(gl_df)} gain_loss entries")
ta_df = await TradeAnalysis.load(env, datetime.strptime(start_date, "%Y-%m-%d"))
print(f"loaded {len(ta_df)} trade_analysis entries")
display(Markdown("## $ Profile / Loss"))
display(returns)
display(Markdown("## % Profile / Loss"))
display(percentages)
display(Markdown("## Total $ investments"))
display(investments)
#
# ## Revenue & Percentage per strategy
columns = list(returns.columns)
columns.insert(0, columns.pop(columns.index("revenue")))
with plt.xkcd():
for column in columns:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3)) # 1 row, 2 columns
ax1.set_ylabel(f"{column} $")
ax2.set_ylabel(f"{column} %")
plt.xticks(rotation=45)
returns[column].plot(ax=ax1)
percentages[column].plot(ax=ax2, color="red")
plt.tight_layout()
# ## Strategy/Symbol affinity to Revenue & Percentage
counts = gl_df.symbol.value_counts().rename("c").to_frame()
display(gl_df[gl_df.symbol.isin(counts.loc[counts.c >= 3].index.tolist())])
# ## Accumulative Revenue & Draw-down
columns = list(returns.columns)
columns.insert(0, columns.pop(columns.index("revenue")))
for column in columns:
fig, (ax1, ax2) = plt.subplots(
2, 1, figsize=(10, 4), gridspec_kw={"height_ratios": [3, 1]}
)
ax1.set_ylabel(f"Accumulative\n{column} $")
plt.xticks(rotation=45)
returns[column].cumsum().plot(ax=ax1)
roll_max_drawdown(returns[column].cumsum(), window=1).plot(ax=ax2)
ax2.set_ylabel("drawdown")
plt.tight_layout()
# ## Strategy performance distribution by revenue
df = pd.DataFrame()
df["strategy"] = returns.columns.unique()
df["mean"] = df.strategy.apply(lambda x: returns[x].dropna().mean())
df["std"] = df.strategy.apply(lambda x: returns[x].dropna().std())
df["skew"] = df.strategy.apply(lambda x: skew(returns[x].dropna()))
df["kurtosis"] = df.strategy.apply(lambda x: kurtosis(returns[x].dropna()))
display(Markdown("### Summary"))
display(df)
display(Markdown("### Revenue Histogram per strategy"))
columns = list(returns.columns)
columns.insert(0, columns.pop(columns.index("revenue")))
with plt.xkcd():
for column in columns:
returns[column].hist()
plt.xticks(rotation=45)
plt.ylabel(column)
plt.xlabel('$ Revenue')
plt.show()
# ## Strategy performance by `R Units`
counts = ta_df.symbol.value_counts().rename('c').to_frame()
with plt.xkcd():
for strat in ta_df.algo_name.unique().tolist():
ta_df[
(ta_df.symbol.isin(counts.loc[counts.c > 0].index.tolist()))
& (ta_df.algo_name == strat)
].r_units.hist(bins=10, density=True)
plt.xticks(rotation=45)
plt.ylabel(strat)
plt.xlabel('r units')
plt.show()
| analysis/notebooks/Labs/tear_sheet.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/African-Quant/WQU_MScFE_Capstone_Grp9/blob/master/model_training.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="mP6UCM0w4VmB"
# !pip install -Uqq fastbook --quiet
# ! pip install pyfolio --quiet
# #! pip install fracdiff --quiet
import fastbook
# fastbook.setup_book()
# + id="wsty6khnzzbo"
import os
import re
#import fracdiff as fd
import random
import numpy as np
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
import pandas as pd
from pylab import mpl, plt
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
os.environ['PYTHONHASHSEED'] = '0'
import warnings
warnings.filterwarnings('ignore')
# + id="cpcz8nQZ7N1D"
from fastbook import *
from pandas.api.types import is_string_dtype, is_numeric_dtype, is_categorical_dtype
from fastai.tabular.all import *
from sklearn.ensemble import RandomForestClassifier
from lightgbm import LGBMClassifier
from xgboost import XGBClassifier
from pyfolio.timeseries import perf_stats
from pyfolio import create_simple_tear_sheet, create_returns_tear_sheet
# + id="OcLIHKoXzzP7"
pairs = ['AUDCAD', 'AUDCHF', 'AUDJPY', 'AUDNZD', 'AUDUSD', 'CAD', 'CADCHF',
'CADJPY', 'CHF', 'CHFJPY', 'EURAUD', 'EURCAD', 'EURCHF', 'EURGBP',
'EURJPY', 'EURNZD', 'EURUSD', 'GBPAUD', 'GBPCAD', 'GBPCHF', 'GBPJPY',
'GBPNZD', 'GBPUSD', 'JPY', 'NZDCAD', 'NZDCHF', 'NZDJPY', 'NZDUSD']
def get_data(pair):
''' Retrieves (from a github repo) and prepares the data.
'''
url = f'https://raw.githubusercontent.com/African-Quant/WQU_MScFE_Capstone_Grp9/master/Datasets/{pair}%3DX.csv'
raw = pd.read_csv(url)
raw = pd.DataFrame(raw).drop(['Adj Close', 'Volume'], axis=1)
raw.iloc[:,0] = pd.to_datetime(raw.iloc[:,0])
raw.set_index('Date', inplace=True)
return raw
# + colab={"base_uri": "https://localhost:8080/"} id="HaLYazeL2V3q" outputId="5e232bc5-9ab5-4e47-ba4f-acf056426875"
d = {a:b for a, b in enumerate(pairs)}
print(d)
# + id="3oitLfY62fj3"
# ATR
def eATR(df1,n=14):
"""This calculates the exponential Average True Range of of a dataframe of the open,
high, low, and close data of an instrument"""
df = df1[['Open', 'High', 'Low', 'Close']].copy()
# True Range
df['TR'] = 0
for i in range(len(df)):
try:
df.iloc[i, 4] = max(df.iat[i,1] - df.iat[i,2],
abs(df.iat[i,1] - df.iat[i-1,3]),
abs(df.iat[i,2] - df.iat[i-1,3]))
except ValueError:
pass
# eATR
df['eATR'] = df['TR'].ewm(span=n, adjust=False).mean()
return df['eATR']
# + colab={"base_uri": "https://localhost:8080/", "height": 106} id="ZJnjMa791AH-" outputId="8c86e3e8-04f4-4635-fcd5-1f6c68e9a3fa"
data = get_data(pairs[0])
data.head(1)
# + id="PZB4tYKn25Pt"
def ssl(df1):
"""This function adds the ssl indicator as features to a dataframe
"""
df = df1.copy()
df['smaHigh'] = df['High'].rolling(window=10).mean()
df['smaLow'] = df['Low'].rolling(window=10).mean()
df['hlv'] = 0
df['hlv'] = np.where(df['Close'] > df['smaHigh'],1,np.where(df['Close'] < df['smaLow'],-1,df['hlv'].shift(1)))
df['sslDown'] = np.where(df['hlv'] < 0, df['smaHigh'], df['smaLow'])
df['sslUp'] = np.where(df['hlv'] < 0, df['smaLow'], df['smaHigh'])
df['sslPosition'] = np.where(df['Close'] > df['sslUp'], 1,
np.where(df['Close'] < df['sslDown'], -1, 0))
return df[['sslDown', 'sslUp', 'sslPosition']]
# + id="VMyJ5sXC3BTp"
# Waddah Attar
def WAE(df1):
"""This function creates adds the indicator Waddah Attar features to a dataframe
"""
df = df1.copy()
# EMA
long_ema = df.loc[:,'Close'].ewm(span=40, adjust=False).mean()
short_ema = df.loc[:,'Close'].ewm(span=20, adjust=False).mean()
# MACD
MACD = short_ema - long_ema
# bBands
sma20 = df.loc[:,'Close'].rolling(window=20).mean() # 20 SMA
stddev = df.loc[:,'Close'].rolling(window=20).std() # 20 STDdev
lower_band = sma20 - (2 * stddev)
upper_band = sma20 + (2 * stddev)
#<NAME>
t1 = (MACD - MACD.shift(1))* 150
#t2 = MACD.shift(2) - MACD.shift(3)
df['e1'] = upper_band - lower_band
df['e2'] = -1 *df['e1']
#e2 = upper_band.shift(1) - lower_band.shift(1)
df['trendUp'] = np.where(t1 > 0, t1, 0)
df['trendDown'] = np.where(t1 < 0, t1, 0)
df['waePosition'] = np.where(df['trendUp'] > 0, 1,
np.where(df['trendDown'] < 0, -1, 0))
return df[['e1','e2','trendUp', 'trendDown', 'waePosition']]
# + id="64QBDao04QB8"
def lag_feat(data1):
"""This function adds lag returns as features to a dataframe
"""
data = data1.copy()
lags = 8
cols = []
for lag in range(1, lags + 1):
col = f'lag_{lag}'
data[col] = data['ret'].shift(lag)
cols.append(col)
return data[cols]
# + id="77nTPYJPi-8_"
def datepart_feat(df0, colname = 'Date'):
"""This function adds some common pandas date parts like 'year',
'month' etc as features to a dataframe
"""
df = df0.copy()
df.reset_index(inplace=True)
df1 = df.loc[:,colname]
nu_feats = ['Day', 'Dayofweek', 'Dayofyear']
targ_pre = re.sub('[Dd]ate$', '', colname)
for n in nu_feats:
df[targ_pre+n] = getattr(df1.dt,n.lower())
df[targ_pre+'week'] = df1.dt.isocalendar().week
df['week'] = np.int64(df['week'])
df[targ_pre+'Elapsed'] = df1.astype(np.int64) // 10**9
nu_feats.extend(['week', 'Elapsed'])
df.set_index(colname, inplace=True)
return df[nu_feats]
# + id="fbunZN7b4V5p"
def gen_feat(pair):
df0 = get_data(pair).iloc[-4200:,]
df0['ret'] = df0['Close'].pct_change()
df0['dir'] = np.sign(df0['ret'])
eATR_ = eATR(df0).shift(1)
wae = WAE(df0).shift(1)
ssl1 = ssl(df0).shift(1)
datepart = datepart_feat(df0)
lags = lag_feat(df0)
return pd.concat([df0, eATR_, wae, ssl1, datepart, lags], axis=1).dropna()
# + colab={"base_uri": "https://localhost:8080/", "height": 329} id="dlzR7a3Q3eEC" outputId="39e6369e-475e-4ac7-d894-92e5940edbf2"
dataset = gen_feat(pairs[5])
dataset.drop(['Open', 'High', 'Low', 'Close'], axis=1, inplace=True)
dataset.tail()
# + id="otGRwzJ75FfM" colab={"base_uri": "https://localhost:8080/"} outputId="619242d3-ad67-43f5-c29b-f412baac9dce"
cols = list(dataset.columns)
print(cols)
# + id="rn5AgqWbo1BU"
feats = cols[2:]
# + id="FlxdEr3rB0sS"
df_train = dataset.iloc[:-1000,:]
train = df_train.copy()
df_test = dataset.iloc[-1000:,:]
test = df_test.copy()
# + id="5hk8Mric8Zoz"
train_f = train.iloc[:-1000,:]
valid = train.iloc[-1000:,:]
# + colab={"base_uri": "https://localhost:8080/"} id="meZX3Hln82T_" outputId="859090dc-d098-4420-8db4-e63e9cf57a49"
train_f[feats].columns
# + [markdown] id="QDoM_fp-y4mi"
# ### Using *Random Forest* to Predict Market Direction.
# + id="Ga9-bjyCLjwI"
def rfc(xs, y, n_estimators=40, max_samples=1000,
max_features=0.5, min_samples_leaf=5, **kwargs):
return RandomForestClassifier(n_jobs=-1, n_estimators=n_estimators,
max_samples=max_samples, max_features=max_features,
min_samples_leaf=min_samples_leaf, oob_score=True).fit(xs, y)
# + id="fhWlBf4mp1EK"
def rfc_results():
"""This function trains a Random Forest classifier and outputs the
out-of-sample performance from the validation and test sets
"""
df1 = pd.DataFrame()
df2 = pd.DataFrame()
for pair in pairs:
# retrieving the data and preparing the features
dataset = gen_feat(pair)
dataset.drop(['Open', 'High', 'Low', 'Close'], axis=1, inplace=True)
# selecting the features to train on
cols = list(dataset.columns)
feats = cols[2:]
#splitting into training, validation and test sets
df_train = dataset.iloc[:-1000,:]
train = df_train.copy()
df_test = dataset.iloc[-1000:,:]
test = df_test.copy()
train_f = train.iloc[:-1000,:]
valid = train.iloc[-1000:,:]
#training the algorithm
m = rfc(train_f[feats], train_f['dir']);
#preparing results for both validation and test sets
valid_pred = m.predict(valid[feats])
# valid_acc = accuracy_score(valid['dir'], valid_pred)
test_pred = m.predict(test[feats])
# test_acc = accuracy_score(test['dir'], test_pred)
# Results for validation set
valid_results = perf_stats(valid_pred*valid['ret']).to_frame(name=pair)
valid_results = valid_results.rename_axis('pairs')
# Results for test set
test_results = perf_stats(test_pred*test['ret']).to_frame(name=pair)
test_results = test_results.rename_axis('pairs')
# Merge
df1 = pd.concat([df1, valid_results], axis=1)
df2 = pd.concat([df2, test_results], axis=1)
#output
return df1.T, df2.T
# + id="RN_Da4BYJ-Ri"
rfc_results_valid, rfc_results_test = rfc_results()
# + id="28OTF0NH8itj" colab={"base_uri": "https://localhost:8080/", "height": 893} outputId="92c26e02-af6c-4f95-b8a6-4b6e427e3bfb"
rfc_results_valid
# + colab={"base_uri": "https://localhost:8080/", "height": 893} id="6fWjagZsmiYz" outputId="0e491f96-8fcf-4a2d-e847-b53c8a1021c5"
rfc_results_test
# + [markdown] id="KNVp8TYoYKpd"
# Light GradientBoosting
# + id="7Un1DmcgPPrI"
def lgb(xs, y, learning_rate=0.15, boosting_type='gbdt',
objective='binary', n_estimators=50,
metric=['auc', 'binary_logloss'],
num_leaves=100, max_depth= 1,
**kwargs):
return LGBMClassifier().fit(xs, y)
# + id="n2u4fnP1phwF"
def lgb_results():
"""This function trains a Light Gradient Boosting Method and outputs the
out-of-sample performance from the validation and test sets
"""
df1 = pd.DataFrame()
df2 = pd.DataFrame()
for pair in pairs:
# retrieving the data and preparing the features
dataset = gen_feat(pair)
dataset.drop(['Open', 'High', 'Low', 'Close'], axis=1, inplace=True)
# selecting the features to train on
cols = list(dataset.columns)
feats = cols[2:]
#splitting into training, validation and test sets
df_train = dataset.iloc[:-1000,:]
train = df_train.copy()
df_test = dataset.iloc[-1000:,:]
test = df_test.copy()
train_f = train.iloc[:-1000,:]
valid = train.iloc[-1000:,:]
#training the algorithm
m = lgb(train_f[feats], train_f['dir']);
#preparing results for both validation and test sets
valid_pred = m.predict(valid[feats])
# valid_acc = accuracy_score(valid['dir'], valid_pred)
test_pred = m.predict(test[feats])
# test_acc = accuracy_score(test['dir'], test_pred)
# Results for validation set
valid_results = perf_stats(valid_pred*valid['ret']).to_frame(name=pair)
valid_results = valid_results.rename_axis('pairs')
# Results for test set
test_results = perf_stats(test_pred*test['ret']).to_frame(name=pair)
test_results = test_results.rename_axis('pairs')
# Merge
df1 = pd.concat([df1, valid_results], axis=1)
df2 = pd.concat([df2, test_results], axis=1)
#output
return df1.transpose(), df2.transpose()
# + id="-4ZhOXePql7X"
lgb_results_valid, lgb_results_test = lgb_results()
# + id="nhJJcQfHrCWt" colab={"base_uri": "https://localhost:8080/", "height": 893} outputId="f3416648-d9f6-45e5-a3ea-d39191550ee3"
lgb_results_valid
# + colab={"base_uri": "https://localhost:8080/", "height": 893} id="IKKMIiEgWk76" outputId="041f3c6e-e7ac-4c71-f4f7-7a35e534b51b"
lgb_results_test
# + [markdown] id="eFEjO70aFanP"
# ### XGBOOST
# + id="3-t8TdVuQwX4"
def xgb(xs, y):
return XGBClassifier().fit(xs, y)
# + id="MND1hQayryxT"
def xgb_results():
"""This function trains a eXtreme Gradient Boosting Method and outputs the
out-of-sample performance from the validation and test sets
"""
df1 = pd.DataFrame()
df2 = pd.DataFrame()
for pair in pairs:
# retrieving the data and preparing the features
dataset = gen_feat(pair)
dataset.drop(['Open', 'High', 'Low', 'Close'], axis=1, inplace=True)
# selecting the features to train on
cols = list(dataset.columns)
feats = cols[2:]
#splitting into training, validation and test sets
df_train = dataset.iloc[:-1000,:]
train = df_train.copy()
df_test = dataset.iloc[-1000:,:]
test = df_test.copy()
train_f = train.iloc[:-1000,:]
valid = train.iloc[-1000:,:]
#training the algorithm
m = xgb(train_f[feats], train_f['dir']);
#preparing results for both validation and test sets
valid_pred = m.predict(valid[feats])
# valid_acc = accuracy_score(valid['dir'], valid_pred)
test_pred = m.predict(test[feats])
# test_acc = accuracy_score(test['dir'], test_pred)
# Results for validation set
valid_results = perf_stats(valid_pred*valid['ret']).to_frame(name=pair)
valid_results = valid_results.rename_axis('pairs')
# Results for test set
test_results = perf_stats(test_pred*test['ret']).to_frame(name=pair)
test_results = test_results.rename_axis('pairs')
# Merge
df1 = pd.concat([df1, valid_results], axis=1)
df2 = pd.concat([df2, test_results], axis=1)
#output
return df1.T, df2.T
# + id="2w6hiFqNsO7_"
xgb_results_valid, xgb_results_test = xgb_results()
# + id="P0q5Fm9LsjSS" colab={"base_uri": "https://localhost:8080/", "height": 893} outputId="f1f7e0e8-f5fe-480d-d881-7eabcb67a998"
xgb_results_valid
# + id="UHakA-TKlVxc" colab={"base_uri": "https://localhost:8080/", "height": 893} outputId="9517846c-6ac2-490b-8d50-0f6bb0a2fe41"
xgb_results_test
# + id="-KpN-qP_nQS5"
| model_training.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
from pathlib import Path
import numpy as np # type: ignore
import matplotlib.pyplot as plt # type: ignore
import PIL # type: ignore
import torch # type: ignore
import torch.nn as nn # type: ignore
import torchvision.models.vgg as models # type: ignore
import torchvision.transforms as transforms # type: ignore
from torch.utils.data import TensorDataset, DataLoader, Dataset # type: ignore
normalize = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
mean = [0.485, 0.456, 0.406],
std = [0.229, 0.224, 0.225]
)
])
# -
fn = Path('../data/raw/dog_derp_big.jpeg')
img = PIL.Image.open(fn)
img
img_array = np.array(img)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
vgg16 = models.vgg16(pretrained = True).to(device)
input_tensor = normalize(img)
input_tensor.shape
input_batch = input_tensor.unsqueeze(0).to(device)
vgg_pred = vgg16(input_batch)
vgg_pred[0].argsort()[-5:]
# # PyTorch doc example
# +
import torch
# model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg11', pretrained=True)
# or any of these variants
# model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg11_bn', pretrained=True)
# model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg13', pretrained=True)
# model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg13_bn', pretrained=True)
model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg16', pretrained=True)
# model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg16_bn', pretrained=True)
# model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg19', pretrained=True)
# model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg19_bn', pretrained=True)
model.eval()
# sample execution (requires torchvision)
from PIL import Image
from torchvision import transforms
input_image = Image.open('../data/raw/dog.jpg')
preprocess = transforms.Compose([
transforms.Resize(256),
# transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model
# move the input and model to GPU for speed if available
if torch.cuda.is_available():
input_batch = input_batch.to('cuda')
model.to('cuda')
with torch.no_grad():
output = model(input_batch)
# Tensor of shape 1000, with confidence scores over Imagenet's 1000 classes
#print(output[0])
# The output has unnormalized scores. To get probabilities, you can run a softmax on it.
probabilities = torch.nn.functional.softmax(output[0], dim=0)
#print(probabilities)
# -
probabilities.argsort()[-5:]
np.array(input_image)
| notebooks/vgg_classifier.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Imports
# Import packages
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn.metrics import accuracy_score, confusion_matrix, normalized_mutual_info_score
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import scale, normalize
from sklearn.model_selection import train_test_split, KFold, cross_val_predict, cross_validate, cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
# %matplotlib inline
# ## Exploration and Preprocessing of the dataset
fair_tgan_adult_path = os.path.join(os.getcwd(), 'Datasets', 'fair_tgan_adult_data_4.csv')
adult_test_path = os.path.join(os.getcwd(), 'Datasets', 'adult_test.csv')
column_names = ['age', 'workclass', 'fnlwgt', 'education', 'education_num', 'marital_status', 'occupation', 'relationship', 'race', 'sex', 'capital_gain', 'capital_loss', 'hours_per_week', 'native_country', 'Income']
def prep_data(path, columns):
data = []
for line in open(path):
line = line.split(',')
if line[13] != 'United-States':
line[13] = 'Non-US'
else:
line[13] = 'US'
if line[3] in ['Preschool', '1st-4th', '5th-6th', '7th-8th']:
line[3] = 'prim-middle-school'
elif line[3] in ['9th', '10th', '11th', '12th']:
line[3] = "high-school"
line[-1] = line[-1][:-1]
to_int = lambda a : int(line[a])
for i in [0,2,4,10,11,12]:
line[i] = to_int(i)
data.append(line)
return pd.DataFrame(data, columns=column_names)
adult_train_data = prep_data(fair_tgan_adult_path, columns=column_names)
adult_test_data = prep_data(adult_test_path, columns=column_names)
print('Adult train dataset info:')
display(adult_train_data.info())
print('Adult test dataset info:')
display(adult_test_data.info())
print('Adult train dataset statistical information')
display(adult_train_data.describe())
print('Adult test dataset statistical information')
display(adult_test_data.describe())
print('Adult train dataset head:')
display(adult_train_data.head(10))
print('\nAdult train dataset tail:')
display(adult_train_data.tail(10))
print('Adult test dataset head:')
display(adult_test_data.head(10))
print('\nAdult test dataset tail:')
display(adult_test_data.tail(10))
adult_train_data['sex'].value_counts()
adult_test_data['sex'].value_counts()
adult_train_data.iloc[0]
# ax = sns.countplot(x='sex', data=pd.concat([adult_train_data.iloc[1:,], adult_train_data.iloc[0]]))
ax = sns.countplot(x='sex', data=adult_train_data)
ax.set_xticklabels(['Male', 'Female'])
plt.xlabel('')
plt.show()
ax = sns.countplot(x='sex', data=adult_test_data)
ax.set_xticklabels(['Male', 'Female'])
plt.xlabel('')
plt.show()
adult_train_data['Income'].value_counts()
adult_test_data['Income'].value_counts()
# ax = sns.countplot(x='Income', data=pd.concat([adult_train_data.iloc[3:,], adult_train_data.iloc[0:3,]]))
ax = sns.countplot(x='Income', data=adult_train_data)
ax.set_xticklabels(['<=50K', '>50K'])
plt.xlabel('')
plt.show()
ax = sns.countplot(x='Income', data=adult_test_data)
ax.set_xticklabels(['<=50K', '>50K'])
plt.xlabel('')
plt.show()
pd.crosstab(adult_train_data['sex'], adult_train_data['Income']).plot(kind='bar')
plt.title('Income per personal sex')
plt.xlabel('Sex')
plt.ylabel('Income')
pd.crosstab(adult_test_data['sex'], adult_test_data['Income']).plot(kind='bar')
plt.title('Income per personal sex')
plt.xlabel('Sex')
plt.ylabel('Income')
# ## Mutual Information
# +
sex = adult_train_data['sex'].copy()
for i in range(len(sex)):
if sex[i] == 'Female':
sex[i] = 1
else:
sex[i] = 0
sex = np.asarray(sex, dtype='float64')
# +
y_df = adult_train_data['Income'].copy()
for i in range(len(y_df)):
if y_df[i] == '>50K':
y_df[i] = 1
else:
y_df[i] = 0
y = np.asarray(y_df, dtype='float64')
# -
normalized_mutual_info_score(adult_train_data['sex'], adult_train_data['Income'])
normalized_mutual_info_score(adult_test_data['sex'], adult_test_data['Income'])
# ## Splitting Data
features = adult_train_data.drop(['fnlwgt', 'Income'], axis=1)
features = pd.get_dummies(features)
test_features = adult_test_data.drop(['fnlwgt', 'Income'], axis=1)
test_features = pd.get_dummies(test_features)
s = pd.get_dummies(adult_train_data['sex'])
test_s = pd.get_dummies(adult_test_data['sex'])
# +
y_df = adult_train_data['Income'].copy()
for i in range(len(y_df)):
if y_df[i] == '>50K':
y_df[i] = 1
else:
y_df[i] = 0
y = np.asarray(y_df, dtype='float64')
# +
test_y_df = adult_test_data['Income'].copy()
for i in range(len(test_y_df)):
if test_y_df[i] == '>50K':
test_y_df[i] = 1
else:
test_y_df[i] = 0
test_y = np.asarray(test_y_df, dtype='float64')
# -
print('Training Data shapes:')
print('Features shape: {}'.format(features.shape))
print('Sensitive attribute shape: {}'.format(s.shape))
print('Output label shape: {}'.format(y.shape))
print('Test Data shapes:')
print('Features shape: {}'.format(test_features.shape))
print('Sensitive attribute shape: {}'.format(test_s.shape))
print('Output label shape: {}'.format(test_y.shape))
# ## Disparate Impact (P%-rule)
def p_rule(files):
df = pd.DataFrame()
for f in files:
df = pd.concat([df, f], axis=1)
prot_pos = 0
unprot_pos = 0
if 'sex' in df.columns:
for row in df.iterrows():
if row[1][9] == 'Female' and row[1][-1] == '>50K':
prot_pos += 1
elif row[1][9] == 'Male' and row[1][-1] == '>50K':
unprot_pos += 1
total_females = df['sex'].value_counts()[1]
total_males = df['sex'].value_counts()[0]
if 'Female' in df.columns:
for row in df.iterrows():
if row[1][0] == 1 and row[1][-1] == 1:
prot_pos += 1
elif row[1][1] == 1 and row[1][-1] == 1:
unprot_pos += 1
total_females = df['Female'].value_counts()[1]
total_males = df['Female'].value_counts()[0]
prot_per = prot_pos / total_females * 100
unprot_per = unprot_pos / total_males * 100
train_p_rule = prot_per / unprot_per
print('Number of Females in the positive class (>50K): {}'.format(prot_pos))
print('Percentage of Females in the positive class (>50K): {:.2f}%'.format(prot_per))
print('\nNumber of Males in the positive class (>50K): {}'.format(unprot_pos))
print('Percentage of Males in the positive class (>50K): {:.2f}%'.format(unprot_per))
print('\nTraining set p-rule: {:.2f}%'.format(train_p_rule * 100))
# ### P%-rule on training data
p_rule([adult_train_data])
# ### P%-rule on test data
p_rule([adult_test_data])
# ## Disparate Mistreatment
# +
def print_disparate_mistreatment_stats(s, y, pred_y):
prot_FP = 0
unprot_FP = 0
prot_FN = 0
unprot_FN = 0
prot_TN = 0
unprot_TN = 0
prot_TP = 0
unprot_TP = 0
for i in range(0, len(s)):
if s['sex_Female'][i] == 1:
if y[i] == 1:
if pred_y[i] != y[i]:
prot_FN += 1
else:
prot_TP += 1
else:
if pred_y[i] != y[i]:
prot_FP += 1
else:
prot_TN += 1
else:
if y[i] == 1:
if pred_y[i] != y[i]:
unprot_FN += 1
else:
unprot_TP += 1
else:
if pred_y[i] != y[i]:
unprot_FP += 1
else:
unprot_TN += 1
prot_FPR = prot_FP / (prot_FP + prot_TN)
prot_FNR = prot_FN / (prot_FN + prot_TP)
if prot_FN == 0 and prot_TN == 0:
prot_FOR = 0
else:
prot_FOR = prot_FP / (prot_FN + prot_TN)
prot_FDR = prot_FN / (prot_FP + prot_TP)
unprot_FPR = unprot_FP / (unprot_FP + unprot_TN)
unprot_FNR = unprot_FN / (unprot_FN + unprot_TP)
if unprot_FN == 0 and unprot_TN == 0:
unprot_FOR = 0
else:
unprot_FOR = unprot_FP / (unprot_FN + unprot_TN)
unprot_FDR = unprot_FN / (unprot_FP + unprot_TP)
print()
print("--- Disparate Mistreatment ---")
print("# protected False Positive Rate: %.2f" % (prot_FPR))
print("# unprotected False Positive Rate: %.2f" % (unprot_FPR))
print()
print("# protected False Negative Rate: %.2f" % (prot_FNR))
print("# unprotected False Negative Rate: %.2f" % (unprot_FNR))
print()
print("# protected False Omission Rate: %.2f" % (prot_FOR))
print("# unprotected False Omission Rate: %.2f" % (unprot_FOR))
print()
print("# protected False Discovery Rate: %.2f" % (prot_FDR))
print("# unprotected False Discovery Rate: %.2f" % (unprot_FDR))
print()
# return prot_FPR, unprot_FPR, prot_FNR, unprot_FNR, prot_FDR, unprot_FDR, prot_FOR, unprot_FOR
# -
# ## Multinomial Naive Bayes
multi_nb = MultinomialNB()
multi_nb.fit(X=features, y=y)
'Class log-priors: {}'.format(multi_nb.class_log_prior_)
test_pred = multi_nb.predict(X=test_features)
score = accuracy_score(test_y, test_pred)
print('Accuracy score of multinomial Naive Bayes classifier: {}'.format(score))
cm_norm = confusion_matrix(test_y, test_pred)/confusion_matrix(test_y, test_pred).sum(axis=1)[:, np.newaxis]
sns.heatmap(cm_norm, xticklabels=['>50K', '<=50K'], yticklabels=['>50K', '<=50K'], vmin=0., vmax=1., annot=True)
plt.title('Confusion Matrix')
plt.ylabel('True label')
plt.xlabel('Predicted label')
#plt.figure()
plt.show()
# +
sort_idx = np.argsort(multi_nb.feature_log_prob_[0])
log_probs = multi_nb.feature_log_prob_[:, sort_idx]
ticklabs = features.columns[sort_idx].tolist()
N = len(ticklabs)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots(figsize=(16,6))
pos = ax.bar(ind, log_probs[0], width)
neg = ax.bar(ind + width, log_probs[1], width)
ax.set_ylabel('Log Probability')
ax.set_xticks(ind + width)
ax.set_xticklabels(ticklabs, rotation='vertical')
ax.legend((pos[0], neg[0]), ('>50K', '<=50K'), loc='best')
plt.show()
# -
# ## Logistic Regression
# +
# Creating the logistic regression classifier:
log_reg = LogisticRegression(solver='lbfgs', max_iter=5000)
# Fitting the training data:
fitted = log_reg.fit(features, y)
# Calculating the class predictions:
pred = fitted.predict(test_features)
print('Accuracy of Logistic Regressor: ', fitted.score(test_features, test_y))
# +
# Creating the confusion matrix:
cm_norm = confusion_matrix(test_y, pred)/confusion_matrix(test_y, pred).sum(axis=1)[:, np.newaxis]
sns.heatmap(cm_norm, xticklabels=['>50K', '<=50K'], yticklabels=['>50K', '<=50K'], vmin=0., vmax=1., annot=True)
plt.title('Confusion Matrix')
plt.ylabel('True label')
plt.xlabel('Predicted label')
#plt.figure()
plt.show()
# -
# #### P%-rule on predictions
test_preds = test_s.copy()
test_preds['Income'] = pred
p_rule([test_preds])
# #### Disparate Mistreatment
print_disparate_mistreatment_stats(test_features, test_y, pred)
# ### Standardized
# Standardizing the training and testing feature variables to achieve zero mean and unit variance.
stand_X_train = scale(features)
stand_X_test = scale(test_features)
# +
# Creating the logistic regression classifier:
log_reg = LogisticRegression(solver='lbfgs', max_iter=5000)
# Fitting the training data:
fitted = log_reg.fit(stand_X_train, y)
# Calculating the class predictions:
stand_pred = fitted.predict(stand_X_test)
print('Accuracy of Logistic Regressor: ', fitted.score(stand_X_test, test_y))
# +
# Creating the confusion matrix:
cm_norm = confusion_matrix(test_y, stand_pred)/confusion_matrix(test_y, stand_pred).sum(axis=1)[:, np.newaxis]
sns.heatmap(cm_norm, xticklabels=['>50K', '<=50K'], yticklabels=['>50K', '<=50K'], vmin=0., vmax=1., annot=True)
plt.title('Confusion Matrix')
plt.ylabel('True label')
plt.xlabel('Predicted label')
#plt.figure()
plt.show()
# -
# #### P%-rule on predictions
test_preds = test_s.copy()
test_preds['Income'] = stand_pred
p_rule([test_preds])
# #### Disaprate Mistreatment
print_disparate_mistreatment_stats(test_features, test_y, stand_pred)
# ## Decision Tree Classifier
clf = DecisionTreeClassifier(random_state=0)
cross_val_score(clf, features, adult_train_data['Income'], cv=10)
np.mean(cross_val_score(clf, features, adult_train_data['Income'], cv=10))
clf = DecisionTreeClassifier(random_state=0)
cross_val_score(clf, features, adult_train_data['Income'], cv=20)
np.mean(cross_val_score(clf, features, adult_train_data['Income'], cv=20))
# ## Random Forest Classifier
# +
# Creating the Random Forest Classifier:
rfc = RandomForestClassifier(n_estimators=500, random_state=42, criterion='entropy', max_depth=20)
# Fitting the training data:
rfc_fitted = rfc.fit(features, y)
# Extracting the feature importances:
feature_importances = rfc_fitted.feature_importances_
# Displaying the training and test set accuracies:
print('Accuracy of random forest classifier on the training set: ', rfc_fitted.score(features, y))
print('Accuracy of random forest classifier on the testing set: ', rfc_fitted.score(test_features, test_y))
# -
# ### Feature importance
# Creating and displaying a dataframe for the top 10 most important features:
feature_importances_df = pd.DataFrame(data = np.array(feature_importances).T, index = features.columns[np.newaxis].T, columns = ['Importance'])
feature_importances_df = feature_importances_df.sort_values(['Importance'], ascending = False)
print('Top 10 features according to the Random Forest Classifier:')
display(feature_importances_df.iloc[0:10])
# ## Neural Networks (Multi-Layer Perceptron)
clf = MLPClassifier()
clf.get_params()
clf.fit(features, y)
test_pred = clf.predict(test_features)
clf.score(test_features, test_y)
test_preds = test_s.copy()
test_preds['Income'] = test_pred
p_rule([test_preds])
| ML_and_Fairness_Experiments/.ipynb_checkpoints/ML and Fairness Tests - Fair TGAN Model 4-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Comparing weakly constraint network with and without adiabatic terms
# %load_ext autoreload
# %autoreload 2
from cbrain.imports import *
limit_mem()
from cbrain.utils import *
from cbrain.normalization import conversion_dict
from cbrain.data_generator import DataGenerator
from cbrain.model_diagnostics.model_diagnostics import ModelDiagnostics
from tensorflow.python.ops.parallel_for.gradients import jacobian
md3 = ModelDiagnostics('../../nn_config/003_8col_weak.yml', '/local/S.Rasp/preprocessed_data/001_valid.nc')
md3.compute_stats(250)
md4 = ModelDiagnostics('../../nn_config/004_8col_weak_noadiab.yml', '/local/S.Rasp/preprocessed_data/001_valid.nc')
md4.compute_stats(250)
md2 = ModelDiagnostics('../../nn_config/002_8col_strong.yml', '/local/S.Rasp/preprocessed_data/001_valid.nc')
# Get the vertical coordinate in pressure levels
PS = 1e5; P0 = 1e5;
P = P0*hyai+PS*hybi; # Total pressure [Pa]
P = (P[1:] + P[:-1]) / 2 / 100
# + [markdown] heading_collapsed=true
# ## R2 by height
# + hidden=true
cols = sns.color_palette(n_colors=7)
fig, ax = plt.subplots(figsize=(15, 15))
for i, (md, sty) in enumerate(zip([md3, md4], ['-','--'])):
for v, c in zip(md3.valid_gen.output_vars[:7], cols):
if v in md.valid_gen.output_vars:
ax.plot(md.stats['hor_r2'][md.get_output_var_idx(v)], P, label=v+str(i+1), ls=sty, c=c)
ax.set_xlim(0, 1)
ax.invert_yaxis()
plt.legend()
# -
# ## Computing the Jacobian
# https://medium.com/unit8-machine-learning-publication/computing-the-jacobian-matrix-of-a-neural-network-in-python-4f162e5db180
md3.model.summary()
# ### Get mean sounding
X, Y = md3.valid_gen[0]; X.shape
X = md3.reshape_ngeo(np.array(X)); X.shape
Y.shape
plt.matshow(X[:, :, 29])
X_mean = X[30:32].mean((0,1)); X_mean.shape
X_mean_noadiab = md4.reshape_ngeo(np.array(md4.valid_gen[0][0], dtype=np.float32))[30:32].mean((0,1)); X_mean_noadiab.shape
# ### Compute
def get_jacobian(x, model):
sess = tf.keras.backend.get_session()
jac = jacobian(model.output, model.input)
J = sess.run(jac, feed_dict={model.input: x.astype(np.float32)[None]})
return J.squeeze()
J2 = get_jacobian(X_mean, md2.model)
J3 = get_jacobian(X_mean, md3.model)
J4 = get_jacobian(X_mean_noadiab, md4.model)
def plot_jacobian(J, gen, inp_var=None, out_var=None, figsize=(15, 15), ax = None, **kwargs):
inp_vars = gen.norm_ds.var_names[gen.input_idxs].values
out_vars = gen.norm_ds.var_names[gen.output_idxs].values
inp_idxs = np.where(inp_vars == inp_var)[0]
out_idxs = np.where(out_vars == out_var)[0]
j = J[out_idxs][:, inp_idxs]
PP = np.meshgrid(P, P)
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
else:
fig = plt.gcf()
pc = ax.pcolormesh(PP[0], PP[1], j, **kwargs)
ax.invert_xaxis(); ax.invert_yaxis()
fig.colorbar(pc, shrink=0.7, ax=ax)
ax.set_aspect('equal')
ax.set_xlabel(inp_var)
ax.set_ylabel(out_var)
fig, axs = plt.subplots(2, 2, figsize=(15,15))
plot_jacobian(J2, md2.valid_gen, inp_var='QBP', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,0])
plot_jacobian(J2, md2.valid_gen, inp_var='TBP', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,1])
plot_jacobian(J2, md2.valid_gen, inp_var='QBP', out_var='TPHYSTND', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,0])
plot_jacobian(J2, md2.valid_gen, inp_var='TBP', out_var='TPHYSTND', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,1])
plt.suptitle('Strong constraint with adiabatic')
plt.tight_layout()
fig, axs = plt.subplots(2, 2, figsize=(15,15))
plot_jacobian(J3, md3.valid_gen, inp_var='QBP', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,0])
plot_jacobian(J3, md3.valid_gen, inp_var='TBP', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,1])
plot_jacobian(J3, md3.valid_gen, inp_var='QBP', out_var='TPHYSTND', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,0])
plot_jacobian(J3, md3.valid_gen, inp_var='TBP', out_var='TPHYSTND', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,1])
plt.suptitle('Weak constraint with adiabatic')
plt.tight_layout()
fig, axs = plt.subplots(2, 2, figsize=(15,15))
plot_jacobian(J4, md4.valid_gen, inp_var='QBP', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,0])
plot_jacobian(J4, md4.valid_gen, inp_var='TBP', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,1])
plot_jacobian(J4, md4.valid_gen, inp_var='QBP', out_var='TPHYSTND', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,0])
plot_jacobian(J4, md4.valid_gen, inp_var='TBP', out_var='TPHYSTND', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,1])
plt.suptitle('Weak constraint without adiabatic')
plt.tight_layout()
fig, axs = plt.subplots(2, 2, figsize=(15,15))
plot_jacobian(J2, md3.valid_gen, inp_var='Qdt_adiabatic', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,0])
plot_jacobian(J2, md3.valid_gen, inp_var='QCdt_adiabatic', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,1])
plot_jacobian(J2, md3.valid_gen, inp_var='QIdt_adiabatic', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,0])
plot_jacobian(J2, md3.valid_gen, inp_var='Tdt_adiabatic', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,1])
plt.suptitle('Strong constraint with adiabatic')
plt.tight_layout()
fig, axs = plt.subplots(2, 2, figsize=(15,15))
plot_jacobian(J3, md3.valid_gen, inp_var='Qdt_adiabatic', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,0])
plot_jacobian(J3, md3.valid_gen, inp_var='QCdt_adiabatic', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[0,1])
plot_jacobian(J3, md3.valid_gen, inp_var='QIdt_adiabatic', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,0])
plot_jacobian(J3, md3.valid_gen, inp_var='Tdt_adiabatic', out_var='PHQ', cmap='RdBu_r', vmin=-500, vmax=500, ax=axs[1,1])
plt.suptitle('Weak constraint with adiabatic')
plt.tight_layout()
fig, ax = plt.subplots(figsize=(20, 20))
ax.matshow(J, vmin=-500, vmax=500, cmap='RdBu_r')
ax.set_aspect('equal')
plt.xticks(range(md3.valid_gen.n_inputs), md3.valid_gen.norm_ds.var_names[md3.valid_gen.input_idxs].values, rotation=90, fontsize=5);
plt.yticks(range(md3.valid_gen.n_outputs), md3.valid_gen.norm_ds.var_names[md3.valid_gen.output_idxs].values, rotation=0, fontsize=5);
| notebooks/stephans-devlog/5.1-Adiabatic-impact-and-jacobians.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: prediction_utils [conda env:anaconda-prediction_utils] *
# language: python
# name: conda-env-anaconda-prediction_utils-prediction_utils
# ---
# +
import os
import numpy as np
import pandas as pd
import joblib
import sklearn
from scipy.sparse import csr_matrix
# -
data_path = "/share/pi/nigam/projects/sepsis/extraction_201003/"
merged_name = "merged_features_binary"
label_col = "early_sepsis" # use early sepsis as the outcome
random_state = np.random.RandomState(0)
# +
cohort = pd.read_parquet(
os.path.join(data_path, 'cohort', 'cohort_cv.parquet')
)
features = joblib.load(
os.path.join(data_path, merged_name, 'features_sparse', 'features.gz')
)
row_id_map = pd.read_parquet(
os.path.join(data_path, merged_name, 'features_sparse', 'features_row_id_map.parquet')
)
vocab = pd.read_parquet(
os.path.join(data_path, merged_name, 'vocab', 'vocab.parquet')
)
# -
cohort = cohort.merge(row_id_map)
cohort_adult = cohort.query('adult_at_admission == 1')
cohort_pediatric = cohort.query('adult_at_admission == 0')
cohort_train = cohort.query('fold_id != "test" & fold_id != "eval"')
cohort_train_adult = cohort_adult.query('fold_id != "test" & fold_id != "eval"')
cohort_train_pediatric = cohort_pediatric.query('fold_id != "test" & fold_id != "eval"')
features_adult = features[cohort_adult['features_row_id'].values]
features_pediatric = features[cohort_pediatric['features_row_id'].values]
features_train_adult = features[cohort_train_adult['features_row_id'].values]
features_train_pediatric = features[cohort_train_pediatric['features_row_id'].values]
assert features.shape[0] == cohort.shape[0]
assert features_adult.shape[0] == cohort_adult.shape[0]
assert features_pediatric.shape[0] == cohort_pediatric.shape[0]
assert features_train_adult.shape[0] == cohort_train_adult.shape[0]
assert features_train_pediatric.shape[0] == cohort_train_pediatric.shape[0]
coo_train_pediatric = features_train_pediatric.tocoo()
vocab_pediatric_train = pd.DataFrame({'col_id': coo_train_pediatric.col}).drop_duplicates()
vocab_pediatric_train = vocab_pediatric_train.reset_index(drop=True).rename_axis('col_id_new').reset_index()
vocab_pediatric_train
# +
# Map vocabularies across datasets
data_coo = features.tocoo()
data_coo_df = pd.DataFrame({
'row_id': data_coo.row,
'col_id': data_coo.col,
'data': data_coo.data
})
data_coo_df
data_coo_df_mapped = data_coo_df.merge(vocab_pediatric_train)
features_mapped = csr_matrix(
(data_coo_df_mapped.data.values.astype(np.int64),
(data_coo_df_mapped.row_id.values, data_coo_df_mapped.col_id_new.values)
),
shape=(features.shape[0], vocab_pediatric_train.shape[0])
)
# features_peds
# -
result_path = os.path.join(data_path, 'features_mapped_pediatric')
os.makedirs(os.path.join(result_path, 'features_sparse'), exist_ok = True)
os.makedirs(os.path.join(result_path, 'vocab'), exist_ok = True)
joblib.dump(
features_mapped,
os.path.join(result_path, 'features_sparse', 'features.gz')
)
vocab_pediatric_train.to_parquet(
os.path.join(result_path, 'vocab', 'vocab.parquet'), index=False
)
row_id_map.to_parquet(
os.path.join(result_path, 'features_sparse', 'features_row_id_map.parquet'),
index=False
)
| sepsis/notebooks/features_mapped_pediatric.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/yes-G/FussballPrognose/blob/analysis/LeagueAnalysis.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="xrwxT6QPJKR5"
# #Introduction
#
# The idea is find a football team which has managed to repeat its performance across two consequtive seasons in the past 10 years. Not based on the where they finish in their league, but to see if the points they've scored have been consistant.
# + colab={"base_uri": "https://localhost:8080/"} id="LylFMjHRQ3eo" outputId="8bece21e-efd6-4142-afe6-9974683358fd"
# !pip install datapackage
# + id="Z2vAa51IJCcI"
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
from scipy.stats import ttest_ind
# + [markdown] id="3DOLlwLMOtP6"
# # How long ago should i look?
# I will examine the data from the past 10 years, for the Spanish 1st Division Football league - the La Liga. Taken literally, one would imagine the creators of the said league to be very arrogant, because its literally means *The League.* And that implies that there can be no other ;)
#
# Is 10 years too much? too less?
# + [markdown] id="QhcsVjmmQAX5"
# #Datahub
#
# This time instead of scrubbing data from a website, i will use the data from the good folks at datahub.io who make available a large number of datasets.
#
# + id="jyvkv9iMMRc_"
import datapackage
data_url = 'https://datahub.io/sports-data/spanish-la-liga/datapackage.json'
# to load Data Package into storage
package = datapackage.Package(data_url)
# to load only tabular data
resources = package.resources
# + [markdown] id="awfaS0RFdnel"
# The data for all the seasons is colated into one dataframe.
# + id="Hwo1rLoBaOv_"
sources = []
df = None
for resource in resources:
if resource.tabular:
#print(resource.name, resource.descriptor['dpp:streamedFrom'])
if resource.descriptor['dpp:streamedFrom'] not in sources:
sources.append(resource.descriptor['dpp:streamedFrom'])
data = pd.read_csv(resource.descriptor['path'])
data['Season']=resource.name
if df is None:
df = data.copy()
else:
df = pd.concat([df, data])
#print(sources)
#The season name is derived from the name of the csv file, but that is not very
#"user" friendly - looks like season-0910_csv, hence a little clean up is done
#with the code below.
df.Season = df.Season.apply(lambda x: '20'+str.join('-20', #Step2: Add the 2000's qualifier and a - between the two years
re.findall('..', #Step 1: split the string with every 2 digits.
re.sub('[a-z]+|[-_]', '',x))#Step 0. ignore season, csv and the - and _
))
# + [markdown] id="2W__8SYCsYOF"
# #How many teams appear in the dataset and in how many seasons did a team appear in?
#
# From the seasons from 2008-09 upto 2018-19, a total of 35 teams have made an appearance in the *La Liga*. Only 20 teams participate in a season.
# + id="MvgTi1EIZkYi"
Teams = df.HomeTeam.unique().tolist()
Teams.sort()
dfSeason = pd.DataFrame(df.groupby(by='HomeTeam')['Season'].nunique()).reset_index()
# + colab={"base_uri": "https://localhost:8080/", "height": 606} id="ZT5Abl6fr-LJ" outputId="aada1c1e-0b2c-4c9a-dbb5-de1d8f4de95e"
plt.figure(figsize=(10,10));
sns.barplot(x='Season',
y='HomeTeam',
palette='crest',
data=dfSeason.sort_values(by='Season', ascending=False));
x = np.arange(0, 11)
plt.ylabel('Team');
plt.xlabel('# of seasons played in');
plt.grid(color='gainsboro', linestyle='--', linewidth=0.7);
plt.xticks(ticks=x);
# + id="b6yGFD4emj-p"
#onhit wonder teams
oneHitWonderTeams = dfSeason.sort_values(by='Season', ascending=False)
oneHitWonderTeams = oneHitWonderTeams[oneHitWonderTeams.Season == 1].HomeTeam.values
# + [markdown] id="6ZRWeIPyuwSk"
# As shown in the following figure, seven teams have made an appearance in every season - *Real Madrid, Barcelona, Valencia, Sevilla, Espaรฑol, Athletico Mardric*, and *Athletico Bilbao*.
#
# Five teams - *Huesca*, *Tenerife*, *Hercules*, *Cordoba* and *Xerez* - have made an appearance only once. Since, the question i want to answer is that of consistancy, these 5 one-hit wonders will not be in the focus during the analysis.
# + colab={"base_uri": "https://localhost:8080/", "height": 730} id="85y4HM2Z2tRc" outputId="6b88c4f5-30d2-4973-9cb7-c175e373d9c6"
plt.figure(figsize=(12, 12))
sns.heatmap(pd.crosstab(df.HomeTeam, df.Season), linewidths=.5, cmap="YlGnBu", cbar=False);
plt.ylabel('Team');
plt.title('Appearance of teams in seasons');
# + [markdown] id="6jwixDtw1MTA"
# In the above chart, the seasons are plotted on the x-axis and the teams on the y-axis sorted alphabetically. A blue entry marks the appearance of the team in that season. Like captain obvious, this view tells us some teams are not very consistant in their appearance in the League.
# + id="kl0oZaP8iUXH"
cols = ['Season', 'Date', 'HomeTeam', 'AwayTeam', 'FTHG', 'FTAG']
df2 = df[cols].copy()
df2[['SH', 'SA']] = df2.apply(lambda x: [3, 0] if x['FTHG'] > x['FTAG'] else [1, 1] if x['FTHG'] == x['FTAG'] else [0,3], axis=1, result_type='expand')
df2.Date=df2.Date.astype(np.datetime64)
# + id="EuMcS8xJEOPn"
def PointsEverySeason(data, team):
"""compute point for the team in all the """
points = None
for season in data.Season.unique():
sH = data[(data.Season == season) & (data.HomeTeam==team)].copy()
sH['Points']=sH.SH
sA = data[(data.Season == season) & (data.AwayTeam==team)].copy()
sA['Points']=sA.SA
s = pd.merge(sH, sA, how='outer').sort_values(by='Date', ascending=True).reset_index(drop=True).reset_index()
#s.Points = s.Points.cumsum()
s['MatchDay']=s['index']+1
s.drop(['index'], axis=1, inplace=True)
if points is None:
points = s.copy()
else:
points = points.append(s, ignore_index=True)
return points
#display(points.head())
#display(points.shape)
# + id="WRuDNj_mwU__"
#Compute back-to-back seasons
def IdentifyBackToBackSeasons(data, team):
seasons = data[data.HomeTeam==team].Season.unique();
backToBack = []
for i, val in enumerate(seasons[:-1]):
s1 = str.split(seasons[i],'-')
s2 = str.split(seasons[i+1], '-')
if s1[0]==s2[1]:
#print(i, val, seasons[i], seasons[i+1])
backToBack.insert(0, [seasons[i], seasons[i+1]])
return backToBack
# + id="Kr5Qsg_Hx5Nr"
teams = df2.HomeTeam.unique()
teams.sort()
similarStories = []
seasonEndPoints=pd.DataFrame()
for team in teams:
points = PointsEverySeason(df2, team)
#seasonEndPoints
for s in points.Season.unique():
seasonEndPoints=seasonEndPoints.append({'Team':team,'Season':s,'Points':points[(points.Season == s)].Points.cumsum().values[-1]},
ignore_index=True)
#Back To Back seasons, with similar points
backToBack = IdentifyBackToBackSeasons(df2, team)
for i, v in enumerate(backToBack,1):
p1 = points[points.Season==v[0]].copy().reset_index(drop=True)
p2 = points[points.Season==v[1]].copy().reset_index(drop=True)
p1['PointsC'] = p1.Points.cumsum()
p2['PointsC'] = p2.Points.cumsum()
#There is really no need for a t-test here, one could just looks at the final scores and determine if they are close to each other or not.
s, p = ttest_ind(p2.Points, p1.Points)
if p > 0.90:
pairPoints = pd.concat([p1, p2],ignore_index=True)
similarStories.insert(0, {'Team':team,'season0':v[0],'season1':v[1],'p-value':p, 'data':pairPoints})
# + colab={"base_uri": "https://localhost:8080/", "height": 893} id="CHJ4UHjs5nDV" outputId="8a4130cf-6bb6-49a3-c5fc-cbadefbc99b7"
#plot the box plot of all teams which have appreared more than once in the League
plt.figure(figsize=(15, 15));
plt.grid(color='gainsboro', linestyle='--', linewidth=0.7);
medianScoreOrder = seasonEndPoints[~seasonEndPoints.Team.isin(oneHitWonderTeams)].groupby(by=["Team"])["Points"].median().sort_values(ascending=False).index
sns.boxplot(data=seasonEndPoints[~seasonEndPoints.Team.isin(oneHitWonderTeams)], x='Points', y='Team', order=medianScoreOrder);
sns.swarmplot(data=seasonEndPoints[~seasonEndPoints.Team.isin(oneHitWonderTeams)], x='Points', y='Team',color=".25", order=medianScoreOrder);
plt.title('Distribuation of points accumulated by team in a season');
# + [markdown] id="a2k6p3uG54hI"
# The above boxplot shows the dominance of Barcelona and Real Madrid in the League. They are on average almost 20 points away from the average of the 3rd placed team and almost 30 points away from the average of the 4th placed team.
#
# From the super-imposed swarm plot, it can be seen that there are multiple instances where a team has scored equal or very similar points in two or more seasons.
# + colab={"base_uri": "https://localhost:8080/", "height": 404} id="3Kf48HF498w4" outputId="ff5dbdbb-e21f-4608-956e-55191ad85f3b"
dfStories = pd.DataFrame(similarStories)
perSeasonSimilarity=dfStories.groupby(by='season0').count().reset_index()
plt.figure(figsize=(10,6));
sns.barplot(data=perSeasonSimilarity,x='Team', y='season0', palette='crest');
x = np.arange(1, max(perSeasonSimilarity.Team)+2)
plt.xticks(ticks=x);
plt.grid(color='gainsboro', linestyle='--', linewidth=0.7)
plt.ylabel('Season');
plt.xlabel('Number of teams');
plt.title('Number of teams with very similar points compared to previous season');
# + colab={"base_uri": "https://localhost:8080/", "height": 404} id="-TA55xssAkPc" outputId="069eca0a-1cc0-4bb2-b3f9-19342e2b0863"
dfStories = pd.DataFrame(similarStories)
perSeasonSimilarity=dfStories.groupby(by='Team').count().reset_index()
plt.figure(figsize=(10,6));
sns.barplot(data=perSeasonSimilarity,y='Team', x='season0', palette='crest');
x = np.arange(1, max(perSeasonSimilarity.season0)+2)
plt.xticks(ticks=x);
plt.xlabel('Number of Seasons');
plt.grid(color='gainsboro', linestyle='--', linewidth=0.7);
plt.title('Number of times a team has scored similar points compared to previous season');
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="nBrBxQrV2tIJ" outputId="29515070-83c4-46f1-b148-a6a07f66963f"
similarStories = sorted(similarStories, key=lambda d: d['season0'])
N = len(similarStories)
R = int(N/2)+1
plt.figure(figsize=(20,R*7));
x = np.arange(1,39)
for i,story in enumerate(similarStories,1):
plt.subplot(R,2,i)
sns.lineplot(y=story['data'].PointsC, x=story['data'].MatchDay, hue=story['data'].Season);
plt.grid(color='gainsboro', linestyle='--', linewidth=0.7);
plt.xticks(ticks=x);
plt.title(f'{story["Team"]} in seasons {story["season0"]} and {story["season1"]}')
# + id="bUwznkSljpi0"
| LeagueAnalysis.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: keras35
# language: python
# name: keras35
# ---
# # Tutorial-LSTM: Project for testing LSTM time series forecasting
# **Notebook number 1/2**
#
# This first notebook shows a simple project as executed usually without deep learning template structure.
# The second notebook will explain how to convert this project into a deep learning template style project.
#
# This is a short deep learning tutorial to show how to implement LSTM time series forecasting using the cookiecutter Deep Learning template: https://github.com/tdeboissiere/cookiecutter-deeplearning
#
# This template is very flexible and clear, but sometimes is not evidence for inexperienced programmer nor deep learning beginners how to use it.
#
# The exemple code comes from: https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/ (all credit for the author,<NAME>, please read him for details). Here only implement his code with minor changes. We rename files and variables just following the template example notation. Also, this notation is very often used in Keras documentation. So we prefer to notate the X train matrix as "X_train" and not "Train_X".
#
#
# # Tutorial-LSTM
# To make the code reproducible.
# %load_ext watermark
# %watermark -a 'Ram' -u -d -p numpy,scipy,matplotlib,sklearn
# # 1. Air Pollution Forecasting
# This is a dataset reports on the weather and the level of pollution each hour for five years at the US embassy in Beijing, China.
#
# The data includes the date-time, the pollution called PM2.5 concentration, and the weather information including dew point, temperature, pressure, wind direction, wind speed and the cumulative number of hours of snow and rain. The complete feature (attributes) list in the raw data is as follows:
#
#
# No: row number
# year: year of data in this row
# month: month of data in this row
# day: day of data in this row
# hour: hour of data in this row
# pm2.5: PM2.5 concentration
# DEWP: Dew Point
# TEMP: Temperature
# PRES: Pressure
# cbwd: Combined wind direction
# Iws: Cumulated wind speed
# Is: Cumulated hours of snow
# Ir: Cumulated hours of rain
#
#
#
# You can download the dataset from the UCI Machine Learning Repository.
#
# [Beijing PM2.5 Data Set:](https://archive.ics.uci.edu/ml/datasets/Beijing+PM2.5+Data)
#
# Download the dataset and place it in your current working directory with the filename โraw.csvโ.
#
# # 2. Basic Data Preparation
from pandas import read_csv
from datetime import datetime
# load data
def parse(x):
return datetime.strptime(x, '%Y %m %d %H')
dataset = read_csv('raw.csv', parse_dates = [['year', 'month', 'day', 'hour']], index_col=0, date_parser=parse)
dataset.drop('No', axis=1, inplace=True)
# manually specify column names
dataset.columns = ['pollution', 'dew', 'temp', 'press', 'wnd_dir', 'wnd_spd', 'snow', 'rain']
dataset.index.name = 'date'
# mark all NA values with 0
dataset['pollution'].fillna(0, inplace=True)
# drop the first 24 hours
dataset = dataset[24:]
# summarize first 5 rows
print(dataset.head(5))
# save to file
dataset.to_csv('pollution.csv')
from pandas import read_csv
from matplotlib import pyplot
# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# specify columns to plot
groups = [0, 1, 2, 3, 5, 6, 7]
i = 1
# plot each column
pyplot.figure()
for group in groups:
pyplot.subplot(len(groups), 1, i)
pyplot.plot(values[:, group])
pyplot.title(dataset.columns[group], y=0.5, loc='right')
i += 1
pyplot.show()
# # 3. Multivariate LSTM Forecast Model
# ## LSTM Data Preparation
# +
# convert series to supervised learning
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
n_vars = 1 if type(data) is list else data.shape[1]
df = DataFrame(data)
cols, names = list(), list()
# input sequence (t-n, ... t-1)
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
# forecast sequence (t, t+1, ... t+n)
for i in range(0, n_out):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
else:
names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
# put it all together
agg = concat(cols, axis=1)
agg.columns = names
# drop rows with NaN values
if dropnan:
agg.dropna(inplace=True)
return agg
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,4] = encoder.fit_transform(values[:,4])
# ensure all data is float
values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# frame as supervised learning
reframed = series_to_supervised(scaled, 1, 1)
# drop columns we don't want to predict
reframed.drop(reframed.columns[[9,10,11,12,13,14,15]], axis=1, inplace=True)
print(reframed.head())
# -
# ## Define and Fit Model
# split into train and test sets
values = reframed.values
n_years = 1
n_train_hours = 365 * 24 * n_years
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]
# split into input and outputs
X_train, y_train = train[:, :-1], train[:, -1]
X_test, y_test = test[:, :-1], test[:, -1]
# reshape input to be 3D [samples, timesteps, features]
X_train = X_train.reshape((X_train.shape[0], 1, X_train.shape[1]))
X_test = X_test.reshape((X_test.shape[0], 1, X_test.shape[1]))
print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
# +
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
# design network
model = Sequential()
model.add(LSTM(50, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(X_train, y_train, epochs=50, batch_size=72, validation_data=(X_test, y_test), verbose=2, shuffle=False)
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
# -
# # Evaluate Model
# +
from math import sqrt
from numpy import concatenate
from sklearn.metrics import mean_squared_error
# make a prediction
yhat = model.predict(X_test)
X_test = X_test.reshape((X_test.shape[0], X_test.shape[2]))
# invert scaling for forecast
yhat_inv = concatenate((yhat, X_test[:, 1:]), axis=1)
yhat_inv = scaler.inverse_transform(yhat_inv)
yhat_inv = yhat_inv[:,0]
# invert scaling for actual
y_test = y_test.reshape((len(y_test), 1))
y_inv = concatenate((y_test, X_test[:, 1:]), axis=1)
y_inv = scaler.inverse_transform(y_inv)
y_inv = y_inv[:,0]
# calculate RMSE
rmse = sqrt(mean_squared_error(y_inv, yhat_inv))
print('Test RMSE: %.3f' % rmse)
y_test
# -
| notebooks/1.0-ram-tutorial-LSTM-notebook-number-1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + id="IMa7Nw31ha1L" colab_type="code" colab={}
from warnings import simplefilter
simplefilter(action='ignore', category=FutureWarning)
# + id="gzZAs7lOjer1" colab_type="code" colab={}
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import pickle as pkl
import math
import csv
import sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn import preprocessing
from sklearn.metrics import classification_report
from imblearn.over_sampling import RandomOverSampler
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
from imblearn.under_sampling import NearMiss
from collections import Counter
# + id="KwTAPKGvjez6" colab_type="code" colab={}
# !pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# + id="kdPfIO_0je2n" colab_type="code" colab={}
link = 'https://drive.google.com/open?id=17DbBIxtBcBM9Q4MWbeF46ml8WNv_ATKl'
fluff, id = link.split('=')
# + id="ayi8mAslje5e" colab_type="code" colab={}
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# + id="f7s6cQybje8K" colab_type="code" colab={}
downloaded = drive.CreateFile({'id':id})
downloaded.GetContentFile('Flight_Weather.csv')
dataframe = pd.read_csv('Flight_Weather.csv')
# + id="9p5_ZtllwLZd" colab_type="code" colab={}
data_label_encoder = preprocessing.LabelEncoder()
encoded_list = data_label_encoder.fit_transform(dataframe['Airport'])
dataframe['EncodedAirport'] = encoded_list
# + id="DdQaobQDje_C" colab_type="code" colab={}
y = dataframe['ArrDel15']
dataframe = dataframe.drop(['ArrDel15','FlightDate','Date','Airport','ArrDelayMinutes'],axis = 1)
X = dataframe
# + id="xpmnP23hjfEt" colab_type="code" colab={}
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
# + id="FPr6pXyWjfM7" colab_type="code" outputId="3bcda283-3108-4fe7-b35c-1c39f1ddbfcc" colab={"base_uri": "https://localhost:8080/", "height": 68}
print(" Original DataSet Shape : ",Counter(y_train))
ros = RandomOverSampler(random_state = 42)
X_ros, y_ros = ros.fit_resample(X_train, y_train)
print(" RandomOverSampled DataSet Shape : ",Counter(y_ros))
smote = SMOTE(random_state = 42)
X_smote, y_smote = smote.fit_resample(X_train, y_train)
print(" SMOTE DataSet Shape : ",Counter(y_smote))
# + id="ziIufdW7jfQB" colab_type="code" outputId="ae8a25de-672e-42b2-9f55-30a8ded70e10" colab={"base_uri": "https://localhost:8080/", "height": 68}
print(" Original DataSet Shape : ",Counter(y_train))
rus = RandomUnderSampler(random_state = 42)
X_rus, y_rus = rus.fit_resample(X_train,y_train)
print(" RandomUnderampled DataSet Shape : ",Counter(y_rus))
nm = NearMiss()
X_nm, y_nm = nm.fit_resample(X_train, y_train)
print(" NearMiss DataSet Shape : ",Counter(y_nm))
# + id="Z8DDmuaCjfS9" colab_type="code" colab={}
clf = RandomForestClassifier(n_estimators = 100)
# + id="Tei9UrNQ_4FM" colab_type="code" outputId="f6361ded-1f5b-4d1e-d545-a8be7cbf14d5" colab={"base_uri": "https://localhost:8080/", "height": 237}
clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)
filename = "RFC_Normal.pkl"
pkl.dump(clf,open(filename,'wb'))
print(" Classification Report ")
print("\n\n")
print(metrics.classification_report(y_test,y_pred))
# + id="f52yGEuhjfV2" colab_type="code" outputId="66b18236-d5b2-4d57-bd27-84e1d4f5708a" colab={"base_uri": "https://localhost:8080/", "height": 237}
clf.fit(X_ros,y_ros)
y_pred_ros = clf.predict(X_test)
filename = "RFC_ROS.pkl"
pkl.dump(clf,open(filename,'wb'))
print(" Classification Report ")
print("\n\n")
print(metrics.classification_report(y_test,y_pred_ros))
# + id="CdoK0cVGjfZJ" colab_type="code" outputId="0898239c-85b9-413b-9630-a31a6a144873" colab={"base_uri": "https://localhost:8080/", "height": 237}
clf.fit(X_smote,y_smote)
y_pred_smote = clf.predict(X_test)
filename = "RFC_SMOTE.pkl"
pkl.dump(clf,open(filename,'wb'))
print(" Classification Report")
print("\n\n")
print(metrics.classification_report(y_test,y_pred_smote))
# + id="VLQiBssHjfKX" colab_type="code" outputId="6653bb73-f248-4469-aca6-5bc6f2ace5bc" colab={"base_uri": "https://localhost:8080/", "height": 237}
clf.fit(X_rus,y_rus)
y_pred_rus = clf.predict(X_test)
filename = "RFC_RUS.pkl"
pkl.dump(clf,open(filename,'wb'))
print(" Classification Report")
print("\n\n")
print(metrics.classification_report(y_test,y_pred_rus))
# + id="SO3h9u9djfJG" colab_type="code" outputId="921cdfac-5f68-4af0-fb55-d27c924036ef" colab={"base_uri": "https://localhost:8080/", "height": 237}
clf.fit(X_nm,y_nm)
y_pred_nm = clf.predict(X_test)
filename = "RFC_NM.pkl"
pkl.dump(clf,open(filename,'wb'))
print(" Classification Report")
print("\n\n")
print(metrics.classification_report(y_test,y_pred_nm))
| MLProjectRandomForestClassifieripynb.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import pickle #Mรณdulo para almacenar colecciones y ficheros binarios
import scipy.stats #Contiene mรณdulos para optimizaciรณn, รกlgebra lineal, inegraciรณn, interpolaciรณn, funciones etc.
import numpy as np #Librerรญa para crear vectores y matrices
import pandas as pd #Librerรญa para leer ficheros tipo CSV, Excel y bases de datos SQL.
pd.set_option('display.max_columns', None) #Aรฑadir la totalidad de las columnas del dataset
#y no distingir entre minรบsculas y mayรบsculas
import matplotlib as mpl #Mรณdulo para generar grรกficos
from sklearn import svm #Mรณdulo para aรฑadir algoritmo de clasificaciรณn y regresiรณn
from sklearn import ensemble
from matplotlib import pyplot as plt
from sklearn.metrics import r2_score, mean_absolute_error #Mรณdulo que incluye las mรฉtricas con las que se va a operar
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import OneHotEncoder #Mรณdulo para el preprocesamiento (entrenamiento) de m. predictivos
from sklearn.tree import DecisionTreeClassifier #Mรณdulo que permite entrenar รกrboles de decisiรณn para problemas de
#clasificaciรณn
from sklearn.linear_model import LinearRegression #Mรณdulo para interpretar modelos de regresiรณn lineal
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score, train_test_split, validation_curve #Mรณdulo para ejecutar varias
#mรฉtricas y cรกlculos (ejemplo: tiempos de ajuste...)
from statsmodels.tsa.statespace.sarimax import SARIMAX #Mรณdulo para ejecutar el modelo SARIMA
from statsmodels.graphics.tsaplots import plot_pacf, plot_acf #Mรณdulo para ejecutar grรกficos y correlaciones.
# %matplotlib inline
# -
df = pd.read_csv('TGN.csv')
print("Number of rows and columns:", df.shape)
print("Column names:", list(df.columns))
df.head(3)
df["data"] = pd.to_datetime(df["data"])
df.sort_values("data", inplace=True)
df.head(3)
colNs_hourly_measurements = ["h%02d" % h for h in range(1,25)]
print(colNs_hourly_measurements)
df["mean_day"] = df[colNs_hourly_measurements].mean(axis=1)
df[["data", "mean_day"] + colNs_hourly_measurements].head()
print("Number of rows before:", df.shape[0])
df = df[df[colNs_hourly_measurements].isna().sum(axis=1)<5]
print("Number of rows after:", df.shape[0])
data = df[["data", "mean_day"]].set_index("data")
data.plot(figsize=(15, 5));
data = df[["data", "mean_day"]].set_index("data").resample("1M").mean()
data.plot(figsize=(15, 5))
date_min_test = "2018-01-01"
TEST_SIZE = len(data[data.index>=date_min_test])
train, test = data.iloc[:-TEST_SIZE], data.iloc[-TEST_SIZE:]
x_train, x_test = np.array(range(train.shape[0])), np.array(range(train.shape[0], data.shape[0]))
train.shape, x_train.shape, test.shape, x_test.shape
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(x_train, train)
ax.plot(x_test, test);
# +
# transformacion exponencial
transExpo = np.exp(train['mean_day'])
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(transExpo)
# +
# transformaciรณn raiz
trnasSq = np.sqrt(train['mean_day'])
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(trnasSq)
# +
#transformaciรณn logaritmica
data["log_ret"] = np.log(data['mean_day'])
data1 = data[["log_ret"]]
train, test = data1.iloc[:-TEST_SIZE], data1.iloc[-TEST_SIZE:]
x_train, x_test = np.array(range(train.shape[0])), np.array(range(train.shape[0], data1.shape[0]))
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(x_train, train)
ax.plot(x_test, test)
# +
train = train.fillna(train.mean())
X = x_train
X = np.reshape(X, (len(X), 1))
y = train["log_ret"].tolist()
model = LinearRegression()
model.fit(X, y)
trend = model.predict(X)
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(x_train, trend)
ax.plot(x_test, test)
ax.plot(x_train, train)
# -
detrended = [y[i]-trend[i] for i in range(0, len(train))]
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(detrended)
for i in range(1, len(train["log_ret"].tolist())-1):
edited = detrended[i:]
original = train["log_ret"].tolist()[:-i]
r = np.corrcoef(edited, original)
print("--------------------------")
print("serie "+str(i))
print(r)
plot_pacf(train)
plt.show()
plot_acf(train)
plt.show()
my_order =(4, 0, 6)
my_seasonal_order = (4, 0, 6, 10)
model = SARIMAX(detrended, order = my_order, seasonal_order=my_seasonal_order)
results = model.fit()
print(results.summary())
# +
pred_u2 = results.get_forecast(steps=len(train))
actual = detrended
forecasted_EtEs = pred_u2.predicted_mean
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(x_train, detrended, label="Training")
ax.plot(x_train, forecasted_EtEs, label="Forecasted")
ax.legend()
plt.draw()
# +
pred_u3 = results.get_forecast(steps=len(test))
actual = detrended
forecasted_last = pred_u3.predicted_mean
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(x_train, detrended, label="Training")
ax.plot(x_test, forecasted_last, label="Forecasted")
ax.legend()
plt.show()
# -
my_order =(4, 0, 6)
my_seasonal_order = (4, 0, 6, 10)
model = SARIMAX(train["log_ret"].tolist(), order = my_order, seasonal_order=my_seasonal_order)
results = model.fit()
print(results.summary())
# +
pred_u3 = results.get_forecast(steps=len(test))
actual = detrended
forecasted = pred_u3.predicted_mean
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(x_train, train, label="Training")
ax.plot(x_test, test, label="Test")
ax.plot(x_test, forecasted, label="Forecasted")
ax.legend()
plt.show()
# +
mae = mean_absolute_error(test, forecasted)
print('MAE: %f' % mae)
r2 = r2_score(test, forecasted)
print('R2: %f' % r2)
# +
data2 = df[["data", "mean_day"]].set_index("data").resample("1M").mean()
train, test = data2.iloc[:-TEST_SIZE], data2.iloc[-TEST_SIZE:]
x_train, x_test = np.array(range(train.shape[0])), np.array(range(train.shape[0], data2.shape[0]))
my_order =(4, 0, 6)
my_seasonal_order = (4, 0, 6, 10)
model = SARIMAX(train["mean_day"].tolist(), order = my_order, seasonal_order=my_seasonal_order)
results = model.fit()
print(results.summary())
# +
pred_u3 = results.get_forecast(steps=len(train))
actual = detrended
forecasted = pred_u3.predicted_mean
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(x_train, train, label="Training")
ax.plot(x_train, forecasted, label="Forecasted")
ax.legend()
plt.show()
# +
pred_u3 = results.get_forecast(steps=len(test))
forecasted = pred_u3.predicted_mean
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(x_train, train, label="Training")
ax.plot(x_test, test, label="Test")
ax.plot(x_test, forecasted, label="Forecasted")
ax.legend()
plt.show()
# +
mae = mean_absolute_error(test, forecasted)
print('MAE: %f' % mae)
r2 = r2_score(test, forecasted)
print('R2: %f' % r2)
# -
| Predicciones Tarragona.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import websocket, json
import pandas as pd
import os
import pickle, codecs
import asyncio
import nest_asyncio
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn import svm
# + pycharm={"name": "#%%\n"}
df = pd.read_csv('Biscotti_italia.csv')
df.reset_index(inplace=True, drop=False)
# -
#Encodes the dataframe obj into bytes and then into a string
pickled = codecs.encode(pickle.dumps(df), "base64").decode()
#Takes the string and runs an undo over the procedure which we have just done
unpickled = pickle.loads(codecs.decode(pickled.encode(), "base64"))
import seaborn as sns
df = sns.load_dataset('iris')
X = df.drop('species', axis=1).values
y = df['species'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42)
# + pycharm={"name": "#%%\n"}
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
svc = svm.SVC()
clf = GridSearchCV(svc, parameters)
clf.fit(X, y)
# -
clf.best_params_
X_train_pickled = codecs.encode(pickle.dumps(X_train), "base64").decode()
X_test_pickled = codecs.encode(pickle.dumps(X_test), "base64").decode()
y_train_pickled = codecs.encode(pickle.dumps(y_train), "base64").decode()
y_test_pickled = codecs.encode(pickle.dumps(y_test), "base64").decode()
ws = websocket.WebSocket()
ws.connect('ws://localhost:8000/ws/computing/')
payload = {
"metadata": {
"worker_node": 'a',
"inquiring_node": 'b',
"start_time": 'c',
"max_cpu_allowed": .67,
"timeout_boundary": 10,
"task_type": 'a',
},
"data": {
"X": X_train_pickled,
"y": y_train_pickled,
},
"instructions": {
"code" : 'i',
"algorithm_name":'random_forest',
"param_grid":{'n_estimators': [5, 10, 50, 100], 'criterion': ['giny', 'entropy']},
},
}
# !pip3 install websockets
# !pip3 install nest-asyncio
nest_asyncio.apply()
# +
# #!/usr/bin/env python
async def send_data():
async with websockets.connect('ws://192.168.1.227:8000/ws/computing/') as websocket:
pp = json.dumps(payload).encode('utf-8')
await websocket.send(pp)
response = await websocket.recv()
print(response)
r = asyncio.get_event_loop().run_until_complete(send_data())
# -
| WebsocketTesting.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: kiteconnect
# language: python
# name: kiteconnect
# ---
# %reload_ext dotenv
# %dotenv
# +
# %env LOGLEVEL=INFO
# %load_ext autoreload
# %autoreload 2
# +
import os, logging
import json
print(os.getenv("LOGLEVEL"))
# logging.basicConfig(level=os.environ.get("LOGLEVEL", "WARNING").upper())
log = logging.getLogger("portfolio-transactions")
log.setLevel(os.environ.get("LOGLEVEL", "WARNING").upper())
# -
import sys
print(sys.path)
# ## References
#
# 1. [Kite Connect 3 / API documentation](https://kite.trade/docs/connect/v3/)
# - [The Kite Connect API Python client - v3](https://github.com/zerodhatech/pykiteconnect/)
# - [developers.kite.trade console](https://developers.kite.trade/apps)
# 2. [zerodhatech on github](https://github.com/zerodhatech)
# 1. [Calculating Implied volatility](https://medium.com/pythoptions/calculate-implied-volatility-or-any-options-greek-in-just-3-lines-in-python-f251e77d1e24)
# - [mibian](http://code.mibian.net/) library
# 2. Google search
# - [candlestick charts with jscharts](https://www.google.com/search?q=candlestick+charts+with+jscharts&oq=candlestick+charts+with+jscharts&aqs=chrome..69i57.7466j0j1&sourceid=chrome&ie=UTF-8)
# - [create dynamic Candlestick Charts](https://www.google.com/search?q=create+dynamic+Candlestick+Charts&oq=create+dynamic+Candlestick+Charts&aqs=chrome..69i57.353j0j1&sourceid=chrome&ie=UTF-8)
# - [highcharts streaming data](https://www.google.com/search?q=highcharts+streaming+data&oq=highcharts+strea&aqs=chrome.0.0j69i57j0l2.8401j0j1&sourceid=chrome&ie=UTF-8)
# - [fastify-websocket example](https://www.google.com/search?q=fastify-websocket+example&oq=fastify+websocket+&aqs=chrome.1.69i57j0.7687j0j1&sourceid=chrome&ie=UTF-8)
# 3. Building candlestick charts dynamically
# - [Ploting candlestick](https://plotly.com/python/candlestick-charts/)
# - [Hands-On Guide To Using YFinance API In Python](https://analyticsindiamag.com/hands-on-guide-to-using-yfinance-api-in-python/)
# - [techanjs.org](http://techanjs.org/) - A visual, stock charting (Candlestick, OHLC, indicators) and technical analysis library built on D3.
# - [anychart](https://www.anychart.com/products/anystock/overview/)
# - [jscharting - finance-stock/candlestick](https://jscharting.com/examples/chart-types/finance-stock/candlestick/)
# - [Google Charts - Candlestick Charts](https://developers.google.com/chart/interactive/docs/gallery/candlestickchart) - [tutorial](https://www.wikitechy.com/tutorials/google-charts/google-charts-candlestick-charts)
# - [canvasjs JavaScript Candlestick Charts & Graphs](https://canvasjs.com/javascript-candlestick-chart/)
# - [chart.js](https://www.chartjs.org/samples/latest/)
# - [scale - timeseries](https://www.chartjs.org/samples/latest/scales/time/financial.html)
# - [udemy course](https://www.udemy.com/course/chart-js/)
# - Highcharts
# - [Live data mechanism](https://www.highcharts.com/docs/working-with-data/live-data)
# - https://jsfiddle.net/BlackLabel/uparh9xo/
# = [Highcharts stock demo](https://www.highcharts.com/demo/stock/stock-tools-gui)
# - [Highcharts Stocks](https://www.highcharts.com/blog/products/stock/) - High-performance financial charting library
# - [Highcharts stocks developer license](https://shop.highsoft.com/developer-license)
# - [candlestick](https://www.highcharts.com/demo/stock/candlestick)
# - [dynamic updates](https://www.highcharts.com/stock/demo/dynamic-update)
# - https://www.highcharts.com/demo/dynamic-update
# - https://jsfiddle.net/BlackLabel/evypfr1L/
# - [TradingView Financial HTML5 Charts](https://www.tradingview.com/HTML5-stock-forex-bitcoin-charting-library/)
# - [charting examples](https://github.com/tradingview/charting-library-examples)
# - [lightweight-charts](https://github.com/tradingview/lightweight-charts)
# - [TradingView JS API Integration Tutorial](https://medium.com/@jonchurch/tradingview-js-api-integration-tutorial-introduction-5e4809d9ef36)
# - [TradingView Charting Library JS API Setup for Crypto](https://medium.com/@jonchurch/tradingview-charting-library-js-api-setup-for-crypto-part-1-57e37f5b3d5a)
# - [TradingView Charting Library Tutorial](https://github.com/tradingview/charting-library-tutorial)
# - [TradingView Charting Library Integration Examples](https://github.com/tradingview/charting-library-examples)
# - [Awesome TradingView](https://github.com/tradingview/awesome-tradingview)
# 3. [similartech.com charting](https://www.similartech.com/categories/charting)
# - [similartech.com/compare/highcharts-vs-tradingview-charting-library](https://www.similartech.com/compare/highcharts-vs-tradingview-charting-library)
# 4. Tick data transformations
# - [Forming Candles in python using Zerodha Websocket](http://ezeetrading.in/Articles/Candles_formation_from_tick_data_zerodha.html)
# - [youtube - Converting WebSocket Streaming Data into OHLC/Candle(https://github.com/tradingview/charting-library-examples)1m,3m,5m,15m,30m,60m,1D) Data](https://www.youtube.com/watch?v=LUvb6XwEc1U)
# - https://gist.github.com/oldmonkABA/f73f5d67bcf85316ac0470919bf54e17
# - https://kite.trade/forum/discussion/6230/program-for-converting-tick-data-into-candlestick-data#latest
# 5. Stream
# - Fastify ecosystem with websockets
# 6. [jsonformatter.org](https://jsonformatter.org/)
#
# **script3 takes the list of dicts per instrument, one at a time and converts it into ohlc as follows:**
# source: https://kite.trade/forum/discussion/2604/convert-ticks-to-candle#latest
#
# ```python
# import pandas.
# pd2 = pandas.DataFrame( instrument1 )
# ticks = pd2.ix[:, [ 'ltp' , 'volume' ] ]
# priceOHLCV = ticks.ltp.resample( '1min' ).ohlc()
# candledata = priceOHLCV.to_csv() # converts the pandas dataframe candle data to csv format written to db which can be easily processed further.
# ```
#
# ### Highcharts
#
# simplest way to make your chart is to use series.removePoint option before you are using series.addPoint.
# http://api.highcharts.com/highstock#Series.addPoint
# http://api.highcharts.com/highstock#Series.removePoint
#
# Here you can see simple example how it can work:
# http://jsfiddle.net/turgya55/3/
#
# You can also use Series.setData, but I don't think that this will be better idea:
# http://api.highcharts.com/highstock#Series.setData
#
#
#
# ### cronjob
#
# ```cron
# 45 03 * * 1-5 /home/harjeet/options-charts/bin/option_charts.sh
# ```
from kiteconnect import KiteConnect
API_KEY = os.getenv("API_KEY")
API_SECRET = os.getenv("API_SECRET")
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
# ## Getting Access Token
#
# Source: https://kite.zerodha.com/connect/login?v=3&api_key=xxx
# !echo "https://kite.zerodha.com/connect/login?v=3&api_key=$API_KEY"
# !echo $ACCESS_TOKEN
# +
request_token = "<KEY>"
def get_access_token():
kite = KiteConnect(api_key=os.getenv("API_KEY")) # api_key is in above url
data = kite.generate_session(request_token, os.getenv("API_SECRET"))
access_token = data["access_token"]
return access_token
# get_access_token()
# -
# ```sh
# curl "https://api.kite.trade/instruments" \
# -H "X-Kite-Version: 3" \
# -H "Authorization: token $API_KEY:$ACCESS_TOKEN"
#
#
# curl "https://api.kite.trade/instruments/historical/5633/minute?from=2020-10-28+09:30:00&to=2020-11-01+10:30:00"
# -H "X-Kite-Version: 3" \
# -H "Authorization: token $API_KEY:$ACCESS_TOKEN" \
# ```
# !curl "https://api.kite.trade/instruments" \
# -H "X-Kite-Version: 3" \
# -H "Authorization: token $API_KEY:$ACCESS_TOKEN"
# !pip list
# ## Get Tick
instruments = [12219650, 12219906]
# +
import logging
from kiteconnect import KiteTicker
logging.basicConfig(level=logging.DEBUG)
# Initialise
# kws = KiteTicker("your_api_key", "your_access_token")
kws = KiteTicker(API_KEY, ACCESS_TOKEN)
def on_ticks(ws, ticks):
# Callback to receive ticks.
# on json.dumps
# TypeError: Object of type datetime is not JSON serializable formatting issue on datetime object
# http://127.0.0.1:7777/?token=<KEY>
logging.debug("Ticks: {}".format(json.dumps(ticks, indent=4, default=str)))
def on_connect(ws, response):
# Callback on successful connect.
# Subscribe to a list of instrument_tokens (RELIANCE and ACC here).
# ws.subscribe([738561, 5633])
ws.subscribe(instruments)
# Set RELIANCE to tick in `full` mode.
# ws.set_mode(ws.MODE_FULL, [738561])
ws.set_mode(ws.MODE_FULL, instruments)
def on_close(ws, code, reason):
# On connection close stop the main loop
# Reconnection will not happen after executing `ws.stop()`
ws.stop()
# Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
# -
# ```json
# DEBUG:root:Ticks: [{'tradable': True, 'mode': 'quote', 'instrument_token': 12219650, 'last_price': 212.9, 'last_quantity': 75, 'average_price': 227.14, 'volume': 1348650, 'buy_quantity': 61500, 'sell_quantity': 67575, 'ohlc': {'open': 265.1, 'high': 268.3, 'low': 205.05, 'close': 264.15}, 'change': -19.401855006625016}, {'tradable': True, 'mode': 'quote', 'instrument_token': 12219906, 'last_price': 272.65, 'last_quantity': 75, 'average_price': 267.43, 'volume': 92700, 'buy_quantity': 58350, 'sell_quantity': 45750, 'ohlc': {'open': 269.6, 'high': 294.15, 'low': 235.05, 'close': 262.5}, 'change': 3.866666666666658}]
# DEBUG:root:Ticks: [{'tradable': True, 'mode': 'quote', 'instrument_token': 12219906, 'last_price': 272.65, 'last_quantity': 75, 'average_price': 267.43, 'volume': 92700, 'buy_quantity': 57000, 'sell_quantity': 47025, 'ohlc': {'open': 269.6, 'high': 294.15, 'low': 235.05, 'close': 262.5}, 'change': 3.866666666666658}]
# ```
#
#
# **ws.MODE_FULL**
#
# ```json
# DEBUG:root:Ticks: [{'tradable': True, 'mode': 'full', 'instrument_token': 12219650, 'last_price': 210.55, 'last_quantity': 75, 'average_price': 227.19, 'volume': 1344000, 'buy_quantity': 61650, 'sell_quantity': 64725, 'ohlc': {'open': 265.1, 'high': 268.3, 'low': 205.05, 'close': 264.15}, 'change': -20.291501041075136, 'last_trade_time': datetime.datetime(2020, 11, 4, 12, 2, 46), 'oi': 834150, 'oi_day_high': 834150, 'oi_day_low': 735225, 'timestamp': datetime.datetime(2020, 11, 4, 12, 2, 50), 'depth': {'buy': [{'quantity': 150, 'price': 210.0, 'orders': 2}, {'quantity': 75, 'price': 209.9, 'orders': 1}, {'quantity': 75, 'price': 209.85, 'orders': 1}, {'quantity': 75, 'price': 209.8, 'orders': 1}, {'quantity': 75, 'price': 209.7, 'orders': 1}], 'sell': [{'quantity': 75, 'price': 210.45, 'orders': 1}, {'quantity': 75, 'price': 210.5, 'orders': 1}, {'quantity': 150, 'price': 210.6, 'orders': 2}, {'quantity': 300, 'price': 210.65, 'orders': 2}, {'quantity': 150, 'price': 210.7, 'orders': 2}]}}, {'tradable': True, 'mode': 'full', 'instrument_token': 12219<PASSWORD>, 'last_price': 277.0, 'last_quantity': 75, 'average_price': 267.28, 'volume': 90825, 'buy_quantity': 53925, 'sell_quantity': 44625, 'ohlc': {'open': 269.6, 'high': 294.15, 'low': 235.05, 'close': 262.5}, 'change': 5.523809523809524, 'last_trade_time': datetime.datetime(2020, 11, 4, 12, 2, 49), 'oi': 54525, 'oi_day_high': 56250, 'oi_day_low': 50100, 'timestamp': datetime.datetime(2020, 11, 4, 12, 2, 51), 'depth': {'buy': [{'quantity': 75, 'price': 277.0, 'orders': 1}, {'quantity': 150, 'price': 276.05, 'orders': 1}, {'quantity': 225, 'price': 276.0, 'orders': 1}, {'quantity': 75, 'price': 275.9, 'orders': 1}, {'quantity': 600, 'price': 275.8, 'orders': 1}], 'sell': [{'quantity': 825, 'price': 277.9, 'orders': 2}, {'quantity': 75, 'price': 278.0, 'orders': 1}, {'quantity': 150, 'price': 278.1, 'orders': 1}, {'quantity': 1125, 'price': 278.15, 'orders': 1}, {'quantity': 1125, 'price': 278.25, 'orders': 1}]}}]
# DEBUG:root:Ticks: [{'tradable': True, 'mode': 'full', 'instrument_token': <PASSWORD>, 'last_price': 277.0, 'last_quantity': 75, 'average_price': 267.28, 'volume': 90825, 'buy_quantity': 53925, 'sell_quantity': 44625, 'ohlc': {'open': 269.6, 'high': 294.15, 'low': 235.05, 'close': 262.5}, 'change': 5.523809523809524, 'last_trade_time': datetime.datetime(2020, 11, 4, 12, 2, 49), 'oi': 54525, 'oi_day_high': 56250, 'oi_day_low': 50100, 'timestamp': datetime.datetime(2020, 11, 4, 12, 2, 51), 'depth': {'buy': [{'quantity': 75, 'price': 277.0, 'orders': 1}, {'quantity': 150, 'price': 276.05, 'orders': 1}, {'quantity': 225, 'price': 276.0, 'orders': 1}, {'quantity': 75, 'price': 275.9, 'orders': 1}, {'quantity': 600, 'price': 275.8, 'orders': 1}], 'sell': [{'quantity': 825, 'price': 277.9, 'orders': 2}, {'quantity': 75, 'price': 278.0, 'orders': 1}, {'quantity': 150, 'price': 278.1, 'orders': 1}, {'quantity': 1125, 'price': 278.15, 'orders': 1}, {'quantity': 1125, 'price': 278.25, 'orders': 1}]}}, {'tradable': True, 'mode': 'full', 'instrument_token': 12219650, 'last_price': 210.55, 'last_quantity': 75, 'average_price': 227.19, 'volume': 1344000, 'buy_quantity': 60150, 'sell_quantity': 64800, 'ohlc': {'open': 265.1, 'high': 268.3, 'low': 205.05, 'close': 264.15}, 'change': -20.291501041075136, 'last_trade_time': datetime.datetime(2020, 11, 4, 12, 2, 46), 'oi': 834150, 'oi_day_high': 834150, 'oi_day_low': 735225, 'timestamp': datetime.datetime(2020, 11, 4, 12, 2, 51), 'depth': {'buy': [{'quantity': 150, 'price': 210.0, 'orders': 2}, {'quantity': 75, 'price': 209.9, 'orders': 1}, {'quantity': 75, 'price': 209.85, 'orders': 1}, {'quantity': 75, 'price': 209.8, 'orders': 1}, {'quantity': 75, 'price': 209.7, 'orders': 1}], 'sell': [{'quantity': 75, 'price': 210.3, 'orders': 1}, {'quantity': 75, 'price': 210.45, 'orders': 1}, {'quantity': 75, 'price': 210.5, 'orders': 1}, {'quantity': 150, 'price': 210.6, 'orders': 2}, {'quantity': 300, 'price': 210.65, 'orders': 2}]}}]
# ```
#
kws.connect()
# ## Import csv
csv_file = '/home/harjeet/playground/KiteConnect/options-charts/data/Instrument_tokens-2020-11-10.csv'
# +
# %%time
import csv
with open(csv_file, newline='') as f:
reader = csv.DictReader(f)
# header = next(reader) # ignore header
data = [int(row['instrument_token']) for row in reader]
# -
len(data)
data[:7]
# ## Sqlite3 insertion
import sqlite3
from datetime import datetime
db = sqlite3.connect(os.getenv("DB_FILE"))
DB_FILE = os.getenv("DB_FILE")
# +
c = db.cursor()
# for tick in ticks:
c.execute(f"insert into ticks values ('{datetime.now()}', 12345, 23.5)")
# c.execute(insert_tick_statement, {
# "date": datetime.now(),
# "token": tick["instrument_token"],
# "price": tick["last_price"]})
# logging.info("Inserting ticks to db : {}".format(json.dumps(ticks)))
try:
db.commit()
except Exception:
db.rollback()
logging.exception("Couldn't write ticks to db: ")
# -
# ## Execute shell command
import subprocess
cmd = "curl -Ls -w %{url_effective} -b /home/harjeet/playground/KiteConnect/data/expr_1_cookies/cookies.txt 'https://kite.zerodha.com/connect/login?v=3&$API_KEY'"
# subprocess.run(['curl', 'http://www.google.com'], stdout=subprocess.PIPE).stdout.decode('utf-8')
subprocess.run('curl http://www.google.com', stdout=subprocess.PIPE).stdout.decode('utf-8')
subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
# ## Delete unwanted keys in tick
tick_str = """{
"tradable": true,
"mode": "full",
"instrument_token": <PASSWORD>,
"last_price": 230.15,
"last_quantity": 75,
"average_price": 235.4,
"volume": 2556900,
"buy_quantity": 68025,
"sell_quantity": 62550,
"ohlc": {
"open": 265.1,
"high": 289.45,
"low": 204.55,
"close": 264.15
},
"change": -12.871474540980495,
"last_trade_time": "2020-11-04 14:12:31",
"oi": 765000,
"oi_day_high": 848175,
"oi_day_low": 734775,
"timestamp": "2020-11-04 14:12:45",
"depth": {
"buy": [
{
"quantity": 1125,
"price": 228.9,
"orders": 1
},
{
"quantity": 150,
"price": 228.85,
"orders": 2
},
{
"quantity": 675,
"price": 228.8,
"orders": 1
},
{
"quantity": 150,
"price": 228.75,
"orders": 2
},
{
"quantity": 75,
"price": 228.7,
"orders": 1
}
],
"sell": [
{
"quantity": 75,
"price": 229.95,
"orders": 1
},
{
"quantity": 225,
"price": 230.0,
"orders": 1
},
{
"quantity": 75,
"price": 230.1,
"orders": 1
},
{
"quantity": 75,
"price": 230.15,
"orders": 1
},
{
"quantity": 75,
"price": 230.25,
"orders": 1
}
]
}
}"""
import json
tick = json.loads(tick_str)
def delete_keys(tick, keys):
# TODO Handle recursive dict structure, buy using dot to separate levels of heirarchy
for key in keys:
# if "." in key:
t = tick
*key_prefix, last_part = key.split('.')
for k in key_prefix:
t = t[k]
try:
del t[last_part]
except KeyError:
print(f'Key {key}" is not in the tick dictionary')
delete_keys(tick, ["depth", "oi_day_high", "oi_day_low", "buy_quantity", "sell_quantity", "ohlc.open", "ohlc.close"])
# +
t = tick["ohlc"]
del t['open']
# +
len(json.dumps(tick))
# 314
# 346
# 949
# -
tick
key = "1.2.3.4.5"
key = "hello"
*prefix_keys, last_part = key.split('.')
f"{prefix_keys} : {last_part}"
prefix_keys
| notebooks/Options Charts.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] colab_type="text" id="PAq3-v_peF9P" slideshow={"slide_type": "slide"}
# [](http://rpi.analyticsdojo.com)
# <center><h1>Revisting Boston Housing with Pytorch</h1></center>
# <center><h3><a href = 'http://rpi.analyticsdojo.com'>rpi.analyticsdojo.com</a></h3></center>
# -
# # Revisting Boston Housing with Pytorch
# + colab={} colab_type="code" id="ssNHzVxmeUho"
# #!pip install torch torchvision
# + colab={} colab_type="code" id="0Usm1-07eF9U"
#Let's get rid of some imports
# %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
#Define the model
import torch
import torch.nn as nn
import torch.nn.functional as F
# + [markdown] colab_type="text" id="ey6rkOdbeF9d" slideshow={"slide_type": "subslide"}
# ## Overview
# - Getting the Data
# - Reviewing Data
# - Modeling
# - Model Evaluation
# - Using Model
# - Storing Model
#
# + [markdown] colab_type="text" id="3wcvspWkeF9f" slideshow={"slide_type": "subslide"}
# ## Getting Data
# - Available in the [sklearn package](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_boston.html) as a Bunch object (dictionary).
# - From FAQ: ["Donโt make a bunch object! They are not part of the scikit-learn API. Bunch objects are just a way to package some numpy arrays. As a scikit-learn user you only ever need numpy arrays to feed your model with data."](http://scikit-learn.org/stable/faq.html)
# - Available in the UCI data repository.
# - Better to convert to Pandas dataframe.
# + colab={} colab_type="code" id="r8nkKvL4eF9o"
#From sklearn tutorial.
from sklearn.datasets import load_boston
boston = load_boston()
print( "Type of boston dataset:", type(boston))
# + colab={} colab_type="code" id="dBPIWOQDeF9s"
#A bunch is you remember is a dictionary based dataset. Dictionaries are addressed by keys.
#Let's look at the keys.
print(boston.keys())
# + colab={} colab_type="code" id="mFOdZXNKeF9x" slideshow={"slide_type": "subslide"}
#DESCR sounds like it could be useful. Let's print the description.
print(boston['DESCR'])
# + colab={} colab_type="code" id="GFUWt9YJeF92" slideshow={"slide_type": "subslide"}
# Let's change the data to a Panda's Dataframe
import pandas as pd
boston_df = pd.DataFrame(boston['data'] )
boston_df.head()
# + colab={} colab_type="code" id="PmWBxnVNeF95" slideshow={"slide_type": "subslide"}
#Now add the column names.
boston_df.columns = boston['feature_names']
boston_df.head()
# + colab={} colab_type="code" id="bSqG7J-GeF99" slideshow={"slide_type": "subslide"}
#Add the target as PRICE.
boston_df['PRICE']= boston['target']
boston_df.head()
# + [markdown] colab_type="text" id="cJHf2nYceF-B" slideshow={"slide_type": "subslide"}
# ## Attribute Information (in order):
# Looks like they are all continuous IV and continuous DV.
# - CRIM per capita crime rate by town
# - ZN proportion of residential land zoned for lots over 25,000 sq.ft.
# - INDUS proportion of non-retail business acres per town
# - CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
# - NOX nitric oxides concentration (parts per 10 million)
# - RM average number of rooms per dwelling
# - AGE proportion of owner-occupied units built prior to 1940
# - DIS weighted distances to five Boston employment centres
# - RAD index of accessibility to radial highways
# - TAX full-value property-tax rate per 10,000
# - PTRATIO pupil-teacher ratio by town
# - B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
# - LSTAT % lower status of the population
# - MEDV Median value of owner-occupied homes in 1000's
# Let's check for missing values.
# + colab={} colab_type="code" id="17iYyvMNeF-D" slideshow={"slide_type": "subslide"}
import numpy as np
#check for missing values
print(np.sum(np.isnan(boston_df)))
# + [markdown] colab_type="text" id="31VBYJCXeF-K" slideshow={"slide_type": "subslide"}
# ## What type of data are there?
# - First let's focus on the dependent variable, as the nature of the DV is critical to selection of model.
# - *Median value of owner-occupied homes in $1000's* is the Dependent Variable (continuous variable).
# - It is relevant to look at the distribution of the dependent variable, so let's do that first.
# - Here there is a normal distribution for the most part, with some at the top end of the distribution we could explore later.
# + colab={} colab_type="code" id="gMC1ywHPeF-N"
#Let's us seaborn, because it is pretty. ;)
#See more here. http://seaborn.pydata.org/tutorial/distributions.html
import seaborn as sns
sns.distplot(boston_df['PRICE']);
# + colab={} colab_type="code" id="7uq7gI9seF-R" slideshow={"slide_type": "subslide"}
#We can quickly look at other data.
#Look at the bottom row to see thinks likely coorelated with price.
#Look along the diagonal to see histograms of each.
sns.pairplot(boston_df);
# + [markdown] colab_type="text" id="Zfa7DQNheF-U" slideshow={"slide_type": "subslide"}
# ## Preparing to Model
# - It is common to separate `y` as the dependent variable and `X` as the matrix of independent variables.
# - Here we are using `train_test_split` to split the test and train.
# - This creates 4 subsets, with IV and DV separted: `X_train, X_test, y_train, y_test`
#
#
# + colab={} colab_type="code" id="89UDBeWFeF-W"
#This will throw and error at import if haven't upgraded.
# from sklearn.cross_validation import train_test_split
from sklearn.model_selection import train_test_split
#y is the dependent variable.
y = boston_df['PRICE']
#As we know, iloc is used to slice the array by index number. Here this is the matrix of
#independent variables.
X = boston_df.iloc[:,0:13]
# Split the data into a training set and a test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
# + colab={} colab_type="code" id="PbbYVzFTfAJL"
#Define training hyperprameters.
batch_size = 50
num_epochs = 200
learning_rate = 0.01
size_hidden= 100
#Calculate some other hyperparameters based on data.
batch_no = len(X_train) // batch_size #batches
cols=X_train.shape[1] #Number of columns in input matrix
n_output=1
# + colab={} colab_type="code" id="xD9PhAU7hoqT"
#Create the model
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Assume that we are on a CUDA machine, then this should print a CUDA device:
print("Executing the model on :",device)
class Net(torch.nn.Module):
def __init__(self, n_feature, size_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(cols, size_hidden) # hidden layer
self.predict = torch.nn.Linear(size_hidden, n_output) # output layer
def forward(self, x):
x = F.relu(self.hidden(x)) # activation function for hidden layer
x = self.predict(x) # linear output
return x
net = Net(cols, size_hidden, n_output)
# + colab={} colab_type="code" id="dE9a54SijQEs"
#Adam is a specific flavor of gradient decent which is typically better
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
#optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
criterion = torch.nn.MSELoss(size_average=False) # this is for regression mean squared loss
# + colab={} colab_type="code" id="J1-OhvPsk6aM"
#Change to numpy arraay.
X_train=X_train.values
y_train=y_train.values
X_test=X_test.values
y_test=y_test.values
# + colab={} colab_type="code" id="Nyf8hhaijqFA"
from sklearn.utils import shuffle
from torch.autograd import Variable
running_loss = 0.0
for epoch in range(num_epochs):
#Shuffle just mixes up the dataset between epocs
X_train, y_train = shuffle(X_train, y_train)
# Mini batch learning
for i in range(batch_no):
start = i * batch_size
end = start + batch_size
inputs = Variable(torch.FloatTensor(X_train[start:end]))
labels = Variable(torch.FloatTensor(y_train[start:end]))
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
#print("outputs",outputs)
#print("outputs",outputs,outputs.shape,"labels",labels, labels.shape)
loss = criterion(outputs, torch.unsqueeze(labels,dim=1))
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
print('Epoch {}'.format(epoch+1), "loss: ",running_loss)
running_loss = 0.0
# + colab={} colab_type="code" id="n4QTTcBF3aeZ"
import pandas as pd
from sklearn.metrics import r2_score
X = Variable(torch.FloatTensor(X_train))
result = net(X)
pred=result.data[:,0].numpy()
print(len(pred),len(y_train))
r2_score(pred,y_train)
# + colab={} colab_type="code" id="rAsEl1qyuSrH"
import pandas as pd
from sklearn.metrics import r2_score
#This is a little bit tricky to get the resulting prediction.
def calculate_r2(x,y=[]):
"""
This function will return the r2 if passed x and y or return predictions if just passed x.
"""
# Evaluate the model with the test set.
X = Variable(torch.FloatTensor(x))
result = net(X) #This outputs the value for regression
result=result.data[:,0].numpy()
if len(y) != 0:
r2=r2_score(result, y)
print("R-Squared", r2)
#print('Accuracy {:.2f}'.format(num_right / len(y)), "for a total of ", len(y), "records")
return pd.DataFrame(data= {'actual': y, 'predicted': result})
else:
print("returning predictions")
return result
# + colab={} colab_type="code" id="WJ451DaG5yXb"
result1=calculate_r2(X_train,y_train)
result2=calculate_r2(X_test,y_test)
# + [markdown] colab_type="text" id="v4mhnevoeF-Y" slideshow={"slide_type": "subslide"}
# ## Modeling
# - First import the package: `from sklearn.linear_model import LinearRegression`
# - Then create the model object.
# - Then fit the data.
# - This creates a trained model (an object) of class regression.
# - The variety of methods and attributes available for regression are shown [here](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html).
#
# + colab={} colab_type="code" id="CcWl-I5BeF-Z"
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit( X_train, y_train )
# + [markdown] colab_type="text" id="fbnv9I0ueF-e" slideshow={"slide_type": "subslide"}
# ## Evaluating the Model Results
# - You have fit a model.
# - You can now store this model, save the object to disk, or evaluate it with different outcomes.
# - Trained regression objects have coefficients (`coef_`) and intercepts (`intercept_`) as attributes.
# - R-Squared is determined from the `score` method of the regression object.
# - For Regression, we are going to use the coefficient of determination as our way of evaluating the results, [also referred to as R-Squared](https://en.wikipedia.org/wiki/Coefficient_of_determination)
# + colab={} colab_type="code" id="lkam3qKNeF-f"
print('R2 for Train)', lm.score( X_train, y_train ))
print('R2 for Test (cross validation)', lm.score(X_test, y_test))
# + [markdown] colab_type="text" id="E-oXxeTweF_G"
#
# Copyright [AnalyticsDojo](http://rpi.analyticsdojo.com) 2016.
# This work is licensed under the [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/) license agreement.
#
| site/_build/jupyter_execute/notebooks/09-deep-learning1/06-regression-bh-pytorch.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Advanced Lane Finding Project
#
# The goals / steps of this project are the following:
#
# * Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.
# * Apply a distortion correction to raw images.
# * Use color transforms, gradients, etc., to create a thresholded binary image.
# * Apply a perspective transform to rectify binary image ("birds-eye view").
# * Detect lane pixels and fit to find the lane boundary.
# * Determine the curvature of the lane and vehicle position with respect to center.
# * Warp the detected lane boundaries back onto the original image.
# * Output visual display of the lane boundaries and numerical estimation of lane curvature and vehicle position.
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
import glob
import os
# %matplotlib inline
# ## Image Preprocessing
# ### Camera Calibration using chessboard images
# #### Define the calibration function
# * find corners
# * draw corners
# * output object points and image points as file
dir_source="camera_cal"
dir_desti="output_images"
dir_test = "test_images"
# +
def camera_calibration(nx=9, ny=6, dir_source="camera_cal", dir_desti="output_images"):
# prepare object points
nx = nx # the number of inside corners in x
ny = ny # the number of inside corners in y
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((ny*nx,3), np.float32)
objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.
# Make a list of calibration images
images = glob.glob(dir_source+'/'+'calibration*.jpg')
# Step through the list and search for chessboard corners
for idx, fname in enumerate(images):
img = cv2.imread(fname)
# plt.imshow(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (nx,ny), None)
# If found, add object points, image points
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
# Draw and display the corners
cv2.drawChessboardCorners(img, (nx,ny), corners, ret)
write_name = dir_desti+'/'+'corners_found'+str(idx+1)+'.jpg'
cv2.imwrite(write_name, img)
# plt.imshow(img)
# cv2.waitKey(500)
# cv2.destroyAllWindows()
fullpath = dir_source+'/'+'calibration3.jpg'
img = cv2.imread(fullpath)
img_size = (img.shape[1], img.shape[0])
# Do camera calibration given object points and image points
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size, None,None)
# Save the camera calibration result for later use (we won't worry about rvecs / tvecs)
dist_pickle = {}
dist_pickle["mtx"] = mtx
dist_pickle["dist"] = dist
aim_file = open(dir_source+"/wide_dist_pickle.p", "wb")
pickle.dump( dist_pickle, aim_file)
aim_file.close()
#dst = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
# -
# Conduct calibration process
def test_camera_calibration():
camera_calibration()
# #### Define function for distortion process
# * read in the save obj and img points
# * process undistortion
# * visualization the results
# * save the results in files
def undistortion_conduct(dir_source="camera_cal", dir_desti="output_images"):
# Step through the list and search for chessboard corners
pickle_file = open('camera_cal/wide_dist_pickle.p', 'rb')
dist_pickle=pickle.load(pickle_file)
pickle_file.close()
mtx = dist_pickle["mtx"]
dist = dist_pickle["dist"]
if dir_source == "camera_cal":
images = glob.glob(dir_source+'/'+'calibration*.jpg')
for idx, fname in enumerate(images):
img = cv2.imread(fname)
dst = cv2.undistort(img, mtx, dist, None, mtx)
cv2.imwrite(dir_desti+'/'+'unstored'+str(idx+1)+'_undistort.jpg',dst)
# Visualize undistortion comparison
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))
ax1.imshow(img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(dst)
ax2.set_title('Undistorted Image', fontsize=30)
plt.savefig(dir_desti+'/'+fname[-16:-4]+'_compar_ori_undist.jpg')
else:
img = cv2.imread(dir_source)
# plt.imshow(img)
dst = cv2.undistort(img, mtx, dist, None, mtx)
cv2.imwrite(dir_desti+'/'+dir_source[-9:-4]+'_undistort.jpg',dst)
# Visualize undistortion comparison
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))
ax1.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(cv2.cvtColor(dst, cv2.COLOR_BGR2RGB))
ax2.set_title('Undistorted Image', fontsize=30)
plt.savefig(dir_desti+'/'+dir_source[-9:-4]+'_compar_ori_undist.jpg')
# Conduct undistortion process on all images
def test_undistortion_conduct_chess():
undistortion_conduct()
def test_undistortion_conduct_real_pic():
undistortion_conduct(dir_source=dir_test+'/straight_lines2.jpg')
# ### Use Threshhold to Creat Binary Image
# #### Investigate different color channels
# #### Investigate the different sobel applicaion
# +
# absolute gradient
def abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh_min=20, thresh_max=100):
# Apply the following steps to img
# 1) Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 2) Take the derivative in x or y given orient = 'x' or 'y'
if orient == 'x':
sobel = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
elif orient == 'y':
sobel = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
else:
print("the inputed orient is not valid")
# 3) Take the absolute value of the derivative or gradient
abs_sobel = np.absolute(sobel)
# 4) Scale to 8-bit (0 - 255) then convert to type = np.uint8
scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))
# 5) Create a mask of 1's where the scaled gradient magnitude
# is > thresh_min and < thresh_max
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[(scaled_sobel>=thresh_min)&(scaled_sobel<=thresh_max)]=1
# 6) Return this mask as your binary_output image
return sxbinary
# direction of the gradient and applies a threshold.
def dir_threshold(img, sobel_kernel=15, thresh=(0.7, 1.3)):
# Apply the following steps to img
# 1) Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 2) Take the gradient in x and y separately
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
# 3) Take the absolute value of the x and y gradients
sobelx_abs = np.absolute(sobelx)
sobely_abs = np.absolute(sobely)
# 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient
dire_gradient = np.arctan2(sobely_abs, sobelx_abs)
# 5) Create a binary mask where direction thresholds are met
binary_output = np.zeros_like(dire_gradient)
binary_output[(dire_gradient >= thresh[0]) & \
(dire_gradient <= thresh[1])] = 1
# 6) Return this mask as the binary_output image
return binary_output
# Magnitude of the gradient
def mag_thresh(img, sobel_kernel=3, mag_thresh=(30, 100)):
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Take both Sobel x and y gradients
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
# Calculate the gradient magnitude
gradmag = np.sqrt(sobelx**2 + sobely**2)
# Rescale to 8 bit
scale_factor = np.max(gradmag)/255
gradmag = (gradmag/scale_factor).astype(np.uint8)
# Create a binary image of ones where threshold is met, zeros otherwise
binary_output = np.zeros_like(gradmag)
binary_output[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1
# Return the binary image
return binary_output
# -
# #### Test the Absolute Sobel threshhold
def test_abs_sobel_thresh_x():
# Test for x
# Choose a Sobel kernel size
ksize = 3 # Choose a larger odd number to smooth gradient measurements
# Choose a image
image = mpimg.imread('test_images/test5_undistort.jpg')
# Apply each of the thresholding functions
gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh_min=15, thresh_max=90)
# 20, 100
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(gradx, cmap='gray')
ax2.set_title('Thresholded Grad. abs_x', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
def test_abs_sobel_thresh_y():
# Test for y
# Choose a Sobel kernel size
ksize = 3 # Choose a larger odd number to smooth gradient measurements
# Choose a image
image = mpimg.imread('test_images/test5_undistort.jpg')
# Apply each of the thresholding functions
grady = abs_sobel_thresh(image, orient='y', sobel_kernel=ksize, thresh_min=20, thresh_max=100)
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(grady, cmap='gray')
ax2.set_title('Thresholded Grad. abs_y', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# #### Test the Magnitude Sobel threshhold
def test_mag_thresh():
# Choose a Sobel kernel size
ksize = 3 # Choose a larger odd number to smooth gradient measurements
# Choose a image
image = mpimg.imread('test_images/test5_undistort.jpg')
# Apply each of the thresholding functions
mag_binary = mag_thresh(image, sobel_kernel=ksize, mag_thresh=(30, 100))
# 30, 100
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(combined, cmap='gray')
ax2.set_title('Thresholded Grad. Magni.', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# #### Test the direction Sobel threshhold
def test_dir_threshold():
# Choose a Sobel kernel size
ksize = 3 # Choose a larger odd number to smooth gradient measurements
# Choose a image
image = mpimg.imread('test_images/test5_undistort.jpg')
# Apply each of the thresholding functions
dir_binary = dir_threshold(image, sobel_kernel=ksize, thresh=(0.7, 1.3)) # 0.7, 1.3
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(dir_binary, cmap='gray')
ax2.set_title('Thresholded Grad. Dire.', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# #### Test the combined Sobel threshhold
def test_combined_thresh_complex():
# Choose a Sobel kernel size
ksize = 3 # Choose a larger odd number to smooth gradient measurements
# Choose a image
image = mpimg.imread('test_images/test5_undistort.jpg')
# Apply each of the thresholding functions
gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh_min=20, thresh_max=100)
grady = abs_sobel_thresh(image, orient='y', sobel_kernel=ksize, thresh_min=20, thresh_max=100)
mag_binary = mag_thresh(image, sobel_kernel=ksize, mag_thresh=(30, 100)) # 30, 100
dir_binary = dir_threshold(image, sobel_kernel=ksize, thresh=(0.7, 1.3)) # 0.7, 1.3
combined = np.zeros_like(dir_binary)
combined[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1))] = 1
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(combined, cmap='gray')
ax2.set_title('Thresholded Grad. Combi1.', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
def test_combined_thresh_simple():
# Choose a Sobel kernel size
ksize = 3 # Choose a larger odd number to smooth gradient measurements
# Choose a image
image = mpimg.imread('test_images/test5_undistort.jpg')
# Apply each of the thresholding functions
gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh_min=20, thresh_max=100)
grady = abs_sobel_thresh(image, orient='y', sobel_kernel=ksize, thresh_min=20, thresh_max=100)
mag_binary = mag_thresh(image, sobel_kernel=ksize, mag_thresh=(30, 100)) # 30, 100
dir_binary = dir_threshold(image, sobel_kernel=ksize, thresh=(0.7, 1.3)) # 0.7, 1.3
combined = np.zeros_like(dir_binary)
# combined[((gradx == 1) & (dir_binary == 1)) | ((grady == 1) & (mag_binary == 1) )] = 1
combined[((gradx == 1) & (dir_binary == 1))] = 1
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(combined, cmap='gray')
ax2.set_title('Thresholded Grad. Combi2.', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# ### Color Threthhold Implementation
# Firstly we glimpse the different channel in grey scale.
def investigation_color_channels():
# Investigate the channel overview
img_cbi = mpimg.imread('test_images/test5.jpg')
img_cbi_r = img_cbi[:,:,0]
img_cbi_g = img_cbi[:,:,1]
img_cbi_b = img_cbi[:,:,2]
img_cbi_hls = cv2.cvtColor(img_cbi, cv2.COLOR_RGB2HLS)
img_cbi_h = img_cbi_hls[:,:,0]
img_cbi_l = img_cbi_hls[:,:,1]
img_cbi_s = img_cbi_hls[:,:,2]
fig0 = plt.figure()
ax0 = fig0.add_subplot(1, 1, 1)
ax0.imshow(img_cbi)
ax0.set_title('original image')
fig1, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(24, 9))
fig1.tight_layout()
ax1.imshow(img_cbi_r, cmap='gray')
ax1.set_title('R Channel')
ax2.imshow(img_cbi_g, cmap='gray')
ax2.set_title('G Channel')
ax3.imshow(img_cbi_b, cmap='gray')
ax3.set_title('B Channel')
plt.savefig(dir_desti+'/'+'compareRGB.jpg')
fig2, (ax4, ax5, ax6) = plt.subplots(1, 3, figsize=(24, 9))
fig2.tight_layout()
ax4.imshow(img_cbi_h, cmap='gray')
ax4.set_title('H Channel')
ax5.imshow(img_cbi_l, cmap='gray')
ax5.set_title('L Channel')
ax6.imshow(img_cbi_s, cmap='gray')
ax6.set_title('S Channel')
plt.savefig(dir_desti+'/'+'compareHLS.jpg')
# With the observation of the different color channel, R, B, G.
# And the investigation of H, L, S, we can find the line color is distinct in R channel and S aspect.
# secondly, we apply threshhold for the seperate channel.
# So we gain more knowledge about the performance.
# Define function for processing HLS threshhold and output a binary img
def hls_select(img, thresh=(160, 255), channel='s'):
# 1) Convert to HLS color space
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
# 2) Apply a threshold to the one channel
if channel=='h':
hls_one = hls[:,:,0]
elif channel=='l':
hls_one = hls[:,:,1]
else:
hls_one = hls[:,:,2]
binary_output = np.zeros_like(hls_one)
binary_output[(hls_one>thresh[0])&(hls_one<=thresh[1])]=1
# 3) Return a binary image of threshold result
return binary_output
def test_hls_select():
# Test the hls_select function
image = mpimg.imread('test_images/test5.jpg')
hls_binary = hls_select(image, thresh=(160, 255), channel='s')
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(hls_binary, cmap='gray')
ax2.set_title('Thresholded S', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# Define function for processing RGB threshhold and output a binary img
def rgb_select(img, thresh=(160, 255), channel='r'):
# 1) Apply a threshold to the one channel
if channel=='b':
rgb_one = img[:,:,2]
elif channel=='g':
rgb_one = img[:,:,1]
else:
rgb_one = img[:,:,0]
binary_output = np.zeros_like(rgb_one)
binary_output[(rgb_one>thresh[0])&(rgb_one<=thresh[1])]=1
# 2) Return a binary image of threshold result
return binary_output
# Test the rgb_select function
def test_rgb_select():
image = mpimg.imread('test_images/test5.jpg')
rgb_binary = rgb_select(image, thresh=(210, 255), channel='r')
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(rgb_binary, cmap='gray')
ax2.set_title('Thresholded R', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# **Conclustion:**
# Thought the detailed investigation. We confirmed that the Threathhold in S and R channel can distinguish the lane line in the near field. And threshold of absolute gradient in x give a presentation of lane line in the far field.
# Then we combine the Threathhold in S and gradien x for the further investigation.
def test_combined_gradx_s():
# Choose a Sobel kernel size
ksize = 3 # Choose a larger odd number to smooth gradient measurements
# Choose a image
image = mpimg.imread('test_images/test5_undistort.jpg')
# Apply the thresholding functions in grad X
gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh_min=20, thresh_max=100)
hls_binary = hls_select(image, thresh=(160, 255), channel='s')
combined_gradx_s = np.zeros_like(gradx)
combined_gradx_s[((gradx == 1) | (hls_binary == 1))] = 1
# print(combined_gradx_s.shape)
# print(combined_gradx_s)
# Plot the result
# fig0 = plt.figure()
# ax0 = fig0.add_subplot(1, 1, 1)
cv2.imwrite('test_images/test5_threshold.jpg',combined_gradx_s*255)
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(combined_gradx_s, cmap='gray')
ax2.set_title('Thresholded Grad. Combi. GradX + S', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# +
# test_combined_gradx_s()
# -
# ### Perspective Transform
# Function for perspective Transform
# def thresh_warp(undist, nx, ny, mtx, dist):
def thresh_warp(undist):
global Minv
img_size = (undist.shape[1], undist.shape[0])
src = np.float32(
[[(img_size[0] / 2) - 63, img_size[1] / 2 + 100],
[((img_size[0] / 6) - 20), img_size[1]],
[(img_size[0] * 5 / 6) + 60, img_size[1]],
[(img_size[0] / 2 + 65), img_size[1] / 2 + 100]])
dst = np.float32(
[[(img_size[0] / 4), 0],
[(img_size[0] / 4), img_size[1]],
[(img_size[0] * 3 / 4), img_size[1]],
[(img_size[0] * 3 / 4), 0]])
M = cv2.getPerspectiveTransform(src, dst)
warped = cv2.warpPerspective(undist, M, img_size, flags= cv2.INTER_LINEAR)
Minv = cv2.getPerspectiveTransform(dst, src)
return warped, M
# +
# test the thresh_warp function
def test_thresh_warp():
img = cv2.imread('test_images/test5_threshold.jpg')
nx = 9 # the number of inside corners in x
ny = 6 # the number of inside corners in y
#read the pickle file
picklefile = open(dir_source+"/wide_dist_pickle.p", "rb")
dist_pickle = pickle.load(picklefile)
picklefile.close()
mtx = dist_pickle["mtx"]
dist = dist_pickle["dist"]
# top_down, perspective_M = thresh_warp(img, nx, ny, mtx, dist)
top_down, perspective_M = thresh_warp(img)
# print(top_down.shape)
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(img)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(top_down)
ax2.set_title('Undistorted and Warped Image', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
cv2.imwrite('test_images/test5_pers_trans.jpg',top_down)
print(top_down.shape)
# +
# test_thresh_warp()
# -
# ## Lane Searching
# ### Polynomial fit according to the pixels
# +
def find_lane_pixels(thresh):
# Take a histogram of the bottom half of the image
if len(thresh.shape)>2:
binary_warped = cv2.cvtColor(thresh, cv2.COLOR_RGB2GRAY)
else:
binary_warped = thresh
histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)
# Create an output image to draw on and visualize the result
out_img = np.dstack((binary_warped, binary_warped, binary_warped))
# Find the peak of the left and right halves of the histogram
# These will be the starting point for the left and right lines
midpoint = np.int(histogram.shape[0]//2)
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:]) + midpoint
# HYPERPARAMETERS
# Choose the number of sliding windows
nwindows = 9
# Set the width of the windows +/- margin
margin = 100
# Set minimum number of pixels found to recenter window
minpix = 50
# Set height of windows - based on nwindows above and image shape
window_height = np.int(binary_warped.shape[0]//nwindows)
# Identify the x and y positions of all nonzero pixels in the image
nonzero = binary_warped.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Current positions to be updated later for each window in nwindows
leftx_current = leftx_base
rightx_current = rightx_base
# Create empty lists to receive left and right lane pixel indices
left_lane_inds = []
right_lane_inds = []
# Step through the windows one by one
for window in range(nwindows):
# Identify window boundaries in x and y (and right and left)
win_y_low = binary_warped.shape[0] - (window+1)*window_height
win_y_high = binary_warped.shape[0] - window*window_height
win_xleft_low = leftx_current - margin
win_xleft_high = leftx_current + margin
win_xright_low = rightx_current - margin
win_xright_high = rightx_current + margin
# Draw the windows on the visualization image
cv2.rectangle(out_img,(win_xleft_low,win_y_low),
(win_xleft_high,win_y_high),(0,255,0), 2)
cv2.rectangle(out_img,(win_xright_low,win_y_low),
(win_xright_high,win_y_high),(0,255,0), 2)
# Identify the nonzero pixels in x and y within the window #
good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
(nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
(nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]
# Append these indices to the lists
left_lane_inds.append(good_left_inds)
right_lane_inds.append(good_right_inds)
# If you found > minpix pixels, recenter next window on their mean position
if len(good_left_inds) > minpix:
leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
if len(good_right_inds) > minpix:
rightx_current = np.int(np.mean(nonzerox[good_right_inds]))
# Concatenate the arrays of indices (previously was a list of lists of pixels)
try:
left_lane_inds = np.concatenate(left_lane_inds)
right_lane_inds = np.concatenate(right_lane_inds)
except ValueError:
# Avoids an error if the above is not implemented fully
pass
# Extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_inds]
righty = nonzeroy[right_lane_inds]
return leftx, lefty, rightx, righty, out_img
def fit_polynomial(binary_warped):
# Find our lane pixels first
leftx, lefty, rightx, righty, out_img = find_lane_pixels(binary_warped)
# Fit a second order polynomial to each using `np.polyfit`
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
# Generate x and y values for plotting
ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )
try:
left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
except TypeError:
# Avoids an error if `left` and `right_fit` are still none or incorrect
print('The function failed to fit a line!')
left_fitx = 1*ploty**2 + 1*ploty
right_fitx = 1*ploty**2 + 1*ploty
return left_fitx, right_fitx, ploty, leftx, lefty, rightx, righty
# -
## check deviation
def sanity_check(left_curverad, right_curverad, left_lane_pos, right_lane_pos):
if not (2 > left_curverad / right_curverad > 0.5):
return 1
if abs(right_lane_pos-left_lane_pos)>4.5 or abs(right_lane_pos-left_lane_pos)<3:
return 2
return 0
def test_fit_polynomial_find_lane_pixels():
# Test the function fit_polynomial, find_lane_pixels
thresh = mpimg.imread('test_images/test5_pers_trans.jpg')
left_fitx, right_fitx, ploty = fit_polynomial(thresh)
## Visualization ##
# Colors in the left and right lane regions
out_img[lefty, leftx] = [255, 0, 0]
out_img[righty, rightx] = [0, 0, 255]
# Plots the left and right polynomials on the lane lines
plt.plot(left_fitx, ploty, color='yellow')
plt.plot(right_fitx, ploty, color='yellow')
plt.imshow(out_img)
# plt.savefig('test_images/test5_draw_rechtangle.jpg')
# +
# test_fit_polynomial_find_lane_pixels()
# -
# #### Calculation of the curvature
# Define conversions in x and y from pixels space to meters
ym_per_pix = 30/720 # meters per pixel in y dimension
xm_per_pix = 3.7/700 # meters per pixel in x dimension
def measure_curvature_offset(thresh, leftx, lefty, rightx, righty):
'''
Calculates the curvature of polynomial functions in pixels.
'''
# Fit a second order polynomial to each using `np.polyfit`
left_fit = np.polyfit(lefty*ym_per_pix, leftx*xm_per_pix, 2)
right_fit = np.polyfit(righty*ym_per_pix, rightx*xm_per_pix, 2)
# Define y-value where we want radius of curvature
# We'll choose the maximum y-value, corresponding to the bottom of the image
y_eval = np.max(thresh.shape[0]*ym_per_pix//2)
# Calculation of R_curve (radius of curvature)
left_curverad = ((1 + (2*left_fit[0]*y_eval + left_fit[1])**2)**1.5) / np.absolute(2*left_fit[0])
right_curverad = ((1 + (2*right_fit[0]*y_eval + right_fit[1])**2)**1.5) / np.absolute(2*right_fit[0])
# Calculation of offset
y_eval_near = np.max((thresh.shape[0]-1)*ym_per_pix)
left_near_lane = np.poly1d(left_fit)(y_eval_near)
right_near_lane = np.poly1d(right_fit)(y_eval_near)
lane_centor = (left_near_lane + right_near_lane) / 2
image_centor = (thresh.shape[1]-1) * xm_per_pix / 2
offset = lane_centor - image_centor
return left_curverad, right_curverad, offset
# Test the function measure_curvature_pixels
# TODO why measure_curvature_offset takes 0 argument
def test_measure_curvature_offset():
thresh = mpimg.imread('test_images/test5_pers_trans.jpg')
leftx, lefty, rightx, righty, out_img = find_lane_pixels(thresh)
# Calculate the radius of curvature in pixels for both lane lines
# left_curverad, right_curverad, offset = measure_curvature_offset(thresh, leftx, lefty, rightx, righty)
left_curverad, right_curverad, offset = measure_curvature_offset(thresh, leftx, lefty, rightx, righty)
print(left_curverad, 'm', right_curverad, 'm', offset, 'm')
# +
# test_measure_curvature_offset()
# -
# ## Video Generation
from moviepy.editor import VideoFileClip
from IPython.display import HTML
def put_lane_info_on_video(image, left_curverad, right_curverad, offset):
"""project the fited lane information to the image
use last 15 frame average data to avoid the number quick jump on screen.
"""
color=(0,200,255)
offset = float(format(offset, '.3f'))
curverad = format(left_curverad, '.3f')
left_right = "right" if offset < 0 else "left"
info_curv = "Curve Radius is {}(m)".format(curverad)
info_offs = "Offset is {0:.2f}m ".format(abs(offset)) + "{} of the center".format(left_right)
cv2.putText(image, info_curv, (50,60), cv2.FONT_HERSHEY_SIMPLEX,2,color,2)
cv2.putText(image, info_offs, (50,120), cv2.FONT_HERSHEY_SIMPLEX,2,color,2)
return image
# +
def drawing_area(birdeye_thresh_warped, ori_image, left_fitx, right_fitx, ploty):
# ori_image = ori_image = mpimg.imread(image) # changed for video
# Create an image to draw the lines on
# warp_zero = np.zeros((720,1280)).astype(np.uint8)
warp_zero = np.zeros_like(birdeye_thresh_warped).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
# Recast the x and y points into usable format for cv2.fillPoly()
pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane onto the warped blank image
cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
newwarp = cv2.warpPerspective(color_warp, Minv, (ori_image.shape[1], ori_image.shape[0]))
# Combine the result with the original image
result = cv2.addWeighted(ori_image, 1, newwarp, 0.3, 0)
return result
# +
# # test drawing and output the result on img
# thresh = mpimg.imread('test_images/test5_pers_trans.jpg')
# ori_image = mpimg.imread('test_images/test5.jpg')
# left_fitx, right_fitx, ploty = fit_polynomial(thresh)
# warp_zero = np.zeros((720,1280)).astype(np.uint8)
# color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
# # Recast the x and y points into usable format for cv2.fillPoly()
# pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
# pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
# pts = np.hstack((pts_left, pts_right))
# # Draw the lane onto the warped blank image
# cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))
# # Warp the blank back to original image space using inverse perspective matrix (Minv)
# newwarp = cv2.warpPerspective(color_warp, Minv, (ori_image.shape[1], ori_image.shape[0]))
# # Combine the result with the original image
# result = cv2.addWeighted(ori_image, 1, newwarp, 0.3, 0)
# color=(0,200,255)
# cv2.putText(result, ' 1000', (50,60), cv2.FONT_HERSHEY_SIMPLEX,2,color,2)
# plt.imshow(result)
# # plt.savefig('test_images/test5_lane_area_draw.jpg')
# -
# ## Pipeline
def undistortion_conduct2(img):
# Step through the list and search for chessboard corners
# img = cv2.imread(ori_image) # changed for video
undistort = cv2.undistort(img, mtx, dist, None, mtx)
return undistort
def combined_gradx_s(image, ksize = 3):
gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh_min=20, thresh_max=100)
hls_binary = hls_select(image, thresh=(160, 255), channel='s')
combined_gradx_s = np.zeros_like(gradx)
combined_gradx_s[((gradx == 1) | (hls_binary == 1))] = 1
return combined_gradx_s
# +
# def finding_lanes_pipeline(ori_image):
# global mtx, dist
# # Make the data ready, which is used for the transformation
# pickle_file = open('camera_cal/wide_dist_pickle.p', 'rb')
# dist_pickle=pickle.load(pickle_file)
# pickle_file.close()
# mtx = dist_pickle["mtx"]
# dist = dist_pickle["dist"]
# # transform the distorted image
# undistort = undistortion_conduct2(ori_image)
# # use gradient methode
# thresh = combined_gradx_s(undistort, ksize = 3)
# # perspective transform
# # birdeye_thresh_warped, perspective_M = thresh_warp(thresh, 9, 6, mtx, dist)
# birdeye_thresh_warped, perspective_M = thresh_warp(thresh)
# # generate polynomial based on the pixels
# left_fitx, right_fitx, ploty, leftx, lefty, rightx, righty = fit_polynomial(birdeye_thresh_warped)
# left_curverad, right_curverad, offset = measure_curvature_offset(birdeye_thresh_warped, leftx, lefty, rightx, righty)
# # drawed = drawing_area(birdeye_thresh_warped, ori_image, left_fitx, right_fitx, ploty)
# drawed = drawing_area(birdeye_thresh_warped, undistort, left_fitx, right_fitx, ploty) # changed to use the undistorted frames as output for more accurate results
# put_lane_info_on_video(drawed, left_curverad, right_curverad, offset)
# # birdeye_thresh_warped_expa = np.expand_dims(birdeye_thresh_warped, axis=2)
# birdeye_thresh_warped_expa = np.stack((birdeye_thresh_warped,birdeye_thresh_warped,birdeye_thresh_warped), axis=2)
# print(drawed.shape)
# print(birdeye_thresh_warped_expa.shape)
# return drawed
# -
def find_lane_base_real(left_fitx, right_fitx, img_shape):
left_lane_pos = (left_fitx[-1] - img_shape[1]*0.5) * xm_per_pix
right_lane_pos = (right_fitx[-1] - img_shape[1]*0.5) * xm_per_pix
return left_lane_pos, right_lane_pos
# try to add binary image
def finding_lanes_pipeline(ori_image):
global mtx, dist, left_fitx_valid, right_fitx_valid, left_curverad_valid, right_curverad_valid, offset_valid
# Make the data ready, which is used for the transformation
pickle_file = open('camera_cal/wide_dist_pickle.p', 'rb')
dist_pickle=pickle.load(pickle_file)
pickle_file.close()
mtx = dist_pickle["mtx"]
dist = dist_pickle["dist"]
# transform the distorted image
undistort = undistortion_conduct2(ori_image)
# use gradient methode
thresh = combined_gradx_s(undistort, ksize = 3)
# perspective transform
# birdeye_thresh_warped, perspective_M = thresh_warp(thresh, 9, 6, mtx, dist)
birdeye_thresh_warped, perspective_M = thresh_warp(thresh)
# generate polynomial based on the pixels
left_fitx, right_fitx, ploty, leftx, lefty, rightx, righty = fit_polynomial(birdeye_thresh_warped)
left_curverad, right_curverad, offset = measure_curvature_offset(birdeye_thresh_warped, leftx, lefty, rightx, righty)
left_lane_pos, right_lane_pos = find_lane_base_real(left_fitx, right_fitx, birdeye_thresh_warped.shape)
valid = sanity_check(left_curverad, right_curverad, left_lane_pos, right_lane_pos)
# print("left_curverad is: ", left_curverad)
# print("right_curverad is: ", right_curverad)
# print("left_lane_pos is: ", left_lane_pos)
# print("right_lane_pos is: ", right_lane_pos)
# print(valid)
# drawed = drawing_area(birdeye_thresh_warped, ori_image, left_fitx, right_fitx, ploty)
if(valid==0):
left_fitx_valid = left_fitx
right_fitx_valid = right_fitx
left_curverad_valid = left_curverad
right_curverad_valid = right_curverad
offset_valid = offset
drawed = drawing_area(birdeye_thresh_warped, undistort, left_fitx_valid, right_fitx_valid, ploty) # changed to use the undistorted frames as output for more accurate results
put_lane_info_on_video(drawed, left_curverad_valid, right_curverad_valid, offset_valid)
birdeye_thresh_warped_expa = np.stack((birdeye_thresh_warped,birdeye_thresh_warped,birdeye_thresh_warped), axis=2)
birdeye_thresh_warped_expa *= 255
# plt.imshow(birdeye_thresh_warped)
# print(undistort.shape)
combi_stack = np.vstack((birdeye_thresh_warped_expa,drawed))
return combi_stack
plt.imshow(finding_lanes_pipeline(mpimg.imread('test_images/test6.jpg')))
# ## Test on Video and Generate result
# +
# for project_video.mp4
white_output = 'test_videos_output/project_video.mp4'
# clip1 = VideoFileClip("project_video.mp4").subclip(41,43)
clip1 = VideoFileClip("project_video.mp4")
# # for challenge_video.mp4
# white_output = 'test_videos_output/challenge_video.mp4'
# # clip1 = VideoFileClip("challenge_video.mp4").subclip(0,5)
# clip1 = VideoFileClip("challenge_video.mp4")
white_clip = clip1.fl_image(finding_lanes_pipeline)
# %time white_clip.write_videofile(white_output, audio=False)
# +
# HTML("""
# <video width="960" height="540" controls>
# <source src="{0}">
# </video>
# """.format(white_output))
# -
# ### Outlook, potential improvement
# +
# # Define a class to receive the characteristics of each line detection
# class Line():
# def __init__(self):
# # was the line detected in the last iteration?
# self.detected = False
# # x values of the last n fits of the line
# self.recent_xfitted = []
# #average x values of the fitted line over the last n iterations
# self.bestx = None
# #polynomial coefficients averaged over the last n iterations
# self.best_fit = None
# #polynomial coefficients for the most recent fit
# self.current_fit = [np.array([False])]
# #radius of curvature of the line in some units
# self.radius_of_curvature = None
# #distance in meters of vehicle center from the line
# self.line_base_pos = None
# #difference in fit coefficients between last and new fits
# self.diffs = np.array([0,0,0], dtype='float')
# #x values for detected line pixels
# self.allx = None
# #y values for detected line
| Code.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + id="hJ2uCA6BHd7k"
import sys
import subprocess
import pkg_resources
required = {'numpy', 'pandas', 'pathlib', 'nltk'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
if missing:
python = sys.executable
subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)
# + id="SL-1kgeNHd7n"
import numpy as np
import pandas as pd
import json
# + [markdown] id="_rdDiBezHd7o"
# # Import data
# + id="NniVRZqmHd7p"
DATASET_PATH = './artifacts/merged.json'
# + colab={"base_uri": "https://localhost:8080/", "height": 676} id="s7idD28THd7q" outputId="aa6d91b9-e7fb-4241-9093-a43a9c3aa9db"
dataset = None
with open(DATASET_PATH) as json_file:
dataset_raw = json.load(json_file)
columns = dataset_raw['catalog'][0].keys()
dataset = pd.DataFrame(columns=columns, data=dataset_raw['catalog'])
# transormations
for index, row in dataset.iterrows():
if row['category'] == '#comp-comments':
row['article_id'] = row['article_id'][:-len('/#comp-comments-button')]
url = row['article_id']
row['category'] = url[url.rfind('/')+1:url.rfind('-')]
dataset
# + colab={"base_uri": "https://localhost:8080/"} id="0ght8ciAHd7r" outputId="73d7135d-6833-4119-fb5d-e81eb97cb562"
dataset['category'].value_counts()[:20]
# + colab={"base_uri": "https://localhost:8080/", "height": 641} id="IphfjqLfHd7s" outputId="738fdcba-46cb-40d3-aa46-52790525886d"
categories_to_keep = ['business', 'health', 'uk-politics', 'entertainment-arts']
max_category_size = 1000
dataset = dataset[dataset['category'].isin(categories_to_keep)]
category_datasets = []
for category in categories_to_keep:
category_datasets.append(dataset[dataset['category'] == category][:max_category_size])
result = category_datasets[0]
for ds in category_datasets[1:]:
result = result.append(ds)
dataset = result
dataset
# + colab={"base_uri": "https://localhost:8080/"} id="xq1yOJE2Hd7s" outputId="f8e903d7-d673-4e2c-d589-482c63087db4"
print(dataset.isna().sum())
dataset = dataset.dropna()
# + colab={"base_uri": "https://localhost:8080/", "height": 367} id="ixJC2AIGHd7t" outputId="f1591396-faa3-4b58-ddbd-9f25836ac88d"
s = dataset['category'].value_counts()
s.plot(kind='bar')
# + [markdown] id="is1DhJ-FHd7t"
# # Text Pre-Processing - Stop-word removal, Stemming, Vectorization
# + colab={"base_uri": "https://localhost:8080/"} id="GTQ9nIIZHd7t" outputId="23aee8f7-2647-4fdc-f1cb-5d1ceea24a5e"
import re
from os import listdir
from os.path import isfile, join
import json
import pathlib
import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
nltk.download('stopwords')
# + id="MRatxR9qHd7u"
import sklearn
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import CountVectorizer
stop_words = stopwords.words('english')
VECTORIZER = None
def clean(text):
cleaned = re.sub(re.compile('<.*?>'), '', text)
cleaned = re.sub('[^A-Za-z0-9]+', ' ', cleaned)
cleaned = cleaned.lower()
return cleaned
def tokenize(text):
tokens = nltk.word_tokenize(text)
return tokens
def remove_stop_words(tokens):
filtered_tokens = [token for token in tokens if token not in stop_words]
return filtered_tokens
def apply_stemming(tokens):
stemmer = PorterStemmer()
stemmed_tokens = [stemmer.stem(token) for token in tokens]
return stemmed_tokens
def vectorize(tokens, vectorizer):
vectorized_tokens = vectorizer.fit(tokens)
return vectorized_tokens
def preprocess_text(text):
cleaned_text = clean(text)
tokens = tokenize(cleaned_text)
tokens = remove_stop_words(tokens)
tokens = remove_stop_words(tokens)
tokens = apply_stemming(tokens)
return tokens
def vectorize(vectorizer, preprocessed_text):
vectorized = vectorizer.transform([preprocessed_text]).toarray()
return vectorized
# + colab={"base_uri": "https://localhost:8080/", "height": 641} id="ha3a8abhHd7v" outputId="02e686bb-8929-469b-b40e-87d4465bc10e"
# dataset = dataset[:100]
# preprocess corpus
for index, row in dataset.iterrows():
row['text'] = preprocess_text(row['text'])
row['text'] = ' '.join(row['text'])
dataset
# + colab={"base_uri": "https://localhost:8080/"} id="M9CtijPSHd7v" outputId="97b19a67-021a-4ece-8b85-abbfdba333ca"
# # create vectorizer
all_texts = dataset['text'].tolist()
vectorizer = CountVectorizer(lowercase=False)
vectorizer.fit(all_texts)
print(len(vectorizer.vocabulary_.keys()))
# vectorizer.vocabulary_
# + colab={"base_uri": "https://localhost:8080/", "height": 641} id="eylcYqLuHd7w" outputId="97b59499-dc6e-4726-d0a2-acd3098a4ad1"
# vectorize preprocessed text
for index, row in dataset.iterrows():
row['text'] = vectorize(vectorizer, row['text'])[0]
dataset
# + colab={"base_uri": "https://localhost:8080/"} id="fTjzEaZqHd7w" outputId="d062a508-a8b3-42f4-8070-b6e00f267c79"
print(dataset.iloc[0]['text'])
print(len(dataset.iloc[0]['text']))
# + [markdown] id="7-jRFX54Hd7x"
# # Classification
# + id="afmJjNmlHd7x"
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import SGDClassifier
from sklearn.neighbors import KNeighborsClassifier
# + id="TKw88gfcIqwf"
X_train, X_valid, y_train, y_valid = train_test_split(dataset['text'], dataset['category'], test_size=0.1, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
# + id="BceqpruRPF13"
X_train_array = []
for i in X_train:
X_train_array.append(i);
X_test_array = []
for i in X_test:
X_test_array.append(i);
# + colab={"base_uri": "https://localhost:8080/"} id="KFvK6CiTQf3w" outputId="834c5aa6-8f59-45a2-9c92-2091706ee65e"
rfc = RandomForestClassifier(n_estimators=1000, random_state=0)
sgd = SGDClassifier()
knb = KNeighborsClassifier(n_neighbors=10)
gnb = GaussianNB()
svc = SVC()
gbc = GradientBoostingClassifier()
rfc.fit(X_train_array, y_train)
sgd.fit(X_train_array, y_train)
knb.fit(X_train_array, y_train)
gnb.fit(X_train_array, y_train)
svc.fit(X_train_array, y_train)
gbc.fit(X_train_array, y_train)
# + colab={"base_uri": "https://localhost:8080/"} id="a5WIuu4VIq7g" outputId="1ff1db3d-2168-4e25-8e83-777387123407"
print('SGD classifier metrics')
predicted_sgd = sgd.predict(X_test_array)
print(metrics.classification_report(predicted_sgd, y_test))
# + colab={"base_uri": "https://localhost:8080/"} id="nwPglFX1Iq-F" outputId="fe8f9a7f-5560-44f8-ee21-4ce692f892c2"
print('K Neighbours classifier metrics')
predicted_knb = knb.predict(X_test_array)
print(metrics.classification_report(predicted_knb, y_test))
# + colab={"base_uri": "https://localhost:8080/"} id="aE-V-lkCIrAd" outputId="6bae5b0a-fca7-430c-cc46-aad7bb3e464a"
print('Random Forest classifier metrics')
predicted_rfc = rfc.predict(X_test_array)
print(metrics.classification_report(predicted_rfc, y_test))
# + colab={"base_uri": "https://localhost:8080/"} id="tgjIDwxWaGGH" outputId="191619d9-78be-4f01-dd95-5d75f410ae36"
print('Gaussian Naive Bayes classifier metrics')
predicted_gnb = gnb.predict(X_test_array)
print(metrics.classification_report(predicted_gnb, y_test))
# + colab={"base_uri": "https://localhost:8080/"} id="lAsgMao6aJaM" outputId="0fcfd091-073c-4345-853d-40a36adf7f17"
print('SVC classifier metrics')
predicted_svc = svc.predict(X_test_array)
print(metrics.classification_report(predicted_svc, y_test))
# + colab={"base_uri": "https://localhost:8080/"} id="fqfjd4PdaJgf" outputId="84717c54-eb66-4ec8-c818-a64c51853a57"
print('Gradient boosting classifier metrics')
predicted_gbc = gbc.predict(X_test_array)
print(metrics.classification_report(predicted_gbc, y_test))
| news_parser/Classification.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Undertale & Deltarune Soundtrack Generator
# ---
# ## Table of Contents
#
# 0. [**Table of Contents**](#Table-of-Contents)
#
# 1. [**Imports**](#Imports)
#
# 2. [**Data Processing**](#Data-Processing)
#
# 2.1 [Data Loading](#Data-Loading)
#
# 2.2 [Data Preprocessing](#Data-Preprocessing)
#
# 2.3 [Dataset & Dataloader Definition](#Dataset-&-Dataloader-Definition)
#
# 3. [**Model Definition**](#Model-Definition)
#
# 4. [**Hyperparameters & Instantiation**](#Hyperparameters-&-Instantiation)
#
# 5. [**Training**](#Training)
# ---
# ## Imports
# [(go to top)](#Undertale-&-Deltarune-Soundtrack-Generator)
#
# Import required packages
# +
import os # File handling
import itertools # chain() for merging lists
import random # Shuffling
import collections # Useful tools like Counter, OrderedDict
import math # For... math
from decimal import Decimal # Scientific notations in string formatting
from time import time # For use in progress bar
import tqdm.auto as tqdm # Progress bar
import torch # Deep Learning Framework
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt # Plotting training progress
from matplotlib.ticker import AutoLocator
# %matplotlib inline
fig_bg_color = "lightsteelblue"
plot_bg_color = "slategray"
fontsize = 20
# -
# ---
# ## Data Processing
# [(go to top)](#Undertale-&-Deltarune-Soundtrack-Generator)
# ### Data Loading
# [(go to top)](#Undertale-&-Deltarune-Soundtrack-Generator)
#
# Read the text files in the target directory.
#
# Do some processing to make sure the texts are clean.
# + code_folding=[0]
def get_texts(texts_dir):
if not os.path.isdir(texts_dir):
raise FileNotFoundError("given text directory not found: {}".format(texts_dir))
texts = []
for text_path in (file.path for file in os.scandir(texts_dir) if file.is_file() and file.name.endswith(".txt")):
with open(file=text_path, mode='r', encoding="utf-8") as text_file:
text = text_file.read().strip()
if not text.replace(' ', '').isdigit():
raise RuntimeError("one or more characters other than digits and white spaces are detected: {}".format(text_path))
while " " in text:
text = text.replace(" ", ' ')
texts.append((text_path, text))
return dict(texts)
[(os.path.split(text_path)[1], text[:20]) for text_path, text in get_texts("./source/converted_texts").items()]
# -
# ### Data Preprocessing
# [(go to top)](#Undertale-&-Deltarune-Soundtrack-Generator)
# Get integers out of the text and make lists of ints.
#
# These lists can be used for the input of the models, or be further processed to compress or simplify the sequences.
#
# In this notebook, I'll leave the data as it is and do note-by-note. (Similar to Character-By-Character approach)
# + code_folding=[0]
def texts_to_intlists(text_list):
intlists = []
for i, text in enumerate(iterable=text_list):
int_strings = text.split(' ')
if not all(int_str.isdigit() for int_str in int_strings):
raise RuntimeError("non-digit string detected in text {}".format(i))
ints = [int(int_str) for int_str in int_strings]
intlists.append(ints)
return intlists
print([ints[:10] for ints in texts_to_intlists(get_texts("./source/converted_texts").values())])
# -
# ### Dataset & Dataloader Definition
# [(go to top)](#Undertale-&-Deltarune-Soundtrack-Generator)
# Create a Dataset class from which training data can be sampled.
#
# This Dataset should convert the encoded sequence above into tensors
#
# and have a method for shuffling the order of multiple sequences while
#
# leaving the patterns inside of each sequence untouched.
class UndertaleDeltaruneDataset(Dataset):
def __init__(self, texts_dir, batch_size=1):
self.texts = get_texts(texts_dir) # read and get a dictionary of {file_paths: text_contents}
self.sequences = texts_to_intlists(self.texts.values())
self.texts_dir = texts_dir
self.batch_size = batch_size
def __len__(self):
return self.batch_size
def data_len(self):
return sum([len(sequence) for sequence in self.sequences])
def __getitem__(self, index):
shuffled_list = list(itertools.chain(*random.sample(self.sequences, len(self.sequences))))
inputs = torch.LongTensor(shuffled_list[:-1])
labels = torch.LongTensor(shuffled_list[1:])
return inputs, labels
# Create a custom class that loads the data from the dataset above and
#
# allows iteration over the dataset, yielding a small sequence batch at a time.
class UDBatchLoader:
def __init__(self, ud_dataset, batch_size, sequence_len, drop_last=False, batch_first=True):
self.ud_dataset = ud_dataset
self.batch_size = batch_size
self.sequence_len = sequence_len
self.drop_last = drop_last
self.batch_first = batch_first
def __len__(self):
if self.drop_last:
return math.floor((self.ud_dataset.data_len() - 1) / self.sequence_len)
return math.ceil((self.ud_dataset.data_len() - 1) / self.sequence_len)
def generator(self):
seq_len = self.sequence_len
n_seq_batches = self.__len__()
batch_first = self.batch_first
input_batch, target_batch = next(iter(DataLoader(self.ud_dataset, self.batch_size)))
if not batch_first:
input_batch = input_batch.transpose(0, 1).contiguous()
target_batch = target_batch.transpose(0, 1).contiguous()
for start, end in zip(range(0, seq_len * n_seq_batches, seq_len), range(seq_len, (seq_len + 1) * n_seq_batches, seq_len)):
if batch_first:
yield (input_batch[:, start:end].contiguous(), target_batch[:, start:end].contiguous())
else:
yield (input_batch[start:end], target_batch[start:end])
def __iter__(self):
return self.generator()
# ---
# ## Model Definition
# [(go to top)](#Undertale-&-Deltarune-Soundtrack-Generator)
#
# Define the model architectures.
# ### Generator
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
self.init_hidden0 = nn.Parameter(torch.randn(1, 1, 256))
self.init_hidden1 = nn.Parameter(torch.randn(1, 1, 256))
self.init_hidden2 = nn.Parameter(torch.randn(1, 1, 256))
self.embed = nn.Embedding(num_embeddings=129, embedding_dim=128)
self.norm0 = nn.LayerNorm(128)
self.gru0 = nn.GRU(input_size=128, hidden_size=256, batch_first=True)
self.norm1 = nn.LayerNorm(256)
self.gru1 = nn.GRU(input_size=256, hidden_size=256, batch_first=True)
self.norm2 = nn.LayerNorm(256)
self.gru2 = nn.GRU(input_size=256, hidden_size=256, batch_first=True)
self.fc0 = nn.Sequential(
nn.LayerNorm(256),
nn.Linear(in_features=256, out_features=512)
)
self.fc1 = nn.Sequential(
nn.ReLU(),
nn.LayerNorm(512),
nn.Linear(in_features=512, out_features=256)
)
self.fc2 = nn.Sequential(
nn.ReLU(),
nn.LayerNorm(256),
nn.Linear(in_features=256, out_features=129)
)
def forward(self, x, hiddens=None, return_all_hiddens=False):
if hiddens is None:
hiddens = self.get_init_hiddens(x.size(0))
if return_all_hiddens:
internal_hiddens = []
x = self.embed(x)
x, new_hidden0 = self.gru0(self.norm0(x), hiddens[0])
if return_all_hiddens:
internal_hiddens.append(x)
x, new_hidden1 = self.gru1(self.norm1(x), hiddens[1])
if return_all_hiddens:
internal_hiddens.append(x)
x, new_hidden2 = self.gru2(self.norm2(x), hiddens[2])
if return_all_hiddens:
internal_hiddens.append(x)
x = self.fc0(x)
x = self.fc1(x)
x = self.fc2(x)
if return_all_hiddens:
return x, [new_hidden0, new_hidden1, new_hidden2], internal_hiddens
return x, [new_hidden0, new_hidden1, new_hidden2]
def get_init_hiddens(self, n_batches):
return [self.init_hidden0.repeat(1, n_batches, 1),
self.init_hidden1.repeat(1, n_batches, 1),
self.init_hidden2.repeat(1, n_batches, 1)]
# ### Discriminator
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.init_hidden0 = nn.Parameter(torch.randn(2, 1, 128))
self.init_hidden1 = nn.Parameter(torch.randn(2, 1, 128))
self.init_hidden2 = nn.Parameter(torch.randn(2, 1, 128))
self.norm0 = nn.LayerNorm(768)
self.gru0 = nn.GRU(input_size=768, hidden_size=128, batch_first=True, bidirectional=True)
self.norm1 = nn.LayerNorm(256)
self.gru1 = nn.GRU(input_size=256, hidden_size=128, batch_first=True, bidirectional=True)
self.norm2 = nn.LayerNorm(256)
self.gru2 = nn.GRU(input_size=256, hidden_size=128, batch_first=True, bidirectional=True)
self.fc0 = nn.Sequential(
nn.LayerNorm(256),
nn.Linear(in_features=256, out_features=512)
)
self.fc1 = nn.Sequential(
nn.ReLU(),
nn.LayerNorm(512),
nn.Linear(in_features=512, out_features=256)
)
self.fc2 = nn.Sequential(
nn.ReLU(),
nn.LayerNorm(256),
nn.Linear(in_features=256, out_features=1)
)
def forward(self, x, hiddens=None):
if hiddens is None:
hiddens = self.get_init_hiddens(x.size(0))
x, new_hidden0 = self.gru0(self.norm0(x), hiddens[0])
x, new_hidden1 = self.gru1(self.norm1(x), hiddens[1])
x, new_hidden2 = self.gru2(self.norm2(x), hiddens[2])
### Consider only the final outputs from both directions by:
### 1) separating the directions,
### 2) taking the last timestep's output for forward direction([:, -1, 0, :])
### and the first timestep's output for backward direction([:, 0, 1, :]),
### 3) then fianlly resizing the selected output into [n_batch, features] form.
x = x.view(*x.shape[:-1], 2, -1)[:, [-1, 0], [0, 1], :].view(x.size(0), -1)
x = self.fc0(x)
x = self.fc1(x)
x = self.fc2(x)
return x, [new_hidden0, new_hidden1, new_hidden2]
def get_init_hiddens(self, n_batches):
return [self.init_hidden0.repeat(1, n_batches, 1),
self.init_hidden1.repeat(1, n_batches, 1),
self.init_hidden2.repeat(1, n_batches, 1)]
# ---
# ## Training
# [(go to top)](#Undertale-&-Deltarune-Soundtrack-Generator)
def free_running_generation(generator, inputs, seq_len, return_all_hiddens=False):
"""
Params
======
generator (Generator): the generator model.
inputs (LongTensor): 2D tensor with dimensions [n_batches, 1].
If the given dimensions are [n_batches, seq_len],
then only the first timestep is used.
seq_len (int): length of sequence to generate.
return_all_hiddens (bool, optional): whether to retrieve the internal hidden states
for all timesteps from every RNN layer. (default: False)
Returns
=======
output_sequence (LongTensor): tensor of generated outputs.
hiddens (list[Tensor]): updated hidden states.
internal_hiddens (list[Tensor]): list of tensors containing internal hidden states
for all timesteps from every RNN layer. Returned only
if `return_all_hiddens` is True.
"""
output_sequence = []
if return_all_hiddens:
internal_hiddens = []
hiddens = generator.get_init_hiddens(inputs.size(0))
x = inputs[:, :1]
for i in range(seq_len):
if return_all_hiddens:
y, hiddens, current_internal_hiddens = generator(x, hiddens, return_all_hiddens=True)
internal_hiddens.append(current_internal_hiddens)
else:
y, hiddens = generator(x, hiddens, return_all_hiddens=False)
y = torch.multinomial(y.squeeze(1).softmax(dim=-1), num_samples=1)
output_sequence.append(y)
x = y
output_sequence = torch.cat(output_sequence, dim=1)
if return_all_hiddens:
internal_hiddens = [torch.cat(layer_hiddens, dim=1) for layer_hiddens in zip(*internal_hiddens)]
return output_sequence, hiddens, internal_hiddens
return output_sequence, hiddens
def generator_loss(discriminator, output_teacher, target_teacher, b_seq_teacher, b_seq_free,
teacher_forcing_loss=True, free_teacher_behavior_loss=True, teacher_free_behavior_loss=True):
"""
Params
======
discriminator (Discriminator): the Discriminator model.
output_teacher (Tensor): output of the Generator during teacher-forcing mode.
target_teacher (Tensor): target for the Generator during teacher-forcing mode.
b_seq_teacher (Tensor): behavior sequence from Generator during teacher-forcing mode.
Must have dimensions [n_batches, seq_len, behavior_size].
b_seq_free (Tensor): behavior sequence from Generator during free-running mode.
Assumed to have the same dimensionality as `b_seq_teacher`.
teacher_forcing_loss (bool): whether to calculate and return the loss for teacher-forced training. (default: True)
free_teacher_behavior_loss (bool): whether to calculate and return the loss for matching the
free-running behavior to the teacher-forced behavior.(default: True)
teacher_free_behavior_loss (bool): whether to calculate and return the loss for matching the
teacher-forced behavior to the free-running behavior.(default: True)
Returns
=======
teacher_forcing_loss (Tensor): loss for maximizing the likelihood of the data
during teacher-forcing mode. Returned if
`teacher_forcing_loss` is True.
free_teacher_behavior_loss (Tensor): loss for changing the free-running behavior so that
it better matches the teacher-forced behavior,
considering the latter fixed. Returned if
`free_teacher_behavior_loss` is True.
teacher_free_behavior_loss (Tensor): loss for making the teacher-forced behavior
indistinguishable from the free-running behavior.
Returned if `teacher_free_behavior_loss` is True.
"""
losses = []
if teacher_forcing_loss:
losses.append(F.cross_entropy(output_teacher.view(-1, output_teacher.size(-1)), target_teacher.view(-1)))
if free_teacher_behavior_loss:
hiddens = discriminator.get_init_hiddens(n_batches=b_seq_free.size(0))
raw_preds, _ = discriminator(b_seq_free, hiddens)
losses.append(F.binary_cross_entropy_with_logits(raw_preds, torch.ones_like(raw_preds)))
if teacher_free_behavior_loss:
hiddens = discriminator.get_init_hiddens(n_batches=b_seq_teacher.size(0))
raw_preds, _ = discriminator(b_seq_teacher, hiddens)
losses.append(F.binary_cross_entropy_with_logits(raw_preds, torch.zeros_like(raw_preds)))
return losses
def discriminator_loss(discriminator, b_seq_teacher, b_seq_free, return_acc=False):
"""
Params
======
discriminator (Discriminator): the Discriminator model.
b_seq_teacher (Tensor): behavior sequence from Generator during teacher-forcing mode.
Must have dimensions [n_batches, seq_len, behavior_size].
b_seq_free (Tensor): behavior sequence from Generator during free-running mode.
Assumed to have the same dimensionality as `b_seq_teacher`.
return_acc (bool): whether to return the Discriminator accuracy or not. (default: False)
Returns
=======
discriminator_loss (Tensor): the Discriminator loss as a scalar tensor.
discriminator_acc (float): accuracy of the Discriminator for the given data.
Returned only if `return_acc` is True.
"""
### Ensure that gradients will flow only through the discriminator and not the generator
b_seq_teacher = b_seq_teacher.detach()
b_seq_free = b_seq_free.detach()
inputs = torch.cat([b_seq_teacher, b_seq_free], dim=0)
targets = torch.cat([b_seq_teacher.new_ones(b_seq_teacher.size(0), 1),
b_seq_free.new_zeros(b_seq_free.size(0), 1)], dim=0)
hiddens = discriminator.get_init_hiddens(n_batches=inputs.size(0))
raw_preds, _ = discriminator(inputs, hiddens)
if return_acc:
preds = raw_preds.sigmoid()
discriminator_loss = F.binary_cross_entropy(preds, targets, reduction='none')
discriminator_loss = discriminator_loss[:b_seq_teacher.size(0)].mean() + discriminator_loss[b_seq_teacher.size(0):].mean() ### Calculate separate average losses
discriminator_acc = (preds.gt(0.5) == targets.byte()).float().mean().item()
return discriminator_loss, discriminator_acc
else:
discriminator_loss = F.binary_cross_entropy_with_logits(raw_preds, targets, reduction='none')
discriminator_loss = discriminator_loss[:b_seq_teacher.size(0)].mean() + discriminator_loss[b_seq_teacher.size(0):].mean() ### Calculate separate average losses
return discriminator_loss
# +
seed = 10
n_epochs = 1000
batch_size = 64
sequence_length = 600
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
random.seed(seed)
torch.manual_seed(seed)
ud_dataset = UndertaleDeltaruneDataset("./source/converted_texts", batch_size)
ud_loader = UDBatchLoader(ud_dataset, batch_size, sequence_length, drop_last=False, batch_first=True)
generator = Generator().to(device)
discriminator = Discriminator().to(device)
generator_optimizer = optim.Adam(generator.parameters(), lr=1e-4)
discriminator_optimizer = optim.Adam(discriminator.parameters(), lr=1e-4)
history = {}
print()
print('Data Sequence Total Length:', ud_dataset.data_len())
print()
print(generator)
print()
print(discriminator)
# +
teacher_forcing_always_on = True
i = 0
while True:
for inputs, targets in ud_loader:
inputs = inputs.to(device)
targets = targets.to(device)
teacher_forcing_outputs, _, teacher_internal_hiddens = generator(inputs, return_all_hiddens=True)
generated_sequence, _, free_internal_hiddens = free_running_generation(generator, inputs, inputs.size(1), return_all_hiddens=True)
b_seq_teacher = torch.cat(teacher_internal_hiddens, dim=-1)
b_seq_free = torch.cat(free_internal_hiddens, dim=-1)
D_loss, D_acc = discriminator_loss(discriminator, b_seq_teacher, b_seq_free, return_acc=True)
if D_acc < 0.99: # If too good, don't train the Discriminator
discriminator_optimizer.zero_grad()
D_loss.backward()
discriminator_optimizer.step()
D_loss = D_loss.item()
if D_acc > 0.75: # If too bad, don't use the Discriminator to train the Generator
t_force_loss, ft_b_loss, tf_b_loss = generator_loss(discriminator, teacher_forcing_outputs, targets,
b_seq_teacher, b_seq_free,
teacher_forcing_loss=True,
free_teacher_behavior_loss=True,
teacher_free_behavior_loss=True)
G_loss = (t_force_loss + ft_b_loss + tf_b_loss) / 3
generator_optimizer.zero_grad()
G_loss.backward()
generator_optimizer.step()
G_loss = G_loss.item()
t_force_loss = t_force_loss.item()
ft_b_loss = ft_b_loss.item()
tf_b_loss = tf_b_loss.item()
else:
if teacher_forcing_always_on:
t_force_loss, = generator_loss(discriminator, teacher_forcing_outputs, targets,
b_seq_teacher, b_seq_free,
teacher_forcing_loss=True,
free_teacher_behavior_loss=False,
teacher_free_behavior_loss=False)
G_loss = t_force_loss
generator_optimizer.zero_grad()
G_loss.backward()
generator_optimizer.step()
G_loss = G_loss.item()
t_force_loss = t_force_loss.item()
else:
G_loss = float('nan')
t_force_loss = float('nan')
ft_b_loss = float('nan')
tf_b_loss = float('nan')
G_acc = (teacher_forcing_outputs.argmax(dim=-1) == targets).float().mean().item()
print("[Update {}]".format(i))
print("Discriminator")
print("=============")
print(" Loss:", D_loss)
print(" Acc:", D_acc)
print("Generator")
print("=============")
print(" Loss:", G_loss)
print(" Teacher-Force:", t_force_loss)
print(" FreeToTeacher:", ft_b_loss)
print(" TeacherToFree:", tf_b_loss)
print(" Acc:", G_acc)
print("####################################")
print()
i += 1
if i % 50 == 0:
torch.save(generated_sequence.cpu().numpy(), "professor_forcing_temp/{}.pth".format(i))
# -
torch.save({'g': generator.state_dict(), 'd': discriminator.state_dict()}, 'professor_forcing_temp/GD_8500.pth')
generated_sequence = free_running_generation(generator, inputs[:1], 50000, return_all_hiddens=False)[0]
torch.save(generated_sequence[0].cpu().numpy(), "professor_forcing_temp/generated_sequence.pth")
# ---
| Undertale_Deltarune_Soundtrack_Generator_(Professor_Forcing).ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/HugoGallardoR/Magister_TI/blob/main/202109221125A4B5E3250F527A7A__DL_tarea1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="g2cmRd0lnU69"
# # **Clasificaciรณn de Documentos**
# En este notebook, experimentarรกs con el dataset Reuters. Reuters es un dataset de documentos en donde cada documento es representado por un conjunto de palabras desde un vocabulario. El dataset contiene 46 clases. Usaremos un mรฉtodo conveniente de Keras colo para obtener el dataset:
# + id="TPQnbFWwVWvG"
from tensorflow.keras.datasets import reuters
import numpy as np
import matplotlib.pyplot as plt
import copy
import random
import time
# + [markdown] id="7dDEWclKuAk2"
# Obtenemos el dataset y especificamos el nรบmero de palabras del vocaulario original que queremos usar. Este nรบmero se convertirรก en la dimensiรณn de nuestros datos. La funciรณn de Keras retorna un array de listas, donde cada lista es una secuencia de รญndices de palabras en un documento. Por ejemplo, la secuencia [1, 5, 8] significa que las palabras 1, 5, y 8 estรกn contenidas en el documento. Para pre-procesar esta data, la convertiremos en un one-hot encoding (un vector que contiene un valor 1 en la palabra que aparece en el documento)
# + id="tk4dgSHuV1jt" colab={"base_uri": "https://localhost:8080/"} outputId="4dfed03f-be34-4e15-8528-5326dbda73be"
def to_one_hot(sequences, dimension):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1
return results
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words = 10000)
train_data = to_one_hot(train_data, 10000)
test_data = to_one_hot(test_data, 10000)
train_data = train_data.astype(np.float32)
test_data = test_data.astype(np.float32)
# + [markdown] id="4L_Q-tbcmh1d"
# Ahora la data tiene la forma de una matriz con dimensiones NxM, donde N es la cantidad de muestras y M es la dimensiรณn de cada muestra.
# + colab={"base_uri": "https://localhost:8080/"} id="K1YHLnZRmsP9" outputId="1074c52e-a710-4212-bc83-c22e51dcd6ed"
print(f'Tamaรฑo de datos de entrenamiento: {train_data.shape}')
print(f'Tamaรฑo de datos de test: {test_data.shape}')
#Existen 8982 muestras para entrenamiento y 2246 muestras para test
# + [markdown] id="_iFxcUJ3zyR1"
# ## **Tarea**
# El objetivo de esta tarea es implementar una red neuronal en Pytorch que nos permita clasificar el dataset Reuters. La red neuronal implementada debe alcanzar al menos un accuracy de 35% sobre el conjunto de test.
# + [markdown] id="uhdyD7TInMTd"
# ## 1. Preparar la data
# Empezaremos por preparar la data para poder usarla en Pytorch. Para eso haremos uso de los DataLoaders. En el cรณdigo inicial, el tamaรฑo de batch estรก configurado en 1, pero puedes cambiar este valor y experimentar (se sugiere usar valores de batch_size mรกs grandes que uno).
# + id="6OnII2BMBTs2"
import torch.utils.data as data
import torch.nn as nn
import torch.optim as optim
import torch
import torch.nn.functional as F
#Se comienza utilizando un batch_size de 10
train_loader = data.DataLoader(list(zip(train_data, train_labels)), shuffle=True, batch_size=100)
test_loader = data.DataLoader(list(zip(test_data, test_labels)), batch_size=100)
# + id="wTXydqDTjFcw" colab={"base_uri": "https://localhost:8080/"} outputId="1a849f15-0dde-4359-d36f-042310ae7364"
# Cuando iteramos sobre el loader, obtenemos cada mini-batch y lo mostramos en pantalla
# Cada mini-batch es un conjunto de muestras con su respectivo conjunto de etiquetas
for sample in test_loader:
print(sample)
# + [markdown] id="RjudrYzColns"
# ## 2. Creaciรณn de red neuronal
# A continuaciรณn, crea tu red neuronal especificando una clase con los mรฉtodos constructor y forward
# + id="1TOtwJKMn8sx"
class RedNeuronal(nn.Module):
#Constructor es para definiciones de variables. Aquรญ recibimos como parรกmetro las dimensiones de la data de entrada
# y la cantidad de clases de salida
#OBS:Ocupo redes con 10000 para hacer match con el input
def __init__(self, input_dim, output_dim):
super().__init__()
self.fc1 = nn.Linear(input_dim, 10000)
self.fc2 = nn.Linear(10000, 5000)
self.fc3 = nn.Linear(5000, output_dim)
#Aquรญ tienes que especificar la arquitectura de tu red.
def forward(self, input):
#Aquรญ especificas lo que pasa cuando a la red se le pone datos
batch_size = input.shape[0]
#View modifica la forma de la data, para que el input tenga la forma de batch_size
input = input.view(batch_size, -1)
h_1 = F.relu(self.fc1(input))
h_2 = F.relu(self.fc2(h_1))
y_pred = self.fc3(h_2)
#Retorna la salida de la red, y el vector de salida de la segunda capa (Para posterior analisis)
return y_pred, h_2
# + [markdown] id="YRCrQUaipdro"
# Luego, creas una instancia de tu red neuronal. A continuaciรณn debes especificar el tamaรฑo de la entrada y el tamaรฑo de la salida para instanciar tu red.
# + id="mIc11MFUpMYT"
# Creamos el modelo
## Aquรญ tienes que cambiar estas dimensiones de acuerdo al problema a resolver
INPUT_DIM = 10000
OUTPUT_DIM = 46
model = RedNeuronal(INPUT_DIM, OUTPUT_DIM)
# + [markdown] id="IxAFYhzkp03V"
# Configuramos el optimizador y la funciรณn de Loss
# + id="yH48kdvFpsiS"
#Crear el objeto para la optimizaciรณn.
optimizer = optim.SGD(model.parameters(), lr=0.001)
#Definir la funciรณn Loss
#En Pytorch, CrossEntropyLoss incluye la activaciรณn Softmax y la funciรณn de costo "negative log-likelihood"
#Van juntas por cuestiones de eficiencia
criterion = nn.CrossEntropyLoss()
#En Pytorch nosotros decidimos dรณnde correr nuestro programa, asรญ que inicializamos el
# dispositivo dependiendo si tenemos un GPU o no
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#Enviamos el modelo y la funciรณn Loss al GPU
model = model.to(device)
criterion = criterion.to(device)
# + id="PO6ORo8sNH1b"
#Funciona para calcular el accuracy
def calculate_accuracy(y_pred, y):
top_pred = y_pred.argmax(1, keepdim=True)
correct = top_pred.eq(y.view_as(top_pred)).sum()
acc = correct.float()/y.shape[0]
return acc
# + [markdown] id="IRtu06_7qcnx"
# ## 3. Entrena tu red neuronal
#
# Entrena tu red neuronal usando Pytorch. Usa el ejemplo de clase para hacer el entrenamiento de tu red.
# + id="b_NdouqgrXBT"
#Se genera funcion de entrenamiento
#Se usan como inputs todo lo generado anteriormente
#iterator se ingresa la data de training generada con dataloader
def train(model, iterator, optimizer, criterion, device):
epoch_loss = 0
epoch_acc = 0
#Poner la red en modo entrenamiento
model.train()
#Training loop
#Se recorre toda la data con X:Valor de entrenamiento, Y:Etiqueta
for (x, y) in iterator:
x = x.to(device) #Data
y = y.long().to(device) #Labels
optimizer.zero_grad() #Limpiar gradientes
#Enviar data a red
y_pred, _ = model(x)
#Computar el loss
loss = criterion(y_pred, y)
#Computar el accuracy
acc = calculate_accuracy(y_pred, y)
#Computar gradientes
loss.backward()
#Aplicar reglas de actualizacion
optimizer.step()
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator)
# + id="pLYCWXZKNgdW"
def evaluate(model, iterator, criterion, device):
epoch_loss = 0
epoch_acc = 0
model.eval()
with torch.no_grad():
for (x, y) in iterator:
x = x.to(device)
y = y.long().to(device)
y_pred, _ = model(x)
loss = criterion(y_pred, y)
acc = calculate_accuracy(y_pred, y)
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator)
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
# + colab={"base_uri": "https://localhost:8080/"} id="Bk-UgWrYNj6s" outputId="8aa03953-c74f-4302-af07-70bfb92e72f1"
EPOCHS = 30
best_valid_loss = float('inf')
train_loss_history = []
val_loss_history = []
for epoch in range(EPOCHS):
start_time = time.time()
train_loss, train_acc = train(model, train_loader, optimizer, criterion, device)
valid_loss, valid_acc = evaluate(model, test_loader, criterion, device)
train_loss_history.append(train_loss)
val_loss_history.append(valid_loss)
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model.state_dict(), 'saved-model.pt')
end_time = time.time()
epoch_mins, epoch_secs = epoch_time(start_time, end_time)
print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s')
print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%')
print(f'\t Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc*100:.2f}%')
# + colab={"base_uri": "https://localhost:8080/", "height": 265} id="snrVLeJ8QDJ_" outputId="4e34dca8-36ad-4cfe-9647-d75280702825"
#Visualizar las perdidas
plt.figure()
plt.plot(train_loss_history, color='b')
plt.plot(val_loss_history, color='r')
plt.show()
| 202109221125A4B5E3250F527A7A__DL_tarea1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/urenajose/lambdata_urena/blob/main/Unit_3_1_assigment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="QPVdf_r0ZQj3" outputId="15c292b1-c12f-46fe-bb46-ebdb8e00dd1a" colab={"base_uri": "https://localhost:8080/"}
print("my repo is at:","https://github.com/urenajose/lambdata_urena")
# + id="bOD-VVfHXvNO"
import pandas as pd
import numpy as np
# + id="_jzokJXxk-g5" outputId="8f75df18-16e4-400a-df52-6172987ba39a" colab={"base_uri": "https://localhost:8080/"}
pip install -i https://test.pypi.org/simple/ lambdata-urena1==0.2.1
# + id="E-6YlNd0A_nI"
import lambdata_urena1 as ju
# + id="AdQcZCtRHdyZ"
#added two functions to my pkg is a float check if string is formatted as a float and datime_columns,
#pass a pd.df and a column with str with dates returns self pd.df with 3 extra columns for day, month and year
# + id="Lpps6QuhXskV"
df_shelter = pd.read_csv('https://raw.githubusercontent.com/urenajose/DS-Unit-2-Applied-Modeling/master/aac_shelter_outcomes.csv')
# + id="kCmmtKSWX4_A" outputId="3f194444-3584-4f01-e552-a705c0af46c8" colab={"base_uri": "https://localhost:8080/"}
df_shelter.info()
# + id="34FslYR2WWEv" outputId="9f2f8739-0b89-463e-c6e1-53a224bc1ec6" colab={"base_uri": "https://localhost:8080/"}
ju.datetime_columns(df_shelter,'datetime').info() #now it has 15 columns day month and year
# + id="ri6GhRJFYbqy" outputId="8578dbff-222c-48e3-ac9f-485d9a1ae90c" colab={"base_uri": "https://localhost:8080/"}
print(ju.isit_float("1.1"),
ju.isit_float("1"),
ju.isit_float(".1"),
ju.isit_float('one.one'))
# + id="ktCW1KzhYa74"
#added Dead poet society class to hold poem information
# + id="RO2-QgB_CX2c" outputId="7e3ab5d5-f5e9-4c4f-ee9e-b4c69a81a603" colab={"base_uri": "https://localhost:8080/"}
ju.poem1
# + id="VMX8EsTgCcDO" outputId="c5c5f15e-52e1-4e6e-c8b6-33c6bb712fb7" colab={"base_uri": "https://localhost:8080/"}
ju.poem2
| Unit_3_1_assigment.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
from os import makedirs
from os.path import join, dirname
from collections import defaultdict
import pandas as pd
import numpy as np
from tqdm import tqdm
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from cac.utils.io import save_yml, read_yml
from cac.utils.pandas import apply_filters
# -
random_state = 0
np.random.seed(random_state)
data_root = '/data/flusense/processed/'
annotation = pd.read_csv(join(data_root, 'annotation.csv'))
annotation['segmentation'][0]
annotation['classification'][0]
annotation['segmentation'] = annotation['segmentation'].apply(lambda x: x if isinstance(x, dict) else eval(x))
annotation['classification'] = annotation['classification'].apply(lambda x: x if isinstance(x, list) else eval(x))
annotation.head()
annotation['file'] = annotation['file'].apply(lambda x: join(data_root, 'audio', x) + '.wav')
annotation.head()
indices = np.arange(len(annotation))
train_indices, val_test_indices = train_test_split(indices, test_size=0.2, random_state=random_state)
val_indices, test_indices = train_test_split(val_test_indices, test_size=0.5, random_state=random_state)
len(train_indices), len(val_indices), len(test_indices)
annotation_train = annotation.loc[train_indices].reset_index(drop=True)
annotation_val = annotation.loc[val_indices].reset_index(drop=True)
annotation_test = annotation.loc[test_indices].reset_index(drop=True)
tasks = {
'classification': {
'valid_labels': ['cough']
}
}
def convert_files_into_segments(df):
segmented_files = defaultdict(list)
for row_idx in tqdm(range(len(df)), desc='Iterating over the dataset'):
row = df.loc[row_idx]
file = row['file']
for label in row['segmentation']:
segments = row['segmentation'][label]
for segment in segments:
start, end = segment
if (end - start) <= 1e-2:
continue
segmented_files['file'].append(file)
label = {'classification': ['cough']} if label == 'cough' else {'classification': []}
segmented_files['label'].append(label)
segmented_files['start'].append(start)
segmented_files['end'].append(end)
return pd.DataFrame(segmented_files, columns=['file', 'label', 'start', 'end'])
df_train = convert_files_into_segments(annotation_train)
df_val = convert_files_into_segments(annotation_val)
df_test = convert_files_into_segments(annotation_test)
df_val.label.astype('str').value_counts()
df_train.shape, df_val.shape, df_test.shape
# +
fig, ax = plt.subplots(1, 3, figsize=(20, 7))
modes = ['train', 'val', 'test']
for i, mode in enumerate(modes):
_df = eval('df_{}'.format(mode)).copy()
_df['label'] = _df['label'].apply(lambda x: 'cough' if 'cough' in x['classification'] else 'non-cough')
sns.countplot(x='label', data=_df, ax=ax[i])
counts = _df['label'].value_counts()
ax[i].set_title(mode.upper() + ' [cough: {} non-cough: {}]'.format(counts['cough'], counts['non-cough']))
ax[i].set_ylim(0, 10000)
ax[i].grid()
plt.show()
# -
version = 'segmented-v1.0'
save_path = join(data_root, 'versions', '{}.yml'.format(version))
# +
description = dict()
description['tasks'] = tasks
description['description'] = 'cough vs non-cough classification with split randomly done across files & files segmented within a split'
for name, _df in zip(['all', 'train', 'val', 'test'], [pd.concat([df_train, df_val, df_test]), df_train, df_val, df_test]):
description[name] = {
'file': _df['file'].values.tolist(),
'label': _df['label'].values.tolist(),
'start': _df['start'].values.tolist(),
'end': _df['end'].values.tolist()
}
# -
# save description
makedirs(dirname(save_path), exist_ok=True)
save_yml(description, save_path)
| datasets/versioning/cough-detection/flusense/segmented-v1.0.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Training a YOLOX Model
#
# In this notebook we will run the YOLOX pretrained on some items locally.
# We will then finetune the model on a custom dataset and upload the new snapshot to Dataloop platform
import datetime
import matplotlib as mpl
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import os
import logging
import sys
import dtlpy as dl
from dtlpy.ml import train_utils
# # Get Global Model and Pretrained Snapshot
#
# Get the global model and snapshot from the platform.
# "list()" followed by the "to_df()" method will return pandas DataFrame to view the Dataloop entities and
model = dl.models.get(model_name='YOLOX')
model.snapshots.list().to_df()
snapshot = model.snapshots.get(snapshot_name='coco-pretrained')
snapshot.to_df()
# # Load the Pretrained Snapshot for Inference
#
# Once we have the Dataloop entities, we can load the Model Adapter using the "build()" method.
# This will create an instance of the model class with "train()", "inference()" and more functions we can use
adapter = model.build()
adapter.load_from_snapshot(snapshot=snapshot)
# ## Inference and Upload Annotations to Item
# +
# upload coco item and inference
item = dl.items.get(item_id='611e174e4c09acc3c5bb81d3')
# use the dapter to inference with uploading annotations
annotations = adapter.predict_items([item], with_upload=True)
# -
# View inference results and plot on the item
image = np.asarray(Image.open(item.download()))
plt.imshow(item.annotations.show(image=image,
thickness=5))
# # Run Training on Custom Dataset
#
# We will use the Fruit Images dataset, which is ready to upload with annotation in the Dataloop format.
# First we'll create new project and dataset and upload the images with anntoations
project = dl.projects.create('Fruits Proj')
dataset = project.datasets.create('FruitImage')
items = dataset.items.upload(local_path='../../assets/sample_datasets/FruitImage/items/*',
local_annotations_path='../../assets/sample_datasets/FruitImage/json')
dataset.ontologies.list()[0].add_labels(['apple', 'orange', 'banana'])
dataset.labels
# # Prepare New Dataset for Training
#
# The "prepare_dataset()" method prepares the raw dataset to be a part of a snapshot and ready for training.
# This will:
# 1. Clone the dataset to prepare
# 1. Create train, validation and test splits
# 1. Lock the dataset to be read only
#
# We can set the partition split to be random (using float to set the precentage) or we can use DQL filters to set specific items and folder
# +
# split the dataset to 2 partitions - 80% train 20% validation
partitions = {dl.SnapshotPartitionType.TRAIN: 0.8,
dl.SnapshotPartitionType.VALIDATION: 0.2}
# use DQL to set the two directories and the train/val split
partitions = {dl.SnapshotPartitionType.TRAIN: dl.Filters(field='dir', values='/train'),
dl.SnapshotPartitionType.VALIDATION: dl.Filters(field='dir', values='/test')}
cloned_dataset = train_utils.prepare_dataset(dataset,
filters=None,
partitions=partitions)
# -
# Cloning the pretrained snapshot to create a new snapshot for our custom dataset.
# When cloning we can change any parameter to the new snapshot. here we will change the dataset for our cloned one
snapshot_name='fruit-first'
bucket = project.buckets.create(model_name=model.name,
snapshot_name=snapshot_name)
new_snapshot = snapshot.clone(snapshot_name=snapshot_name,
dataset_id=cloned_dataset.id,
bucket=bucket,
configuration={'batch_size': 2,
'start_epoch': 0,
'max_epoch': 5,
'input_size': (256, 256)})
new_snapshot = model.snapshots.get(snapshot_name=snapshot_name)
# We can easily list the content of the new cloned snapshtop:
new_snapshot.bucket.list_content().to_df()
# We will load the new snapshot to the adapter and preprare the snapshot for training.
# This will:
# 1. download the dataset lcoally
# 1. run the adapter's "convert_from_dtlpy()" if we need to convert the dataloop format to another format
adapter.load_from_snapshot(snapshot=new_snapshot)
root_path, data_path, output_path = adapter.prepare_training()
# ## Start Training
# now we're ready to train
# Start the Train
print("Training {!r} with snapshot {!r} on data {!r}".format(model.name, new_snapshot.id, data_path))
adapter.train(data_path=data_path,
output_path=output_path)
adapter.snapshot.bucket.list_content().to_df()
adapter.save_to_snapshot(local_path=output_path,
replace=True)
adapter.snapshot.bucket.list_content().to_df()
# # Predict New Snapshot in Platform Item
item = dl.items.get(item_id='6110d4a41467ded7a8c2a23d')
adapter.load_from_snapshot(snapshot=new_snapshot)
annotations = adapter.predict_items([item], with_upload=True)
image = Image.open(item.download())
plt.imshow(item.annotations.show(np.asarray(image),
thickness=5))
| model_management/object_detection/yolox_training.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: conda_python3
# language: python
# name: conda_python3
# ---
# +
# Creating EndPoint from Existing Model Artifacts
# You can easily create an endpoint with model artifacts stored in S3.
# NOTE: Change Kernel to Python 3
import numpy as np
import pandas as pd
from sklearn import preprocessing
import os
# Define IAM role
import boto3
import re
from sagemaker import get_execution_role
import sagemaker
# +
# We no longer have to maintain a mapping of container images by region
# Simply use the convenience method provided by sagemaker
# https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html
# NOTE: Update algorithm name
from sagemaker.amazon.amazon_estimator import get_image_uri
image_name = get_image_uri(boto3.Session().region_name, 'xgboost')
# -
# NOTE: Provide the location of your model artifacts stored in S3
# Example shown here:
# Replace path here
s3_model_location = r'https://s3-us-west-2.amazonaws.com/chandra-ml-sagemaker/linear/model/xgboost/xgboost-linear-fn-regression-20180123-14-54/output/model.tar.gz'
role = get_execution_role()
sess = sagemaker.Session()
model = sagemaker.model.Model (model_data = s3_model_location,
image = image_name,
role = role,
sagemaker_session = sess)
# Specify endpoint instance type and count
model.deploy(initial_instance_count = 1,
instance_type = 'ml.m4.xlarge')
print('done')
| Deploy_Model.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import pandas as pd
import numpy as np
pd.set_option('display.max_columns', 100)
# +
df_train_feat = pd.read_csv('training_set_features_cleaned.csv')
df_train_label = pd.read_csv('training_set_labels.csv')
df_test_feat = pd.read_csv('test_set_features_cleaned.csv')
df_train_feat = df_train_feat.drop(columns=['Unnamed: 0', 'respondent_id'], axis=1)
df_test_feat = df_test_feat.drop(columns=['Unnamed: 0', 'respondent_id'], axis=1)
display(df_train_feat.head())
display(df_test_feat.head())
display(df_train_label.head())
# -
df_train_feat.info()
display(df_train_feat.columns)
# +
cat_cols = ['h1n1_concern', 'h1n1_knowledge', 'opinion_h1n1_vacc_effective', 'opinion_h1n1_risk','opinion_h1n1_sick_from_vacc', 'opinion_seas_vacc_effective','opinion_seas_risk', 'opinion_seas_sick_from_vacc']
df_train_feat[cat_cols] = df_train_feat[cat_cols].astype(int)
df_train_feat[cat_cols] = df_train_feat[cat_cols].astype(str)
float_cols = ['behavioral_antiviral_meds', 'behavioral_avoidance','behavioral_face_mask', 'behavioral_wash_hands','behavioral_large_gatherings', 'behavioral_outside_home','behavioral_touch_face', 'doctor_recc_h1n1', 'doctor_recc_seasonal','chronic_med_condition', 'child_under_6_months', 'health_worker', 'health_insurance', 'household_adults','household_children']
df_train_feat[float_cols] = df_train_feat[float_cols].astype(int)
display(df_train_feat.head())
# +
df_train_feat['h1n1_concern'].replace({'0': 'Not at all concerned', '1': 'Not very concerned', '2': ' Somewhat concerned', '3': 'Very concerned'}, inplace=True)
df_train_feat['h1n1_knowledge'].replace({'0': 'No knowledge', '1': 'A little knowledge', '2': 'A lot of knowledge'}, inplace=True)
df_train_feat['opinion_h1n1_vacc_effective'].replace({'1': 'Not at all effective', '2': 'Not very effective', '3': "Don't know", '4': 'Somewhat effective', '5': 'Very effective'}, inplace=True)
df_train_feat['opinion_h1n1_risk'].replace({'1': 'Very Low', '2': 'Somewhat low', '3': "Don't know", '4': 'Somewhat high', '5': 'Very high'}, inplace=True)
df_train_feat['opinion_h1n1_sick_from_vacc'].replace({'1': 'Not at all worried', '2': 'Not very worried', '3': "Don't know", '4': 'Somewhat worried', '5': 'Very worried'}, inplace=True)
df_train_feat['opinion_seas_vacc_effective'].replace({'1': 'Not at all effective', '2': 'Not very effective', '3': "Don't know", '4': 'Somewhat effective', '5': 'Very effective'}, inplace=True)
df_train_feat['opinion_seas_risk'].replace({'1': 'Very Low', '2': 'Somewhat low', '3': "Don't know", '4': 'Somewhat high', '5': 'Very high'}, inplace=True)
df_train_feat['opinion_seas_sick_from_vacc'].replace({'1': 'Not at all worried', '2': 'Not very worried', '3': "Don't know", '4': 'Somewhat worried', '5': 'Very worried'}, inplace=True)
display(df_train_feat)
# -
df_train_feat = pd.get_dummies(df_train_feat, drop_first=True)
df_train_feat.head()
# +
import re
regex = re.compile(r"\[|\]|<", re.IGNORECASE)
# test input data with string, int, and symbol-included columns
df_train_feat.columns = [regex.sub("_", col) if any(x in str(col) for x in set(('[', ']', '<'))) else col for col in df_train_feat.columns.values]
target = df_train_feat.iloc[:, 0]
predictors = df_train_feat.iloc[:, 1:]
# -
# # Model
df_train_feat.columns
# +
X = df_train_feat.drop(columns=['opinion_seas_vacc_effective_Not at all effective',
'opinion_seas_vacc_effective_Not very effective',
'opinion_seas_vacc_effective_Somewhat effective',
'opinion_seas_vacc_effective_Very effective',
'opinion_seas_risk_Somewhat high', 'opinion_seas_risk_Somewhat low',
'opinion_seas_risk_Very Low', 'opinion_seas_risk_Very high',
'opinion_seas_sick_from_vacc_Not at all worried',
'opinion_seas_sick_from_vacc_Not very worried',
'opinion_seas_sick_from_vacc_Somewhat worried',
'opinion_seas_sick_from_vacc_Very worried'], axis=1)
y = df_train_label['h1n1_vaccine']
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 = 42)
# +
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
to_scale = ['household_adults', 'household_children']
X_train[to_scale] = scaler.fit_transform(X_train[to_scale])
X_test[to_scale] = scaler.fit_transform(X_test[to_scale])
# +
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from xgboost import XGBClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
tree= DecisionTreeClassifier(random_state=42)
forest= RandomForestClassifier(random_state=42)
knn= KNeighborsClassifier()
svm= SVC(random_state=42)
xboost= XGBClassifier(objective ='reg:linear', colsample_bytree = 0.3, learning_rate = 0.1, max_depth = 5, alpha = 10, n_estimators = 10)
gnb = GaussianNB()
logreg = LogisticRegression(max_iter=1000)
models= [tree, forest, knn, svm, xboost, gnb, logreg]
for model in models:
model.fit(X_train, y_train) # fit the model
y_pred= model.predict(X_test) # then predict on the test set
accuracy= accuracy_score(y_test, y_pred) # this gives us how often the algorithm predicted correctly
clf_report= classification_report(y_test, y_pred, zero_division=1) # with the report, we have a bigger picture, with precision and recall for each class
print(f"The accuracy of model {type(model).__name__} is {accuracy:.2f}")
print(clf_report)
print("\n")
# +
from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), max_iter=1000, random_state=42)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy= accuracy_score(y_test, y_pred) # this gives us how often the algorithm predicted correctly
clf_report= classification_report(y_test, y_pred, zero_division=1) # with the report, we have a bigger picture, with precision and recall for each class
print(f"The accuracy of model {type(model).__name__} is {accuracy:.2f}")
print(clf_report)
print("\n")
# -
# # MLP
# +
#Change dtypes of columns
cat_cols = ['h1n1_concern', 'h1n1_knowledge', 'opinion_h1n1_vacc_effective', 'opinion_h1n1_risk','opinion_h1n1_sick_from_vacc', 'opinion_seas_vacc_effective','opinion_seas_risk', 'opinion_seas_sick_from_vacc']
df_test_feat[cat_cols] = df_test_feat[cat_cols].astype(int)
df_test_feat[cat_cols] = df_test_feat[cat_cols].astype(str)
float_cols = ['behavioral_antiviral_meds', 'behavioral_avoidance','behavioral_face_mask', 'behavioral_wash_hands','behavioral_large_gatherings', 'behavioral_outside_home','behavioral_touch_face', 'doctor_recc_h1n1', 'doctor_recc_seasonal','chronic_med_condition', 'child_under_6_months', 'health_worker', 'health_insurance', 'household_adults','household_children']
df_test_feat[float_cols] = df_test_feat[float_cols].astype(int)
#Categoricals
df_test_feat['h1n1_concern'].replace({'0': 'Not at all concerned', '1': 'Not very concerned', '2': ' Somewhat concerned', '3': 'Very concerned'}, inplace=True)
df_test_feat['h1n1_knowledge'].replace({'0': 'No knowledge', '1': 'A little knowledge', '2': 'A lot of knowledge'}, inplace=True)
df_test_feat['opinion_h1n1_vacc_effective'].replace({'1': 'Not at all effective', '2': 'Not very effective', '3': "Don't know", '4': 'Somewhat effective', '5': 'Very effective'}, inplace=True)
df_test_feat['opinion_h1n1_risk'].replace({'1': 'Very Low', '2': 'Somewhat low', '3': "Don't know", '4': 'Somewhat high', '5': 'Very high'}, inplace=True)
df_test_feat['opinion_h1n1_sick_from_vacc'].replace({'1': 'Not at all worried', '2': 'Not very worried', '3': "Don't know", '4': 'Somewhat worried', '5': 'Very worried'}, inplace=True)
df_test_feat['opinion_seas_vacc_effective'].replace({'1': 'Not at all effective', '2': 'Not very effective', '3': "Don't know", '4': 'Somewhat effective', '5': 'Very effective'}, inplace=True)
df_test_feat['opinion_seas_risk'].replace({'1': 'Very Low', '2': 'Somewhat low', '3': "Don't know", '4': 'Somewhat high', '5': 'Very high'}, inplace=True)
df_test_feat['opinion_seas_sick_from_vacc'].replace({'1': 'Not at all worried', '2': 'Not very worried', '3': "Don't know", '4': 'Somewhat worried', '5': 'Very worried'}, inplace=True)
df_test_feat = pd.get_dummies(df_test_feat, drop_first=True)
import re
regex = re.compile(r"\[|\]|<", re.IGNORECASE)
# test input data with string, int, and symbol-included columns
df_test_feat.columns = [regex.sub("_", col) if any(x in str(col) for x in set(('[', ']', '<'))) else col for col in df_test_feat.columns.values]
target = df_test_feat.iloc[:, 0]
predictors = df_test_feat.iloc[:, 1:]
df_test_feat.head(5)
# +
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
to_scale = ['household_adults', 'household_children']
df_test_feat[to_scale] = scaler.fit_transform(df_test_feat[to_scale])
# -
# ### H1N1 VACCINE
# +
predict_h1n1 = df_test_feat.drop(columns=['opinion_seas_vacc_effective_Not at all effective',
'opinion_seas_vacc_effective_Not very effective',
'opinion_seas_vacc_effective_Somewhat effective',
'opinion_seas_vacc_effective_Very effective',
'opinion_seas_risk_Somewhat high', 'opinion_seas_risk_Somewhat low',
'opinion_seas_risk_Very Low', 'opinion_seas_risk_Very high',
'opinion_seas_sick_from_vacc_Not at all worried',
'opinion_seas_sick_from_vacc_Not very worried',
'opinion_seas_sick_from_vacc_Somewhat worried',
'opinion_seas_sick_from_vacc_Very worried'], axis=1)
clf.fit(X_train, y_train) # fit the model
y_pred= clf.predict_proba(predict_h1n1) # then predict on the test set
# -
h1n1_vaccine = pd.DataFrame(y_pred)
h1n1_vaccine = h1n1_vaccine.drop([0], axis=1)
h1n1_vaccine = h1n1_vaccine.rename(columns={1:'h1n1_vaccine'})
h1n1_vaccine = pd.DataFrame(h1n1_vaccine['h1n1_vaccine'].round(1))
h1n1_vaccine
# ### SEASONAL VACCINE
df_test_feat.columns
# +
predict_seasonal = df_test_feat.drop(columns=['opinion_seas_vacc_effective_Not at all effective',
'opinion_seas_vacc_effective_Not very effective',
'opinion_seas_vacc_effective_Somewhat effective',
'opinion_seas_vacc_effective_Very effective',
'opinion_seas_risk_Somewhat high', 'opinion_seas_risk_Somewhat low',
'opinion_seas_risk_Very Low', 'opinion_seas_risk_Very high',
'opinion_seas_sick_from_vacc_Not at all worried',
'opinion_seas_sick_from_vacc_Not very worried',
'opinion_seas_sick_from_vacc_Somewhat worried',
'opinion_seas_sick_from_vacc_Very worried'], axis=1)
clf.fit(X_train, y_train) # fit the model
y_pred= clf.predict_proba(predict_seasonal) # then predict on the test set
# -
seasonal_vaccine = pd.DataFrame(y_pred)
seasonal_vaccine = seasonal_vaccine.drop([0], axis=1)
seasonal_vaccine = seasonal_vaccine.rename(columns={1:'seasonal_vaccine'})
seasonal_vaccine = pd.DataFrame(seasonal_vaccine['seasonal_vaccine'].round(1))
seasonal_vaccine
# +
df = pd.read_csv('test_set_features_cleaned.csv')
final = pd.concat([h1n1_vaccine, seasonal_vaccine[['seasonal_vaccine']]], axis = 1)
final = pd.concat([df[['respondent_id']], final], axis=1)
final
# -
final.to_csv('Final_CLF.csv', index=False)
| Multi-layer Perceptron (MLP).ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
import pylab
import matplotlib.pyplot as plt
# +
# Using pandas to import data from Excel
df1 = pd.read_csv('Frequency and Gain.csv', skiprows=1, names=['Frequency','Log_frequency','Vrms1','Vrms2','Gain','Log_gain'])
# -
print(df1)
# +
# Plotting Frequency vs. Gain
plt.style.use(['seaborn-pastel'])
plt.title('Frequency vs. Gain')
plt.ylabel('Gain (G)')
plt.xlabel('Frequency (kHz)')
pylab.xlim(-10, 100)
pylab.ylim(-5,15)
plt.grid()
plt.plot(df1.Frequency, df1.Gain, '-k')
plt.savefig('./freq-gain.svg')
# +
# Plotting Log of Frequency vs. Gain
Log_freq = np.array(df1.Log_frequency)
Log_gain = np.array(df1.Log_gain)
plt.style.use(['seaborn-pastel'])
plt.title('log(Frequency) vs. log(Gain)')
plt.ylabel('log(Gain) (G)')
plt.xlabel('log(Frequency) (kHz)')
pylab.xlim(.5, 2.5)
pylab.ylim(0,2)
plt.grid()
# Polyfit for log(Frequency) vs. log(Gain)
zlog = np.polyfit(Log_freq[49:],Log_gain[49:],1)
p = np.poly1d(zlog)
p30 = np.poly1d(np.polyfit(Log_freq[52:],Log_gain[52:], 30))
xp = np.linspace(.5, 2.5, 100)
plt.plot(df1.Log_frequency, df1.Log_gain, '-k')
plt.plot(xp, p(xp), '-',Log_freq[52:],Log_gain[52:], 'g--')
plt.savefig('./log-freq-gain.svg')
# +
import scipy
from scipy import stats
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(Log_freq[52:],Log_gain[52:])
print(slope)
# Possibly retake data
# Slope of log(Frequency) vs. log(Gain) should be -1 varying +/- 5%
# -
df2 = pd.read_csv('Frequency and Gain New.csv', skiprows=1, names=['Frequency_new','Vrms1_new','Vrms2_new','Gain_new','Log_frequency_new','Log_gain_new'])
print(df2)
# +
# Plotting Frequency New vs. Gain New
plt.style.use(['seaborn-pastel'])
plt.title('Frequency New vs. Gain New')
plt.ylabel('Gain (G)')
plt.xlabel('Frequency (kHz)')
pylab.xlim(-10, 100)
pylab.ylim(-5,15)
plt.grid()
plt.plot(df2.Frequency_new, df2.Gain_new, '-k')
# +
# Plotting Log of new Frequency vs. Gain
Log_freq_new = np.array(df2.Log_frequency_new)
Log_gain_new = np.array(df2.Log_gain_new)
plt.style.use(['seaborn-pastel'])
plt.title('New log(Frequency) vs. log(Gain)')
plt.ylabel('log(Gain) (G)')
plt.xlabel('log(Frequency) (kHz)')
pylab.xlim(0, 5)
pylab.ylim(0,2)
plt.grid()
# Polyfit for new log(Frequency) vs. log(Gain)
zlognew = np.polyfit(Log_freq_new[50:],Log_gain_new[50:],1)
p = np.poly1d(zlognew)
p30 = np.poly1d(np.polyfit(Log_freq_new[50:],Log_gain_new[50:], 30))
xp = np.linspace(.5, 2.5, 100)
plt.plot(df2.Log_frequency_new, df2.Log_gain_new, '-k')
plt.plot(xp, p(xp), '-',Log_freq_new[50:],Log_gain_new[50:], 'g--')
plt.savefig('./log-freq-gain-new.svg')
# +
import scipy
from scipy import stats
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(Log_freq_new[50:],Log_gain_new[50:])
print(slope)
# +
# May need to take more data
# Theory should fit after more conclusive data
# -
| Operational Amplifier.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernel_info:
# name: python3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Note
# * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
# +
# Dependencies and Setup
import pandas as pd
# File to Load (Remember to Change These)
file_to_load = "purchase_data.csv"
# Read Purchasing File and store into Pandas data frame
purchase_data = pd.read_csv(file_to_load)
# Display data
purchase_data.head(10)
# -
# ## Player Count
# * Display the total number of players
# +
# Total count of players
unique_players = purchase_data['SN'].unique()
count_unique_players = len(unique_players)
print("Total Players : " + str(count_unique_players))
# -
# ## Purchasing Analysis (Total)
# * Run basic calculations to obtain number of unique items, average price, etc.
#
#
# * Create a summary data frame to hold the results
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display the summary data frame
#
# +
# count of unique Items
unique_itemID = purchase_data["Item ID"].unique()
count_unique_items = len(unique_itemID)
print('Number of Unique Items: ' + str(count_unique_items))
# Calculate average purchase price
average_price = round(purchase_data['Price'].mean(),2)
print('The Average Purchase Price: $' + str(average_price))
# total number of purchases
count_of_purchases = purchase_data["Purchase ID"].count()
print('Total number of purchases: ' + str(count_of_purchases))
# Total Revenue of all purchases
sum_of_purchases = purchase_data['Price'].sum()
print('Total Revenue: $'+str(sum_of_purchases))
# Summary Table of the Purchasing Analysis
summary_table1 = pd.DataFrame(
{"Number of Unique Items":[count_unique_items],
"Average Purchase Price": ['$'+str(average_price)],
"Total Number of Purchases":[count_of_purchases],
"Total Revenue": ['$'+str(sum_of_purchases)]
}
)
summary_table1
# -
# ## Gender Demographics
# * Percentage and Count of Male Players
#
#
# * Percentage and Count of Female Players
#
#
# * Percentage and Count of Other / Non-Disclosed
#
#
#
# +
# counts of all genders
gender_counts = purchase_data.groupby('Gender').nunique()['SN']
gender_counts
# -
# percentages of all genders
gender_percentages = round((gender_counts/count_unique_players*100),2)
gender_percentages
# +
# Summary Table of Gender Demographics
# Clearner format( added percentage sign)
summary_table2 = pd.DataFrame(
{'Total Count': gender_counts,
'Percentage of Players':gender_percentages
}
)
clean_formated2 = summary_table2.style.format({'Percentage of Players': '{:.2f}%'})
clean_formated2
# -
#
# ## Purchasing Analysis (Gender)
# * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender
#
#
#
#
# * Create a summary data frame to hold the results
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display the summary data frame
# +
# Purchase Count by Gender
gender_purchase_count = purchase_data.groupby("Gender").count()['Purchase ID']
gender_purchase_count
# -
# Average Purchase Price by Gender
avg_pp_gender = round(purchase_data.groupby('Gender').mean()['Price'],2)
avg_pp_gender
# Total Purchase value by Gender
sum_purchase = purchase_data.groupby('Gender').sum()['Price']
sum_purchase
# Average Total Purchase per person by Gender
avg_total_pp = round((sum_purchase/gender_counts),2)
avg_total_pp
# +
# Summary Table of Purchasing Analysis by Gender
# Cleaner formatted ( added $ sign on columns 'Avg Purchase Price, Total Purchase Value and AVG total Purchase per Person')
summary_table3 = pd.DataFrame(
{'Purchase Count': gender_purchase_count,
'Average Purchase Price':avg_pp_gender,
'Total Purchase Value': sum_purchase,
'Avg Total Purchase Per Person':avg_total_pp
}
)
clean_formated3 = summary_table3.style.format({'Average Purchase Price':'${:.2f}', 'Total Purchase Value':'${:.2f}',
'Avg Total Purchase Per Person':'${:.2f}'})
clean_formated3
# -
# ## Age Demographics
# * Establish bins for ages
#
#
# * Categorize the existing players using the age bins. Hint: use pd.cut()
#
#
# * Calculate the numbers and percentages by age group
#
#
# * Create a summary data frame to hold the results
#
#
# * Optional: round the percentage column to two decimal points
#
#
# * Display Age Demographics Table
#
# +
# Bins for age demographics
# Group age groups
bins = [0,9,14,19,24,29,34,39,100]
age_labels = ['>10','10-14','15-19','20-24','25-29','30-34','35-39','40+']
purchase_data['Age Groups'] = pd.cut(purchase_data["Age"], bins, labels = age_labels)
# +
# Group by age group
# count age groups
# display age groups
age_groups = purchase_data.groupby('Age Groups')
count_age_group = age_groups['SN'].nunique()
count_age_group
# +
# percentage of age groups
# round percentage to 2 decimal points
percentage_age_groups = round((count_age_group/count_unique_players) * 100,2)
percentage_age_groups
# +
# Summary table of age demographics
# cleaner format ( adding percentage sign to Percentage of Players column)
summary_table4 = pd.DataFrame(
{'Total Count': count_age_group,
'Percentage of Players': percentage_age_groups
}
)
clean_formated4 = summary_table4.style.format({'Percentage of Players':'{:.2f}%'})
clean_formated4
# -
# ## Purchasing Analysis (Age)
# * Bin the purchase_data data frame by age
#
#
# * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below
#
#
# * Create a summary data frame to hold the results
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display the summary data frame
# +
# Use same bins and labels as Age demographics
# Use same grouped 'aged groups'
# calculage Purchase count
count_age_purchases = age_groups['Purchase ID'].count()
count_age_purchases
# +
# Calculate Average Purchase Price
avg_age_group_pp = round((age_groups['Price'].mean()),2)
avg_age_group_pp
# +
# Calculate Total Purchase Value
total_age_group_pv = age_groups['Price'].sum()
total_age_group_pv
# -
# Avg Total Purchase Per Person
avg_tp_pp = round((total_age_group_pv/count_age_group),2)
avg_tp_pp
# +
# Summary Table of purchasing analysis (age)
# cleaner formating (add $ sign to columns that represent currency)
summary_table5 = pd.DataFrame(
{'Purchase Count': count_age_purchases,
'Average Purchase Price': avg_age_group_pp,
'Total Purchase Value': total_age_group_pv,
'Avg Total Purchase Per Person': avg_tp_pp
}
)
clean_formated5 = summary_table5.style.format({'Average Purchase Price':'${:.2f}', 'Total Purchase Value':'${:.2f}',
'Avg Total Purchase Per Person':'${:.2f}'})
clean_formated5
# -
# ## Top Spenders
# * Run basic calculations to obtain the results in the table below
#
#
# * Create a summary data frame to hold the results
#
#
# * Sort the total purchase value column in descending order
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display a preview of the summary data frame
#
#
# +
# Top Spender
# Group by unique SN
# Count of purchases by SN
sn_grouped = purchase_data.groupby('SN')
count_sn_grouped = sn_grouped['Purchase ID'].count()
count_sn_grouped.head(10)
# -
# Average Purchase Price by SN
avg_pp_spender = round((sn_grouped['Price'].mean()),2)
avg_pp_spender.head(10)
# Total Purchase Value
total_pv_spender = sn_grouped['Price'].sum()
total_pv_spender.head(10)
# +
# Summary Table
# Total Purchase Value in Descending order
# cleaner formatting (place $ on columns that have currency values)
summary_table6 = pd.DataFrame(
{'Purchase Count': count_sn_grouped,
'Average Purchase Price': avg_pp_spender,
'Total Purchase Value': total_pv_spender
}
)
sort_tpv = summary_table6.sort_values(['Total Purchase Value'], ascending = False).head()
clean_formated6 = sort_tpv.style.format({'Average Purchase Price':'${:.2f}', 'Total Purchase Value':'${:.2f}'})
clean_formated6
# -
# ## Most Popular Items
# * Retrieve the Item ID, Item Name, and Item Price columns
#
#
# * Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value
#
#
# * Create a summary data frame to hold the results
#
#
# * Sort the purchase count column in descending order
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display a preview of the summary data frame
#
#
# +
# Most Popular Items
# Group by Item ID
# Count of purchases by Item ID
item_grouped = purchase_data.groupby(['Item ID','Item Name'])
#hold price of item value
Item_price = purchase_data['Price']
count_item_grouped = item_grouped['Purchase ID'].count()
count_item_grouped.head(10)
# -
# Total Purchase Value by Item
total_pv_item = item_grouped['Price'].sum()
total_pv_item.head(10)
# +
# Summary table
# sort Purchase count in descending order
# cleaner formating(add $ to currency columns)
summary_table7 = pd.DataFrame(
{'Purchase Count': count_item_grouped,
'Item Price': (total_pv_item/count_item_grouped),
'Total Purchase Value': total_pv_item
}
)
sorted_mpt = summary_table7.sort_values(['Purchase Count'], ascending = False).head()
clean_formated7 = sorted_mpt.style.format({'Item Price':'${:.2f}', 'Total Purchase Value':'${:.2f}'})
clean_formated7
# -
# ## Most Profitable Items
# * Sort the above table by total purchase value in descending order
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display a preview of the data frame
#
#
# +
# sort previous table by Total Purchase Value instead
# cleaner format(add $ sign to currency columns)
sorted_mpi = summary_table7.sort_values(['Total Purchase Value'], ascending = False).head()
clean_formated8 = sorted_mpi.style.format({'Item Price':'${:.2f}', 'Total Purchase Value':'${:.2f}'})
clean_formated8
# -
| HeroesOfPymoli/HeroesOfPymoli_starter.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# -
# # Render a colored point cloud
#
# This tutorial shows how to:
# - set up a renderer
# - render the point cloud
# - vary the rendering settings such as compositing and camera position
# ## Import modules
# Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:
import os
import sys
import torch
need_pytorch3d=False
try:
import pytorch3d
except ModuleNotFoundError:
need_pytorch3d=True
if need_pytorch3d:
if torch.__version__.startswith("1.7") and sys.platform.startswith("linux"):
# We try to install PyTorch3D via a released wheel.
version_str="".join([
f"py3{sys.version_info.minor}_cu",
torch.version.cuda.replace(".",""),
f"_pyt{torch.__version__[0:5:2]}"
])
# !pip install pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html
else:
# We try to install PyTorch3D from source.
# !curl -LO https://github.com/NVIDIA/cub/archive/1.10.0.tar.gz
# !tar xzf 1.10.0.tar.gz
os.environ["CUB_HOME"] = os.getcwd() + "/cub-1.10.0"
# !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'
# +
import os
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
from skimage.io import imread
# Util function for loading point clouds|
import numpy as np
# Data structures and functions for rendering
from pytorch3d.structures import Pointclouds
from pytorch3d.vis.plotly_vis import AxisArgs, plot_batch_individually, plot_scene
from pytorch3d.renderer import (
look_at_view_transform,
FoVOrthographicCameras,
PointsRasterizationSettings,
PointsRenderer,
PulsarPointsRenderer,
PointsRasterizer,
AlphaCompositor,
NormWeightedCompositor
)
# -
# ### Load a point cloud and corresponding colors
#
# Load and create a **Point Cloud** object.
#
# **Pointclouds** is a unique datastructure provided in PyTorch3D for working with batches of point clouds of different sizes.
# If running this notebook using **Google Colab**, run the following cell to fetch the pointcloud data and save it at the path `data/PittsburghBridge`:
# If running locally, the data is already available at the correct path.
# !mkdir -p data/PittsburghBridge
# !wget -P data/PittsburghBridge https://dl.fbaipublicfiles.com/pytorch3d/data/PittsburghBridge/pointcloud.npz
# +
# Setup
if torch.cuda.is_available():
device = torch.device("cuda:0")
torch.cuda.set_device(device)
else:
device = torch.device("cpu")
# Set paths
DATA_DIR = "./data"
obj_filename = os.path.join(DATA_DIR, "PittsburghBridge/pointcloud.npz")
# Load point cloud
pointcloud = np.load(obj_filename)
verts = torch.Tensor(pointcloud['verts']).to(device)
rgb = torch.Tensor(pointcloud['rgb']).to(device)
point_cloud = Pointclouds(points=[verts], features=[rgb])
# -
# ## Create a renderer
#
# A renderer in PyTorch3D is composed of a **rasterizer** and a **shader** which each have a number of subcomponents such as a **camera** (orthographic/perspective). Here we initialize some of these components and use default values for the rest.
#
# In this example we will first create a **renderer** which uses an **orthographic camera**, and applies **alpha compositing**. Then we learn how to vary different components using the modular API.
#
# [1] <a href="https://arxiv.org/abs/1912.08804">SynSin: End to end View Synthesis from a Single Image.</a> <NAME>, <NAME>, <NAME>, <NAME>. CVPR 2020.
# +
# Initialize a camera.
R, T = look_at_view_transform(20, 10, 0)
cameras = FoVOrthographicCameras(device=device, R=R, T=T, znear=0.01)
# Define the settings for rasterization and shading. Here we set the output image to be of size
# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1
# and blur_radius=0.0. Refer to raster_points.py for explanations of these parameters.
raster_settings = PointsRasterizationSettings(
image_size=512,
radius = 0.003,
points_per_pixel = 10
)
# Create a points renderer by compositing points using an alpha compositor (nearer points
# are weighted more heavily). See [1] for an explanation.
rasterizer = PointsRasterizer(cameras=cameras, raster_settings=raster_settings)
renderer = PointsRenderer(
rasterizer=rasterizer,
compositor=AlphaCompositor()
)
# -
images = renderer(point_cloud)
plt.figure(figsize=(10, 10))
plt.imshow(images[0, ..., :3].cpu().numpy())
plt.grid("off")
plt.axis("off");
# We will now modify the **renderer** to use **alpha compositing** with a set background color.
# +
renderer = PointsRenderer(
rasterizer=rasterizer,
# Pass in background_color to the alpha compositor, setting the background color
# to the 3 item tuple, representing rgb on a scale of 0 -> 1, in this case blue
compositor=AlphaCompositor(background_color=(0, 0, 1))
)
images = renderer(point_cloud)
plt.figure(figsize=(10, 10))
plt.imshow(images[0, ..., :3].cpu().numpy())
plt.grid("off")
plt.axis("off");
# -
# In this example we will first create a **renderer** which uses an **orthographic camera**, and applies **weighted compositing**.
# +
# Initialize a camera.
R, T = look_at_view_transform(20, 10, 0)
cameras = FoVOrthographicCameras(device=device, R=R, T=T, znear=0.01)
# Define the settings for rasterization and shading. Here we set the output image to be of size
# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1
# and blur_radius=0.0. Refer to rasterize_points.py for explanations of these parameters.
raster_settings = PointsRasterizationSettings(
image_size=512,
radius = 0.003,
points_per_pixel = 10
)
# Create a points renderer by compositing points using an weighted compositor (3D points are
# weighted according to their distance to a pixel and accumulated using a weighted sum)
renderer = PointsRenderer(
rasterizer=PointsRasterizer(cameras=cameras, raster_settings=raster_settings),
compositor=NormWeightedCompositor()
)
# -
images = renderer(point_cloud)
plt.figure(figsize=(10, 10))
plt.imshow(images[0, ..., :3].cpu().numpy())
plt.grid("off")
plt.axis("off");
# We will now modify the **renderer** to use **weighted compositing** with a set background color.
renderer = PointsRenderer(
rasterizer=PointsRasterizer(cameras=cameras, raster_settings=raster_settings),
# Pass in background_color to the norm weighted compositor, setting the background color
# to the 3 item tuple, representing rgb on a scale of 0 -> 1, in this case red
compositor=NormWeightedCompositor(background_color=(1,0,0))
)
images = renderer(point_cloud)
plt.figure(figsize=(10, 10))
plt.imshow(images[0, ..., :3].cpu().numpy())
plt.grid("off")
plt.axis("off");
# ## Using the pulsar backend
#
# Switching to the pulsar backend is easy! The pulsar backend has a compositor built-in, so the `compositor` argument is not required when creating it (a warning will be displayed if you provide it nevertheless). It pre-allocates memory on the rendering device, that's why it needs the `n_channels` at construction time.
#
# All parameters for the renderer forward function are batch-wise except the background color (in this example, `gamma`) and you have to provide as many values as you have examples in your batch. The background color is optional and by default set to all zeros. You can find a detailed explanation of how gamma influences the rendering function here in the paper [Fast Differentiable Raycasting for Neural Rendering using
# Sphere-based Representations](https://arxiv.org/pdf/2004.07484.pdf).
#
# You can also use the `native` backend for the pulsar backend which already provides access to point opacity. The native backend can be imported from `pytorch3d.renderer.points.pulsar`; you can find examples for this in the folder `docs/examples`.
# +
renderer = PulsarPointsRenderer(
rasterizer=PointsRasterizer(cameras=cameras, raster_settings=raster_settings),
n_channels=4
).to(device)
images = renderer(point_cloud, gamma=(1e-4,),
bg_col=torch.tensor([0.0, 1.0, 0.0, 1.0], dtype=torch.float32, device=device))
plt.figure(figsize=(10, 10))
plt.imshow(images[0, ..., :3].cpu().numpy())
plt.grid("off")
plt.axis("off");
# -
# ### View pointclouds in Plotly figures
#
# Here we use the PyTorch3D function `plot_scene` to render the pointcloud in a Plotly figure. `plot_scene` returns a plotly figure with trace and subplots defined by the input.
plot_scene({
"Pointcloud": {
"person": point_cloud
}
})
# We will now render a batch of pointclouds. The first pointcloud is the same as above, and the second is all-black and offset by 2 in all dimensions so we can see them on the same plot.
point_cloud_batch = Pointclouds(points=[verts, verts + 2], features=[rgb, torch.zeros_like(rgb)])
# render both in the same plot in different traces
fig = plot_scene({
"Pointcloud": {
"person": point_cloud_batch[0],
"person2": point_cloud_batch[1]
}
})
fig.show()
# render both in the same plot in one trace
fig = plot_scene({
"Pointcloud": {
"2 people": point_cloud_batch
}
})
fig.show()
# For batches, we can also use `plot_batch_individually` to avoid constructing the scene dictionary ourselves.
# render both in 1 row in different subplots
fig2 = plot_batch_individually(point_cloud_batch, ncols=2)
fig2.show()
# modify the plotly figure height and width
fig2.update_layout(height=500, width=500)
fig2.show()
# We can also modify the axis arguments and axis backgrounds for either function, and title our plots in `plot_batch_individually`.
fig3 = plot_batch_individually(
point_cloud_batch,
xaxis={"backgroundcolor":"rgb(200, 200, 230)"},
yaxis={"backgroundcolor":"rgb(230, 200, 200)"},
zaxis={"backgroundcolor":"rgb(200, 230, 200)"},
subplot_titles=["Pointcloud1", "Pointcloud2"], # this should have a title for each subplot, titles can be ""
axis_args=AxisArgs(showgrid=True))
fig3.show()
| docs/tutorials/render_colored_points.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="6bYaCABobL5q"
# ##### Copyright 2021 The TensorFlow Authors.
# + cellView="form" id="FlUw7tSKbtg4"
#@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.
# + [markdown] id="61dp4Hg5ksTC"
# # Reuse pre-existing TF1.x checkpoints
#
# + [markdown] id="MfBg1C5NB3X0"
# <table class="tfo-notebook-buttons" align="left">
# <td>
# <a target="_blank" href="https://www.tensorflow.org/guide/migrate/reuse_checkpoints"><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/migrate/reuse_checkpoints.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/migrate/reuse_checkpoints.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View on GitHub</a>
# </td>
# <td>
# <a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/migrate/reuse_checkpoints.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
# </td>
# </table>
# + [markdown] id="avuMwzscPnHh"
# As seen in the above testing, `get_variable` calls in decorators for `tf.Module` and `tf.keras.layers.Layer` methods end up maintaining the variable naming semantics of `get_variable` in TF1.x graphs and sessions.
#
# Because [`tf.train.Checkpoint`](https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint) supports loading legacy `tf.compat.v1.train.Saver`-generated name-based checkpoints and your variable names are likely to match, you can use your pre-existing TF1.x name-based checkpoints often entirely out of the box.
# + [markdown] id="TaYgaekzOAHf"
# ## Setup
# + [markdown] id="9kv9SmyVjGLA"
# ## Loading checkpoints with no assignment mapping
#
# If your TF1.x program loaded checkpoints directly with no assignment mapping to map from saved to loaded variable names (such as when warm-starting), and your variable names from `tf.keras.layers.Layer` successfully matched the variable names exactly in the above tests, then you can just load your existing checkpoint directly with `tf.train.Checkpoint`.
#
# The `tf.train.Checkpoint` [guide](https://www.tensorflow.org/guide/checkpoint) describes APIs which you can use to validate that any and all variables you expect to have been loaded are actually loaded. Remember that `get_variable` weights will only get created when your model's forward pass runs.
#
# After loading the checkpoint and running it, consider saving out a new `tf.train.Checkpoint` that uses the TF2 object-oriented style and reusing that one. You should save out the TF2 object-oriented style checkpoint once your variables have been created.
# + [markdown] id="NkUQJUUyjOJz"
# ## Loading checkpoints with a simple nested variable_scope assignment map
#
# TF1.x code that used checkpoints for warm-starting just the backbone of a model often relies on an *assignment map*, such as the `assignment_map` argument of `tf.compat.v1.train.init_from_checkpoint`.
#
# If the assignment map rule is a simple one like `{"/": "backbone_name/"}` (which tries to map any variable named "FOO" in your checkpoint to the corresponding variable named "backbone_name/FOO" in your model), then it may be possible to either add or remove a `variable_scope` in your `track_tf1_style_variable`-decorated call method to make sure the variable names exactly match the names in your checkpoint with no need for an assignment map.
#
# Note: As described in past sections you still need to nest `tf.compat.v1.layers` that rely on autogenerated names inside at least one `variable_scope` to ensure variables get re-used correctly.
#
# You can then load your existing checkpoint as is with `tf.train.Checkpoint`, and save out a new object-oriented checkpoint right away.
# + [markdown] id="J7NPybZVi_Ew"
# ## Loading checkpoints with a more complicated assignment mapping
#
# If adjusting the `variable_scope` nesting in your shim-decorated call method proves insufficient, or you have a more complicated name and scope assignment mapping, you may need to directly rename the variables in your saved TF1.x name-based checkpoint to the expected variable names post-mapping. There are several approaches to do this like using a dictionary mapping that contains all variable names, using regular expressions to rewrite any scopes, etc. The following code snippets demonstrate a few of these methods.
# + [markdown] id="RLpGN0kFy4OZ"
# This first code snippet shows how you can programmatically grab the names from an existing name-based checkpoint.
# ```
# CKPT = "/PATH/TO/ORIGINAL/CHECKPOINT"
# with tf.Graph().as_default():
# checkpoint_reader = tf.train.NewCheckpointReader(CKPT)
# names_to_shapes = checkpoint_reader.get_variable_to_shape_map()
# var_names = sorted(list(names_to_shapes))
# for name in var_names:
# print(name)
# ```
# + [markdown] id="5qrjLapzsJ1K"
# This second code snippet shows how you can rename variables in one TF1.x name-based checkpoint and save out a new name-based checkpoint (if you have a dict `new_name_from_old_name` mapping old variable names to post-assignment-mapping variable names).
# ```
# to_migrate = [
# ("/PATH/TO/ORIGINAL/CHECKPOINT",
# "/PATH/TO/CHECKPOINT/WITH/RENAMED/VARIABLES"),
# ]
# for input_ckpt, output_ckpt in to_migrate:
# print(f'Migrating {input_ckpt} to {output_ckpt}')
# with tf.Graph().as_default():
# checkpoint_reader = tf.train.NewCheckpointReader(input_ckpt)
# variable_from_new_name = {}
#
# for old_name, new_name in new_name_from_old_name.items():
# value = checkpoint_reader.get_tensor(old_name)
# variable_from_new_name[new_name] = tf.Variable(value)
#
# init = tf.global_variables_initializer()
# saver = tf.train.Saver(variable_from_new_name)
#
# with tf.Session() as sess:
# sess.run(init)
# saver.save(sess, output_ckpt, write_meta_graph=False)
#
# for old_name, new_name in new_name_from_old_name.items():
# print(f'{old_name} -> {new_name}')
# ```
# + [markdown] id="ejem9qLuoWp_"
# Once you have remapped the names in your variable name checkpoint according to the assignment map, you should then be able to load it and afterwards save out a new object-oriented checkpoint.
# + [markdown] id="ZDYSFob4jazB"
# ## Loading checkpoints when not all variables are created by `get_variable`
#
# If your shim-decorated layer or module consists of some variables (or Keras layers/models) that use `tf.Variable` instead of `tf.compat.v1.get_variable` and get attached as properties/tracked in an object oriented way, they may have different variable naming semantics in TF1.x graphs/sessions versus during eager exection.
#
# So, you will have to compare these variable names before and after and explicitly rewrite the checkpoint with renamed variables, just as for more complex assignment mapping above.
#
# Once you do that you can load the checkpoint, and save out a new object-oriented checkpoint for future use.
#
# Warning: Variables may have duplicate names in eager execution, which may cause problems if multiple variables in the name-based checkpoint need to be mapped to the same name. You may be able to explicitly adjust the layer and variable names using `tf.name_scope` and layer constructor or `tf.Variable` `name` arguments to adjust variable names and ensure there are no duplicates.
# + [markdown] id="JBMfArLQ0jb-"
# ## Resources
#
# Refer to the following guides:
# * Validating numerical equivalence and correctness
# * TF Modeling Shims
| site/en/guide/migrate/reuse_checkpoints.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
from flask import Flask
import matplotlib.pyplot as plt
from flask import Flask, request, render_template
import pandas
import os
import sys
from flask import Flask, request, session, g, redirect, url_for, abort, render_template
from flaskext.mysql import MySQL
from flask_wtf import FlaskForm
from wtforms.fields.html5 import DateField
from wtforms import SelectField,StringField, BooleanField, SubmitField
from wtforms.validators import DataRequired
from datetime import date
import time
import gmplot
from wtforms import Form
from flask_wtf import Form
from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField,SelectField
import seaborn as sns
from wtforms import validators, ValidationError
app = Flask(__name__)
app.secret_key = 'A0Zr98slkjdf984jnflskj_sdkfjhT'
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '<PASSWORD>'
app.config['MYSQL_DATABASE_DB'] = 'CREDIT'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()
class AnalyticsForm(FlaskForm):
attributes = SelectField('Data Attributes', choices=[('SEX', 'SEX'), ('MARRIAGE', 'MARRIAGE'), ('EDUCATION', 'EDUCATION')])
class InfoForm(FlaskForm):
sex = StringField('Gender') #, validators=[DataRequired()])
#submit = SubmitField('Sign In')
class PaymentForm(FlaskForm):
attributes = SelectField('Data Attributes', choices=[('BILL_AMT1', 'BILL_AMT1'),
('BILL_AMT2', 'BILL_AMT2'), ('BILL_AMT3', 'BILL_AMT3'),
('BILL_AMT4', 'BILL_AMT4'), ('BILL_AMT5', 'BILL_AMT5'),
('BILL_AMT6', 'BILL_AMT6')])
class ContactForm(Form):
Age = TextField("Age",[validators.Required("Please enter the age.")])
Gender = RadioField('Gender', choices = [('M','Male'),('F','Female')])
Education = SelectField('Education', choices = [('1','Graduate'),('2','university'),('3','high school'), ('4','others'), ('5','unknown')])
#Address = TextAreaField("Education")
PAY_0 = SelectField("PAY_0",choices = [('-1','pay duly'), ('1','payment delay for one month'), ('2','payment delay for two months'),('3','payment delay for three month'), ('4','payment delay for four months'),('5','payment delay for five month'), ('6','payment delay for six months'),('7','payment delay for one month'), ('8','payment delay for eight months'),('9','payment delay for nine months and above')])
PAY_2 = SelectField("PAY_2",choices = [('-1','pay duly'), ('1','payment delay for one month'), ('2','payment delay for two months'),('3','payment delay for three month'), ('4','payment delay for four months'),('5','payment delay for five month'), ('6','payment delay for six months'),('7','payment delay for one month'), ('8','payment delay for eight months'),('9','payment delay for nine months and above')])
PAY_3 = SelectField("PAY_3",choices = [('-1','pay duly'), ('1','payment delay for one month'), ('2','payment delay for two months'),('3','payment delay for three month'), ('4','payment delay for four months'),('5','payment delay for five month'), ('6','payment delay for six months'),('7','payment delay for one month'), ('8','payment delay for eight months'),('9','payment delay for nine months and above')])
PAY_4 = SelectField("PAY_4",choices = [('-1','pay duly'), ('1','payment delay for one month'), ('2','payment delay for two months'),('3','payment delay for three month'), ('4','payment delay for four months'),('5','payment delay for five month'), ('6','payment delay for six months'),('7','payment delay for one month'), ('8','payment delay for eight months'),('9','payment delay for nine months and above')])
PAY_5 = SelectField("PAY_5",choices = [('-1','pay duly'), ('1','payment delay for one month'), ('2','payment delay for two months'),('3','payment delay for three month'), ('4','payment delay for four months'),('5','payment delay for five month'), ('6','payment delay for six months'),('7','payment delay for one month'), ('8','payment delay for eight months'),('9','payment delay for nine months and above')])
PAY_6 = SelectField("PAY_6",choices = [('-1','pay duly'), ('1','payment delay for one month'), ('2','payment delay for two months'),('3','payment delay for three month'), ('4','payment delay for four months'),('5','payment delay for five month'), ('6','payment delay for six months'),('7','payment delay for one month'), ('8','payment delay for eight months'),('9','payment delay for nine months and above')])
BILL_AMT1 = TextField("Amount of bill statement in September")
BILL_AMT2 = TextField("Amount of bill statement in August")
BILL_AMT3 = TextField("Amount of bill statement in July")
BILL_AMT4 = TextField("Amount of bill statement in June")
BILL_AMT5 = TextField("Amount of bill statement in May")
BILL_AMT6 = TextField("Amount of bill statement in April")
PAY_AMT1 = TextField("Amount of previous payment in September")
PAY_AMT2 = TextField("Amount of previous payment in August")
PAY_AMT3 = TextField("Amount of previous payment in July")
PAY_AMT4 = TextField("Amount of previous payment in June")
PAY_AMT5 = TextField("Amount of previous payment in May")
PAY_AMT6 = TextField("Amount of previous payment in April")
MARRIAGE = RadioField("MARRIAGE", choices = [('1','married'), ('2','single'), ('3','others')])
language = SelectField('Languages', choices = [('cpp', 'C++'), ('py', 'Python')])
submit = SubmitField("Send")
class MarriageForm(FlaskForm):
attributes = SelectField('Data Attributes', choices=[('BILL_AMT1', 'BILL_AMT1'),
('BILL_AMT2', 'BILL_AMT2'), ('BILL_AMT3', 'BILL_AMT3'),
('BILL_AMT4', 'BILL_AMT4'), ('BILL_AMT5', 'BILL_AMT5'),
('BILL_AMT6', 'BILL_AMT6')])
def get_homepage_links1():
return [{"href": url_for('analytics'), "label":"plot"},{"href": url_for('data'), "label":"data"}]
def get_homepage_links2():
return [{"href": url_for('predict'), "label":"predict"}]
def get_df_data():
query = "select ID, MARRIAGE, SEX, EDUCATION,default_payment from credit_card;"
cursor.execute(query)
data = cursor.fetchall()
df = pandas.DataFrame(data=list(data),columns=['ID', 'MARRIAGE', 'SEX', 'EDUCATION','default_payment'])
return df
@app.route("/")
def home():
#session["data_loaded"] = True
return render_template('new_layout.html', link1=get_homepage_links1(), link2=get_homepage_links2())
@app.route("/data")
def data():
return render_template('data1.html')
@app.route("/data2",methods = ['POST', 'GET'])
def data2():
if request.method == 'POST':
result = request.form
AGE = result['AGE']
SEX = result['SEX']
EDUCATION = result['EDUCATION']
MARRIAGE = result['MARRIAGE']
query = f"select ID, AGE, SEX, EDUCATION,MARRIAGE,default_payment from credit_card where AGE ={AGE} "
if SEX:
query += f"and SEX = {SEX} "
if EDUCATION:
query += f"and EDUCATION = {EDUCATION} "
if MARRIAGE:
query += f"and MARRIAGE = {MARRIAGE} "
cursor.execute(query)
data = cursor.fetchall()
data=list(data)
return render_template("data.html",df = data)
@app.route("/predcit")
def predict():
return render_template('predict1.html')
@app.route("/predict2",methods = ['POST', 'GET'])
def predict2():
if request.method == 'POST':
result = request.form
LIMIT_BAL = result['LIMIT_BAL']
AGE = result['AGE']
SEX = result['SEX']
EDUCATION = result['EDUCATION']
MARRIAGE = result['MARRIAGE']
PAY_0 = result['PAY_0']
PAY_2 = result['PAY_2']
PAY_3 = result['PAY_3']
PAY_4 = result['PAY_4']
PAY_5 = result['PAY_5']
PAY_6 = result['PAY_6']
CREDIT_AMT1=result['CREDIT_AMT1']
CREDIT_AMT2=result['CREDIT_AMT2']
CREDIT_AMT3=result['CREDIT_AMT3']
CREDIT_AMT4=result['CREDIT_AMT4']
CREDIT_AMT5=result['CREDIT_AMT5']
CREDIT_AMT6=result['CREDIT_AMT6']
info = [LIMIT_BAL,AGE,SEX,EDUCATION,MARRIAGE,PAY_0,PAY_2,PAY_3,PAY_4,PAY_5,PAY_6,CREDIT_AMT1,CREDIT_AMT2,CREDIT_AMT3,CREDIT_AMT4,CREDIT_AMT5,CREDIT_AMT6]
a = list(visulization(info).values())
df = [['Method1',a[0]],['Method2',a[1]],['Method3',a[2]],['Method4',a[3]],['Method5',a[4]],['Method6',a[5]],['Method6',a[6]]]
return render_template("predict.html",df = df)
# +
def get_age_range(age):
j = 20
for i in range(6):
if int(age) < j+10:
break
j = j + 10
return j
def get_payment_data():
query = "select AGE, MARRIAGE, BILL_AMT1, BILL_AMT2, BILL_AMT3, BILL_AMT4, BILL_AMT5, BILL_AMT6 from credit_card;"
cursor.execute(query)
data = cursor.fetchall()
payment_data = pandas.DataFrame(data=list(data),columns=['AGE', 'MARRIAGE', 'BILL_AMT1', 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6'])
payment_data['BILL_AMT1'] = payment_data['BILL_AMT1'].apply(lambda x: float(x))
payment_data['BILL_AMT2'] = payment_data['BILL_AMT2'].apply(lambda x: float(x))
payment_data['BILL_AMT3'] = payment_data['BILL_AMT3'].apply(lambda x: float(x))
payment_data['BILL_AMT4'] = payment_data['BILL_AMT4'].apply(lambda x: float(x))
payment_data['BILL_AMT5'] = payment_data['BILL_AMT5'].apply(lambda x: float(x))
payment_data['BILL_AMT6'] = payment_data['BILL_AMT6'].apply(lambda x: float(x))
payment_data['age_range'] = payment_data['AGE'].apply(lambda x:get_age_range(x))
return payment_data
# -
@app.route('/analytics',methods=['GET','POST'])
def analytics():
form1= AnalyticsForm()
if form1.validate_on_submit():
df = get_df_data()
column = request.form.get('attributes')
group = df.groupby([column,'default_payment'])
ax = group.size().unstack().plot(kind='bar')
fig = ax.get_figure()
filename = f'static/charts/{column}.png'
fig.savefig(filename)
return render_template('analytics.html', chart_src="/"+filename)
form2 = PaymentForm()
if form2.validate_on_submit():
payment_df = get_payment_data()
column = request.form.get('attributes')
df1 = payment_df[['age_range', column]]
sns.set_style('ticks')
sns_plot = sns.violinplot(df1['age_range'], df1[column])
sns_plot.set_title('Bill Amount for Different Age Groups on Month '+ column[-1])
sns_plot.set_ylabel('Bill Amount')
sns_plot.set_xlabel('Age Range')
fig = sns_plot.get_figure()
filename = f'static/charts/{column + "AGE"}.png'
fig.savefig(filename)
return render_template('payment_age.html', chart_src="/"+filename)
form3 = MarriageForm()
if form3.validate_on_submit():
payment_df = get_payment_data()
column = request.form.get('attributes')
df1 = payment_df[['MARRIAGE', column]]
sns.set_style('ticks')
sns_plot = sns.violinplot(df1['MARRIAGE'], df1[column])
sns_plot.set_title('Bill Amount for Different MARRIAGE Groups on Month '+ column[-1])
sns_plot.set_ylabel('Bill Amount')
sns_plot.set_xlabel('MARRIAGE')
fig = sns_plot.get_figure()
filename = f'static/charts/{column + "MARRIAGE"}.png'
fig.savefig(filename)
return render_template('payment_marriage.html', chart_src="/"+filename)
return render_template('analyticsparams.html', form1 =form1, form2 = form2, form3 = form3)
if __name__ == "__main__":
app.run()
| Final Project/falsk.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %matplotlib inline
import csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
records = pd.read_csv('../data/fucking_final_dataset.csv')
records = records[records.pub_year > 1799]
records = records[records.pub_year < 1900]
len(records)
records.head(1)
plt.rcParams['figure.figsize'] = (12.0, 6.0)
records.groupby('canonical_country').count()['control_number'].sort_values(inplace=False, ascending=False).ix[:10].plot(kind="bar")
records.groupby('slug').count()['control_number'].sort_values(inplace=False, ascending=False).ix[:25].plot(kind="bar")
# ## Global Publication By Year
records.sort_values('pub_year').groupby('pub_year').count()['control_number'].plot()
top_slugs = records.groupby('slug').count()['control_number'].sort_values(inplace=False, ascending=False).ix[:11].index
top_slugs
top_producers = records[records.slug.isin(top_slugs)]
group_top_producers = top_producers.sort_values('pub_year').groupby(['slug', 'pub_year']).count()['control_number']
top_producer_df = pd.DataFrame({
'madrid,spain': group_top_producers.ix['madrid,spain'],
'mexico,mexico': group_top_producers.ix['mexico,mexico'],
'barcelona,spain': group_top_producers.ix['barcelona,spain'],
'lisbon,portugal': group_top_producers.ix['lisbon,portugal'],
'santiago,chile': group_top_producers.ix['santiago,chile'],
'buenos aires,argentina': group_top_producers.ix['buenos aires,argentina'],
'rio de janeiro,brazil': group_top_producers.ix['rio de janeiro,brazil'],
'lima,peru': group_top_producers.ix['lima,peru'],
'valencia,spain': group_top_producers.ix['valencia,spain'],
'paris': group_top_producers.ix['paris'],
})
top_producer_df.plot()
counted_by_year = records.sort_values('pub_year').groupby('pub_year').count()['control_number']
top_producer_df_percent = pd.DataFrame({
'madrid,spain': top_producer_df['madrid,spain'].divide(counted_by_year.values),
'mexico,mexico': top_producer_df['mexico,mexico'].divide(counted_by_year.values),
'barcelona,spain': top_producer_df['barcelona,spain'].divide(counted_by_year.values),
'lisbon,portugal': top_producer_df['lisbon,portugal'].divide(counted_by_year.values),
'santiago,chile': top_producer_df['santiago,chile'].divide(counted_by_year.values),
# 'buenos aires,argentina': top_producer_df['buenos aires,argentina'].divide(counted_by_year.values),
# 'rio de janeiro,brazil': top_producer_df['rio de janeiro,brazil'].divide(counted_by_year.values),
# 'lima,peru': top_producer_df['lima,peru'].divide(counted_by_year.values),
# 'valencia,spain': top_producer_df['valencia,spain'].divide(counted_by_year.values),
# 'havana,cuba': top_producer_df['havana,cuba'].divide(counted_by_year.values),
})
top_producer_df_percent.plot.area(stacked=False)
| processing/final_analysis/19th_century_geotemporal_analysis.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Advanced topics
#
# The following material is a deep-dive into Yangson, and is not necessarily representative of how one would perform manipulations in a production environment. Please refer to the other tutorials for a better picture of Rosetta's intended use. Keep in mind that the key feature of Yangson is to be able to manipulate YANG data models in a more human-readable format, ala JSON. What lies below digs beneath the higher-level abstractions and should paint a decent picture of the functional nature of Yangson.
# # Manipulating models with Rosetta and Yangson
#
# One of the goals of many network operators is to provide abstractions in a multi-vendor environment. This can be done with YANG and OpenConfig data models, but as they say, the devil is in the details. It occurred to me that you should be able to parse configuration from one vendor and translate it to another. Unfortunately, as we all know, these configurations don't always translate well on a 1-to-1 basis. I will demonstrate this process below and show several features of the related libraries along the way.
#
# The following example begins exactly the same as the Cisco parsing tutorial. Let's load up some Juniper config and parse it into a YANG data model. First, we'll read the file.
# +
from ntc_rosetta import get_driver
import json
junos = get_driver("junos", "openconfig")
junos_driver = junos()
# Strip any rpc tags before and after `<configuration>...</configuration>`
with open("data/junos/dev_conf.xml", "r") as fp:
config = fp.read()
print(config)
# -
# ## Junos parsing
#
# Now, we parse the config and take a look at the data model.
# +
from sys import exc_info
from yangson.exceptions import SemanticError
try:
parsed = junos_driver.parse(
native={"dev_conf": config},
validate=False,
include=[
"/openconfig-interfaces:interfaces",
"/openconfig-network-instance:network-instances/network-instance/name",
"/openconfig-network-instance:network-instances/network-instance/config",
"/openconfig-network-instance:network-instances/network-instance/vlans",
]
)
except SemanticError as e:
print(f"error: {e}")
print(json.dumps(parsed.raw_value(), sort_keys=True, indent=2))
# -
# ## Naive translation
# Since we have a valid data model, let's see if Rosetta can translate it as-is.
# +
ios = get_driver("ios", "openconfig")
ios_driver = ios()
native = ios_driver.translate(candidate=parsed.raw_value())
print(native)
# -
# Pretty cool, right?! Rosetta does a great job of parsing and translating, but it is a case of "monkey see, monkey do". Rosetta doesn't have any mechanisms to translate interface names, for example. It is up to the operator to perform this sort of manipulation.
#
# ## Down the Yangson rabbit hole
# Yangson allows the developer to easily translate between YANG data models and JSON. Most all of these manipulations can be performed on dictionaries in Python and loaded into data models using [`from_raw`](https://yangson.labs.nic.cz/datamodel.html#yangson.datamodel.DataModel.from_raw). The following examples may appear to be a little obtuse, but the goal is to demonstrate the internals of Yangson.
#
# ### And it's mostly functional
# It is critical to read the short description of the [zipper](https://yangson.labs.nic.cz/instance.html?highlight=zipper#yangson.instance.InstanceNode) interface in the InstanceNode section of the docs. Yanson never manipulates an object, but returns a copy with the manipulated attributes.
#
# ### Show me the code!
# Let's take a look at fixing up the interface names and how we can manipulate data model attributes. To do that, we need to locate the attribute in the tree using the [`parse_resource_id`](https://yangson.labs.nic.cz/datamodel.html#yangson.datamodel.DataModel.parse_resource_id) method. This method returns an [`instance route'](https://yangson.labs.nic.cz/instance.html?highlight=arrayentry#yangson.instance.InstanceRoute). The string passed to the method is an xpath.
#
# Locate the interfaces in the tree. We need to modify this one
# Note that we have to URL-escape the forward slashes per https://tools.ietf.org/html/rfc8040#section-3.5.3
irt = parsed.datamodel.parse_resource_id("openconfig-interfaces:interfaces/interface=xe-0%2F0%2F1")
current_data = parsed.root.goto(irt)
print("Current node configuration: ", json.dumps(current_data.raw_value(), sort_keys=True, indent=2))
modify_data = current_data.raw_value()
ifname = 'Ethernet0/0/1'
modify_data['name'] = ifname
modify_data['config']['name'] = ifname
stub = current_data.update(modify_data, raw=True)
print("\n\nCandidate node configuration: ", json.dumps(stub.raw_value(), sort_keys=True, indent=2))
# ### Instance routes
# You will notice a `goto` method on child nodes. You _can_ access successors with this method, but you have to build the path from the root `datamodel` attribute as seen in the following example. If you aren't sure where an object is in the tree, you can also rely on its `path` attribute.
#
# Quick tangent... what is the difference between `parse_instance_id` and `parse_resource_id`? The answer can be found in the [Yangson glossary](https://yangson.labs.nic.cz/glossary.html) and the respective RFC's.
# +
# TL;DR
irt = parsed.datamodel.parse_instance_id('/openconfig-network-instance:network-instances/network-instance[1]/vlans/vlan[3]')
print(parsed.root.goto(irt).raw_value())
irt = parsed.datamodel.parse_resource_id('openconfig-network-instance:network-instances/network-instance=default/vlans/vlan=10')
print(parsed.root.goto(irt).raw_value())
# -
# What about the rest of the interfaces in the list? Yangson provides an iterator for array nodes.
# +
import re
irt = parsed.datamodel.parse_resource_id("openconfig-interfaces:interfaces/interface")
iface_objs = parsed.root.goto(irt)
# Swap the name as required
p, sub = re.compile(r'xe-'), 'Ethernet'
# There are a couple challenges here. First is that Yanson doesn't impliment __len__
# The second problem is that you cannot modify a list in-place, so we're basically
# hacking this to hijack the index of the current element and looking it up from a "clean"
# instance. This is a pet example! It would be much easier using Python dicts.
new_ifaces = None
for iface in iface_objs:
name_irt = parsed.datamodel.parse_instance_id('/name')
cname_irt = parsed.datamodel.parse_instance_id('/config/name')
if new_ifaces:
name = new_ifaces[iface.index].goto(name_irt)
else:
name = iface.goto(name_irt)
name = name.update(p.sub(sub, name.raw_value()), raw=True)
cname = name.up().goto(cname_irt)
cname = cname.update(p.sub(sub, cname.raw_value()), raw=True)
iface = cname.up().up()
new_ifaces = iface.up()
print(json.dumps(new_ifaces.raw_value(), sort_keys=True, indent=2))
# +
# Translate to Cisco-speak
native = ios_driver.translate(candidate=new_ifaces.top().raw_value())
print(native)
# -
# Hooray! That should work. One final approach, just to show you different ways of doing things. This is another pet example to demonstrate Yangson methods.
# +
import re
from typing import Dict
irt = parsed.datamodel.parse_resource_id("openconfig-interfaces:interfaces")
iface_objs = parsed.root.goto(irt)
# Nuke the whole branch!
iface_objs = iface_objs.delete_item("interface")
def build_iface(data: str) -> Dict:
# Example template, this could be anything you like that conforms to the schema
return {
"name": f"{data['name']}",
"config": {
"name": f"{data['name']}",
"description": f"{data['description']}",
"type": "iana-if-type:ethernetCsmacd",
"enabled": True
},
}
iface_data = [
build_iface({
"name": f"TenGigabitEthernet0/{idx}",
"description": f"This is interface TenGigabitEthernet0/{idx}"
}) for idx in range(10, 0, -1)
]
initial = iface_data.pop()
# Start a new interface list
iface_objs = iface_objs.put_member("interface", [initial], raw=True)
cur_obj = iface_objs[0]
# Yangson exposes `next`, `insert_after`, and `insert_before` methods.
# There is no `append`.
while iface_data:
new_obj = cur_obj.insert_after(iface_data.pop(), raw=True)
cur_obj = new_obj
# +
# Translate to Cisco-speak
native = ios_driver.translate(candidate=cur_obj.top().raw_value())
print(native)
# -
# ### Deleting individual items
# Here is an example of deleting an individual item. Navigating the tree can be a bit tricky, but it's not too bad once you get the hang of it.
# Locate a vlan by ID and delete it
irt = parsed.datamodel.parse_resource_id("openconfig-network-instance:network-instances/network-instance=default/vlans/vlan=10")
vlan10 = parsed.root.goto(irt)
vlans = vlan10.up().delete_item(vlan10.index)
print(json.dumps(vlans.raw_value(), sort_keys=True, indent=2))
| docs/tutorials/rosetta_and_yangson_walkthrough.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.10.0 64-bit (''cpp'': conda)'
# language: python
# name: python3
# ---
# # ็ฑปๅๆ็คบ
#
# {mod}`typing` ๆไพไบๅฏน็ฑปๅๆ็คบ็่ฟ่กๆถๆฏๆใๆๅบๆฌ็ๆฏๆๅ
ๆฌ {data}`Any`, {data}`Union`, {data}`Callable`, {class}`TypeVar`, ๅ {class}`Generic`ใ
#
# ็คบไพ๏ผ
# +
def greeting(name: str) -> str:
return 'Hello ' + name
getattr(greeting, '__annotations__', None)
# -
# ## ็ฑปๅๅซๅ
#
# ๆ็ฑปๅ่ต็ปๅซๅ๏ผๅฐฑๅฏไปฅๅฎไน็ฑปๅๅซๅใๆฌไพไธญ๏ผ`Vector` ๅ `list[float]` ็ธๅ๏ผๅฏไบๆข๏ผ
# +
Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# ็ฑปๅๆฃๆฅ๏ผไธไธชๆตฎ็นๆฐ็ๅ่กจๅฏไปฅไฝไธบไธไธชๅ้
new_vector = scale(2.0, [1.0, -4.2, 5.4])
new_vector
# -
# ็ฑปๅๅซๅ้็จไบ็ฎๅๅคๆ็็ฑปๅ็ญพๅใไพๅฆ๏ผ
# +
from collections.abc import Sequence
from typing import NoReturn
ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> NoReturn:
...
# ้ๆ็ฑปๅๆฃๆฅๅจไผๅฐไนๅ็็ฑปๅ็ญพๅ่งไธบไธๆญคๅฎๅ
จ็ญไปทใ
def broadcast_message(
message: str,
servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> NoReturn:
...
# -
# ## NewType
#
# ไฝฟ็จ {class}`typing.NewType` ๅๅปบ็ฎๅ็ๅฏไธ็ฑปๅ๏ผๅ ไนๆฒกๆ่ฟ่กๆถ็ๅผ้ใ`NewType(name, tp)` ่ขซ่ฎคไธบๆฏ `tp` ็ๅญ็ฑปๅใๅจ่ฟ่กๆถ๏ผ`NewType(name, tp)` ็ฎๅๅฐ่ฟๅๅ
ถๅๆฐ็ dummy ๅฝๆฐใไฝฟ็จๆนๆณ๏ผ
# +
from typing import NewType
UserId = NewType('UserId', int)
def name_by_id(user_id: UserId) -> str: ...
UserId('user') # ็ฑปๅๆฃๆฅๅคฑ่ดฅ
name_by_id(42) # ็ฑปๅๆฃๆฅๅคฑ่ดฅ
name_by_id(UserId(42)) # ๆญฃ็กฎ
num = UserId(5) + 1 # ็ฑปๅ๏ผ`int`
# -
# 1. ้ๆ็ฑปๅๆฃๆฅๅจๆๆฐ็ฑปๅๅฝไฝๅๅง็ฑปๅ็ๅญ็ฑป๏ผ่ฟ็งๆนๅผ้็จไบๆๆ้ป่พ้่ฏฏใ
# 2. `NewType` ๅฃฐๆๆไธ็ง็ฑปๅๅฝไฝๅฆไธ็ง็ฑปๅ็ๅญ็ฑปๅใ`Derived = NewType('Derived', Original)` ๆถ๏ผ้ๆ็ฑปๅๆฃๆฅๅจๆ `Derived` ๅฝไฝ `Original` ็ๅญ็ฑป ๏ผๅณ๏ผ`Original` ็ฑปๅ็ๅผไธ่ฝ็จๅจ้ขๆ `Derived` ็ฑปๅ็ไฝ็ฝฎใ่ฟ็งๆนๅผ้็จไบไปฅๆๅฐ่ฟ่กๆถๆๆฌ้ฒๆญข้ป่พ้่ฏฏใ
# 3. ็ปงๆฟ `NewType` ๅฃฐๆ็ๅญ็ฑปๅๆฏๆ ๆ็ใ
#
# ## ๅฏ่ฐๅฏน่ฑก
#
# ้ขๆ็นๅฎ็ญพๅๅ่ฐๅฝๆฐ็ๆกๆถๅฏไปฅ็จ `Callable[[Arg1Type, Arg2Type], ReturnType]` ๅฎ็ฐ็ฑปๅๆ็คบใ
# +
from typing import Callable
def feeder(get_next_item: Callable[[], str]) -> None:
# Body
...
def async_query(on_success: Callable[[int], None],
on_error: Callable[[int, Exception], None]) -> None:
# Body
...
# -
# ๆ ้ๆๅฎ่ฐ็จ็ญพๅ๏ผ็จ็็ฅๅทๅญ้ข้ๆฟๆข็ฑปๅๆ็คบ้็ๅๆฐๅ่กจ๏ผ `Callable[..., ReturnType]`๏ผๅฐฑๅฏไปฅๅฃฐๆๅฏ่ฐๅฏน่ฑก็่ฟๅ็ฑปๅใ
#
# ไปฅๅ
ถไปๅฏ่ฐ็จๅฏน่ฑกไธบๅๆฐ็ๅฏ่ฐ็จๅฏน่ฑกๅฏไปฅไฝฟ็จ `ParamSpec` ๆฅ่กจๆๅ
ถๅๆฐ็ฑปๅๆฏ็ธไบไพ่ต็ใๆญคๅค๏ผๅฆๆ่ฏฅๅฏ่ฐ็จๅฏน่ฑกๅขๅ ๆๅ ้คไบๅ
ถไปๅฏ่ฐ็จๅฏน่ฑก็ๅๆฐ๏ผๅฏไปฅไฝฟ็จ `Concatenate` ๆไฝ็ฌฆใๅฎไปฌๅๅซ้ๅ `Callable[ParamSpecVariable, ReturnType]` ๅ `Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]` ็ๅฝขๅผใ
#
# ## ๆณๅ
#
# ๅฎนๅจไธญ๏ผๅฏน่ฑก็็ฑปๅไฟกๆฏไธ่ฝไปฅๆณๅๆนๅผ้ๆๆจๆญ๏ผๅ ๆญค๏ผๆฝ่ฑกๅบ็ฑปๆฉๅฑๆฏๆไธๆ ๏ผ็จไบ่กจ็คบๅฎนๅจๅ
็ด ็้ขๆ็ฑปๅใ
# ```python
# from typing import Mapping, Sequence
#
# def notify_by_email(employees: Sequence[Employee],
# overrides: Mapping[str, str]) -> None: ...
# ```
#
# {class}`typing.TypeVar` ๅทฅๅๅฝๆฐๅฎ็ฐๆณๅๅๆฐๅใ
#
# ```python
# from typing import TypeVar
#
# T = TypeVar('T') # Declare type variable
#
# def first(l: Sequence[T]) -> T: # Generic function
# return l[0]
# ```
#
# ## ็จๆทๅฎไน็ๆณๅ็ฑปๅ
#
# ็จๆทๅฎไน็็ฑปๅฏไปฅๅฎไนไธบๆณๅ็ฑปใ
# +
from typing import TypeVar, Generic
from logging import Logger
T = TypeVar('T')
class LoggedVar(Generic[T]):
def __init__(self, value: T, name: str, logger: Logger) -> None:
self.name = name
self.logger = logger
self.value = value
def set(self, new: T) -> None:
self.log('Set ' + repr(self.value))
self.value = new
def get(self) -> T:
self.log('Get ' + repr(self.value))
return self.value
def log(self, message: str) -> None:
self.logger.info('%s: %s', self.name, message)
# -
# `Generic[T]` ๆฏๅฎไน็ฑป `LoggedVar` ็ๅบ็ฑป๏ผ่ฏฅ็ฑปไฝฟ็จๅ็ฑปๅๅๆฐ `T`ใๅจ่ฏฅ็ฑปไฝๅ
๏ผ`T` ๆฏๆๆ็็ฑปๅใ
#
| doc/analysis/draft/typing.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
# -
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import Lasso
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
df = pd.read_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/AAA hh.csv")
plt.scatter(df[(df.cost_2018_per_member_log != 0) & (df.cost_2019_per_member_log != 0)].cost_2018_per_member_log,
df[(df.cost_2018_per_member_log != 0) & (df.cost_2019_per_member_log != 0)].cost_2019_per_member_log,
alpha = 0.7)
plt.scatter(df.cost_2018_per_member_log,
df.cost_2019_per_member_log,
alpha = 0.7)
plt.scatter(df[df['call_2019_dummy'] == 1].cost_2018_per_member_log,
df[df['call_2019_dummy'] == 1].cost_2019_per_member_log,
alpha = 0.7)
df.billing_grouped_other.value_counts()
cond = ~((df.billing_grouped_downgrade_member == 1) |
(df.billing_grouped_new_member == 1) |
(df.billing_grouped_renewal_to_daily == 1))
df.billing_grouped_other = df.billing_grouped_other.where(cond,1)
df.billing_grouped_other.value_counts()
df['dwelling_type_large_multi-family_w/o_apt_number'].value_counts()
df['dwelling_type_p.o._box'].value_counts()
df = df.assign(dwelling_type_other = ((df['dwelling_type_large_multi-family_w/o_apt_number'] == 1) |
(df['dwelling_type_p.o._box'] == 1)).astype('float64').astype('int'))
df = df.assign(fsv_rare_dummy = ((df.fsv_deposit_program_flag_y == 1) |
(df.fsv_home_equity_flag_y == 1) |
(df.fsv_mortgage_flag_y == 1)
).astype('float64').astype('int'))
df = df.assign(primary_race_hispanic = ((df['primary_race_grouped_hispanic_-_hispanic_origin'] == 1) |
(df['primary_race_grouped_hispanic_-_portuguese_origin'] == 1)
).astype('float64').astype('int'))
df = df.assign(primary_occupation_retired = ((df['primary_occupation_group_grouped_retired_-_inferred'] == 1) |
(df['primary_occupation_group_grouped_retired_-_known'] == 1)
).astype('float64').astype('int'))
df = df.assign(new_member_dummy = (df['new_member'] == 1).astype('float64').astype('int'))
[i for i in df.columns]
# LINEAR REGRESSION WILL BE RUN ON A SUBSAMPLE OF THOSE WHO HAD CALLS IN 2019. ADDITIONAL GROUPING OF VARIABLES IS NEEDED
df['call_2019_dummy'].value_counts()
df = df.assign(email_status_other_grouped = ((df.email_status_bounced == 1) |
(df.email_status_held == 1)).astype('float64').astype('int'))
df.email_status_other_grouped.value_counts()
df = df.assign(primary_mosaic_global_household_other_grouped = ((df['primary_mosaic_global_household_low_income_elders'] == 1) |
(df['primary_mosaic_global_household_metropolitan_strugglers'] == 1) |
(df['primary_mosaic_global_household_rural_inheritance'] == 1) |
(df['primary_mosaic_global_household_sophisticated_singles'] == 1)
).astype('float64').astype('int'))
df.primary_mosaic_global_household_other_grouped.value_counts()
df = df.assign(primary_occupation_group_grouped_blue_collar = ((df['primary_occupation_group_grouped_blue_collar_-_inferred'] == 1) |
(df['primary_occupation_group_grouped_blue_collar_-_known'] == 1)
).astype('float64').astype('int'))
df.primary_occupation_group_grouped_blue_collar.value_counts()
df = df.assign(primary_occupation_group_grouped_management = ((df['primary_occupation_group_grouped_management_-_inferred'] == 1) |
(df['primary_occupation_group_grouped_management_-_known'] == 1)
).astype('float64').astype('int'))
df.primary_occupation_group_grouped_management.value_counts()
df = df.assign(primary_occupation_group_grouped_office_administration = ((df['primary_occupation_group_grouped_office_administration_-_inferred'] == 1) |
(df['primary_occupation_group_grouped_office_administration_-_known'] == 1)
).astype('float64').astype('int'))
df.primary_occupation_group_grouped_office_administration.value_counts()
df = df.assign(primary_occupation_group_grouped_other = ((df['primary_occupation_group_grouped_other_-_inferred'] == 1) |
(df['primary_occupation_group_grouped_other_-_known'] == 1)
).astype('float64').astype('int'))
df.primary_occupation_group_grouped_other.value_counts()
df = df.assign(primary_occupation_group_grouped_professional = ((df['primary_occupation_group_grouped_professional_-_inferred'] == 1) |
(df['primary_occupation_group_grouped_professional_-_known'] == 1)
).astype('float64').astype('int'))
df.primary_occupation_group_grouped_professional.value_counts()
df = df.assign(primary_occupation_group_grouped_sales = ((df['primary_occupation_group_grouped_sales_-_inferred'] == 1) |
(df['primary_occupation_group_grouped_sales_-_known'] == 1)
).astype('float64').astype('int'))
df.primary_occupation_group_grouped_sales.value_counts()
df = df.assign(primary_race_grouped_other_grouped = (
(df['primary_race_grouped_asian'] == 1) |
(df['primary_race_grouped_middle_eastern'] == 1) |
(df['primary_race_grouped_other'] == 1) |
(df['primary_race_grouped_unknown'] == 1)
).astype('float64').astype('int'))
df.primary_race_grouped_other_grouped.value_counts()
X = [
'aaa_before_club_dummy',
'fin_missing',
'renew_not_notice',
'billing_grouped_other',
'billing_grouped_upgrade_member',
'county_grouped_bristol',
'county_grouped_kent',
'county_grouped_newport',
'county_grouped_washington',
'dwelling_type_small_or_large_multi-family_w/apt_number',
'email_status_unsubscribed',
'email_status_other_grouped',
'email_status_nan',
'member_phone_type_landline',
'member_phone_type_voip',
'member_phone_type_nan',
'new_mover_flag_y',
'plus_indicator_grouped_plus_membership',
'plus_indicator_grouped_premier_membership',
'mail_responder_no',
'responded_to_catalog_yes',
'responded_to_catalog_yes_multiple_responses',
'primary_education_completed_college',
'primary_education_high_school',
'primary_education_unknown',
'primary_gender_grouped_male',
'primary_gender_grouped_nan',
'primary_language_grouped_unknown',
'primary_mosaic_global_household_bourgeois_prosperity',
'primary_mosaic_global_household_career_and_family',
'primary_mosaic_global_household_hard_working_blue_collar',
'primary_mosaic_global_household_post_industrial_survivors',
'primary_mosaic_global_household_routine_service_workers',
'primary_mosaic_global_household_other_grouped',
'primary_mosaic_global_household_nan',
'primary_occupation_group_grouped_blue_collar',
'primary_occupation_group_grouped_management',
'primary_occupation_group_grouped_office_administration',
'primary_occupation_group_grouped_other',
'primary_occupation_group_grouped_professional',
'primary_occupation_group_grouped_sales',
'primary_occupation_group_grouped_technical',
'primary_race_hispanic',
'primary_race_grouped_other_grouped',
'children_num_std',
'primary_credit_ranges_num_std',
'primary_income_mid_std',
'member_out_std',
'age_2018_primary_std',
'join_club_year_std',
'active_2018_std'
]
X01 = list(X)
X02 = list(X)
X03 = list(X)
X04 = list(X)
X01.append('cost_2018_std')
X02.append('cost_2018_per_member_std')
X03.append('cost_2018_log_std')
X04.append('cost_2018_per_member_log_std')
# SPLIT INTO TRAIN AND TEST SETS
df_train, df_test = train_test_split(df, random_state = 15)
# LINEAR REGRESSION
X_train_01 = df_train[df_train['call_2019_dummy'] == 1][X01]
X_test_01 = df_test[df_test['call_2019_dummy'] == 1][X01]
Y_train_01 = df_train[df_train['call_2019_dummy'] == 1].cost_2019
Y_test_01 = df_test[df_test['call_2019_dummy'] == 1].cost_2019
X_train_02 = df_train[df_train['call_2019_dummy'] == 1][X02]
X_test_02 = df_test[df_test['call_2019_dummy'] == 1][X02]
Y_train_02 = df_train[df_train['call_2019_dummy'] == 1].cost_2019_per_member
Y_test_02 = df_test[df_test['call_2019_dummy'] == 1].cost_2019_per_member
X_train_03 = df_train[df_train['call_2019_dummy'] == 1][X03]
X_test_03 = df_test[df_test['call_2019_dummy'] == 1][X03]
Y_train_03 = df_train[df_train['call_2019_dummy'] == 1].cost_2019_log
Y_test_03 = df_test[df_test['call_2019_dummy'] == 1].cost_2019_log
X_train_04 = df_train[df_train['call_2019_dummy'] == 1][X04]
X_test_04 = df_test[df_test['call_2019_dummy'] == 1][X04]
Y_train_04 = df_train[df_train['call_2019_dummy'] == 1].cost_2019_per_member_log
Y_test_04 = df_test[df_test['call_2019_dummy'] == 1].cost_2019_per_member_log
lr = LinearRegression()
df.shape
print(Y_train_04.shape)
print(Y_test_04.shape)
lr.fit(X_train_01, Y_train_01)
print(lr.score(X_train_01, Y_train_01))
print(lr.score(X_test_01, Y_test_01))
y_pred_01 = lr.predict(X_test_01)
print(np.sqrt(metrics.mean_squared_error(y_pred_01, df_test[df_test['call_2019_dummy'] == 1]['cost_2019'])))
y_pred_full_01 = lr.predict(df[X01])
y_pred_df_01 = pd.DataFrame(y_pred_full_01, columns = ['costs_cond_01'])
df = pd.concat([df, y_pred_df_01], axis = 1)
coefs = pd.DataFrame(lr.coef_, columns = ['Lin 01'])
coef_labels = pd.DataFrame(X_train_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Lin 01.csv")
lr.fit(X_train_02, Y_train_02)
print(lr.score(X_train_02, Y_train_02))
print(lr.score(X_test_02, Y_test_02))
y_pred_02 = lr.predict(X_test_02)
y_pred_02_transformed = y_pred_02 * df_test[df_test['call_2019_dummy'] == 1]['active_2019']
print(np.sqrt(metrics.mean_squared_error(y_pred_02_transformed,
df_test[df_test['call_2019_dummy'] == 1]['cost_2019'])))
y_pred_full_02 = lr.predict(df[X02])
y_pred_full_02_transformed = y_pred_full_02 * df['active_2019']
y_pred_df_02 = y_pred_full_02_transformed.to_frame(name = "costs_cond_02")
df = pd.concat([df, y_pred_df_02], axis = 1)
coefs = pd.DataFrame(lr.coef_, columns = ['Lin 02'])
coef_labels = pd.DataFrame(X_train_02.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Lin 02.csv")
lr.fit(X_train_03, Y_train_03)
print(lr.score(X_train_03, Y_train_03))
print(lr.score(X_test_03, Y_test_03))
y_pred_03 = lr.predict(X_test_03)
y_pred_03_transformed = np.exp(y_pred_03)
print(np.sqrt(metrics.mean_squared_error(y_pred_03_transformed,
df_test[df_test['call_2019_dummy'] == 1]['cost_2019'])))
y_pred_full_03 = lr.predict(df[X03])
y_pred_full_03_transformed = np.exp(y_pred_full_03)
y_pred_df_03 = pd.DataFrame(y_pred_full_03_transformed, columns = ["costs_cond_03"])
df = pd.concat([df, y_pred_df_03], axis = 1)
coefs = pd.DataFrame(lr.coef_, columns = ['Lin 03'])
coef_labels = pd.DataFrame(X_train_03.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Lin 03.csv")
lr.fit(X_train_04, Y_train_04)
print(lr.score(X_train_04, Y_train_04))
print(lr.score(X_test_04, Y_test_04))
y_pred_04 = lr.predict(X_test_04)
y_pred_04_transformed = np.exp(y_pred_04) * df_test[df_test['call_2019_dummy'] == 1]['active_2019']
print(np.sqrt(metrics.mean_squared_error(y_pred_04_transformed,
df_test[df_test['call_2019_dummy'] == 1]['cost_2019'])))
y_pred_full_04 = lr.predict(df[X04])
y_pred_full_04_transformed = np.exp(y_pred_full_04) * df['active_2019']
y_pred_df_04 = y_pred_full_04_transformed.to_frame(name = "costs_cond_04")
df = pd.concat([df, y_pred_df_04], axis = 1)
coefs = pd.DataFrame(lr.coef_, columns = ['Lin 04'])
coef_labels = pd.DataFrame(X_train_04.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Lin 04.csv")
pd.Series(y_pred_full_01).describe()
plt.scatter(df[df['call_2019_dummy'] == 1].cost_2019,
df[df['call_2019_dummy'] == 1].costs_cond_01,
alpha = 0.7)
plt.scatter(df.cost_2019,
df.costs_cond_01,
alpha = 0.7)
pd.Series(y_pred_full_02).describe()
pd.Series(y_pred_full_02_transformed).describe()
plt.scatter(df[df['call_2019_dummy'] == 1].cost_2019,
df[df['call_2019_dummy'] == 1].costs_cond_02,
alpha = 0.7)
plt.scatter(df.cost_2019,
df.costs_cond_02,
alpha = 0.7)
pd.Series(y_pred_full_03).describe()
pd.Series(y_pred_full_03_transformed).describe()
plt.scatter(df[df['call_2019_dummy'] == 1].cost_2019,
df[df['call_2019_dummy'] == 1].costs_cond_03,
alpha = 0.7)
plt.scatter(df.cost_2019,
df.costs_cond_03,
alpha = 0.7)
pd.Series(y_pred_full_04).describe()
pd.Series(y_pred_full_04_transformed).describe()
plt.scatter(df[df['call_2019_dummy'] == 1].cost_2019,
df[df['call_2019_dummy'] == 1].costs_cond_04,
alpha = 0.7)
plt.scatter(df.cost_2019,
df.costs_cond_04,
alpha = 0.7)
# 4th configuration (per member in logs) is kept for the following reasons:
# - Adjustment quality
# - No negative costs predictions due to logs
# LOGIT MODELS
X_rs_01 = list(X)
X_rs_02 = list(X)
X_rs_03 = list(X)
X_rs_04 = list(X)
X_rs_01.append('cost_2018_std')
X_rs_02.append('calls_2018_std')
X_rs_03.extend(['cost_2018_std',
'fsv_cmsi_flag_y',
'fsv_credit_card_flag_y',
'fsv_id_theft_flag_y',
'fsv_rare_dummy',
'ins_client_flag_y',
'trv_globalware_flag_y'
])
X_rs_04.extend(['calls_2018_std',
'fsv_cmsi_flag_y',
'fsv_credit_card_flag_y',
'fsv_id_theft_flag_y',
'fsv_rare_dummy',
'ins_client_flag_y',
'trv_globalware_flag_y'
])
X_train_rs_01 = df_train[X_rs_01]
X_test_rs_01 = df_test[X_rs_01]
X_train_rs_02 = df_train[X_rs_02]
X_test_rs_02 = df_test[X_rs_02]
X_train_rs_03 = df_train[X_rs_03]
X_test_rs_03 = df_test[X_rs_03]
X_train_rs_04 = df_train[X_rs_04]
X_test_rs_04 = df_test[X_rs_04]
Y_rs_train = df_train['call_2019_dummy']
Y_rs_test = df_test['call_2019_dummy']
from sklearn.metrics import f1_score
from sklearn.metrics import log_loss
lgr = LogisticRegression(solver = 'lbfgs', max_iter = 1000)
lgr.fit(X_train_rs_01, Y_rs_train)
rs_pred_01 = lgr.predict(X_test_rs_01)
rs_pr_01 = lgr.predict_proba(X_test_rs_01)
print(f1_score(Y_rs_test, rs_pred_01))
print(log_loss(Y_rs_test, rs_pr_01))
rs_pr_full_01 = lgr.predict_proba(df[X_rs_01])
cfm = confusion_matrix(Y_rs_test, rs_pred_01)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log rs 01'])
coef_labels = pd.DataFrame(X_train_rs_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Log rs 01.csv")
rs_pr_full_01 = lgr.predict_proba(df[X_rs_01])[:,1]
rs_pr_df_01 = pd.DataFrame(rs_pr_full_01, columns = ['rs_pred_01'])
df = pd.concat([df, rs_pr_df_01], axis = 1)
lgr.fit(X_train_rs_02, Y_rs_train)
rs_pred_02 = lgr.predict(X_test_rs_02)
rs_pr_02 = lgr.predict_proba(X_test_rs_02)
print(f1_score(Y_rs_test, rs_pred_02))
print(log_loss(Y_rs_test, rs_pr_02))
rs_pr_full_02 = lgr.predict_proba(df[X_rs_02])
cfm = confusion_matrix(Y_rs_test, rs_pred_02)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log rs 02'])
coef_labels = pd.DataFrame(X_train_rs_02.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Log rs 02.csv")
rs_pr_full_02 = lgr.predict_proba(df[X_rs_02])[:,1]
rs_pr_df_02 = pd.DataFrame(rs_pr_full_02, columns = ['rs_pred_02'])
df = pd.concat([df, rs_pr_df_02], axis = 1)
lgr.fit(X_train_rs_03, Y_rs_train)
rs_pred_03 = lgr.predict(X_test_rs_03)
rs_pr_03 = lgr.predict_proba(X_test_rs_03)
print(f1_score(Y_rs_test, rs_pred_03))
print(log_loss(Y_rs_test, rs_pr_03))
rs_pr_full_03 = lgr.predict_proba(df[X_rs_03])
cfm = confusion_matrix(Y_rs_test, rs_pred_03)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log rs 03'])
coef_labels = pd.DataFrame(X_train_rs_03.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Log rs 03.csv")
rs_pr_full_03 = lgr.predict_proba(df[X_rs_03])[:,1]
rs_pr_df_03 = pd.DataFrame(rs_pr_full_03, columns = ['rs_pred_03'])
df = pd.concat([df, rs_pr_df_03], axis = 1)
lgr.fit(X_train_rs_04, Y_rs_train)
rs_pred_04 = lgr.predict(X_test_rs_04)
rs_pr_04 = lgr.predict_proba(X_test_rs_04)
print(f1_score(Y_rs_test, rs_pred_04))
print(log_loss(Y_rs_test, rs_pr_04))
rs_pr_full_04 = lgr.predict_proba(df[X_rs_04])
cfm = confusion_matrix(Y_rs_test, rs_pred_04)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log rs 04'])
coef_labels = pd.DataFrame(X_train_rs_04.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Log rs 04.csv")
rs_pr_full_04 = lgr.predict_proba(df[X_rs_04])[:,1]
rs_pr_df_04 = pd.DataFrame(rs_pr_full_04, columns = ['rs_pred_04'])
df = pd.concat([df, rs_pr_df_04], axis = 1)
# Conclusion: No big differences in terms of performance between models. 1st configuration is kept
# BUILDING VARIABLE FOR EXPECTED COSTS
df['rs_pred_01'].describe()
df = df.assign(expected_costs = df['costs_cond_04'] * df['rs_pred_01'])
df['expected_costs'].describe()
plt.scatter(df.cost_2019,
df['expected_costs'],
alpha = 0.7)
# LOGIT MODELS FOR NEW PRODUCTS
X_new_01 = list(X_rs_01)
X_new_01.extend(['motorcycle_indicator_y', 'motorcycle_indicator_nan',])
X_new_01
# COLINEARITY CHECK
corr = np.corrcoef(df[X_rs_01], rowvar = False)
w, v = np.linalg.eig(corr)
w = pd.Series(w)
[i for i in w]
# All fine
X_train_new_01 = df_train[X_new_01]
X_test_new_01 = df_test[X_new_01]
# Logit for fsv_any
Y_fsv_any_train = df_train['fsv_any']
Y_fsv_any_test = df_test['fsv_any']
lgr.fit(X_train_new_01, Y_fsv_any_train)
fsv_any_pred_01 = lgr.predict(X_test_new_01)
fsv_any_pr_01 = lgr.predict_proba(X_test_new_01)
print(f1_score(Y_fsv_any_test, fsv_any_pred_01))
print(log_loss(Y_fsv_any_test, fsv_any_pr_01))
fsv_any_pr_full_01 = lgr.predict_proba(df[X_new_01])
cfm = confusion_matrix(Y_fsv_any_test, fsv_any_pred_01)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log FSV any 01'])
coef_labels = pd.DataFrame(X_train_new_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Log FSV any 01.csv")
fsv_any_pr_full_01 = lgr.predict_proba(df[X_new_01])[:,1]
fsv_any_pr_df_01 = pd.DataFrame(fsv_any_pr_full_01, columns = ['fsv_any_pred_01'])
df = pd.concat([df, fsv_any_pr_df_01], axis = 1)
# Logit for new products together
Y_new_any_train = df_train['new_product_any']
Y_new_any_test = df_test['new_product_any']
lgr.fit(X_train_new_01, Y_new_any_train)
new_any_pred_01 = lgr.predict(X_test_new_01)
new_any_pr_01 = lgr.predict_proba(X_test_new_01)
print(f1_score(Y_new_any_test, new_any_pred_01))
print(log_loss(Y_new_any_test, new_any_pr_01))
new_any_pr_full_01 = lgr.predict_proba(df[X_new_01])
cfm = confusion_matrix(Y_new_any_test, new_any_pred_01)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log new any 01'])
coef_labels = pd.DataFrame(X_train_new_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Log new any 01.csv")
new_any_pr_full_01 = lgr.predict_proba(df[X_new_01])[:,1]
new_any_pr_df_01 = pd.DataFrame(new_any_pr_full_01, columns = ['new_any_pred_01'])
df = pd.concat([df, new_any_pr_df_01], axis = 1)
# Logit for FSV CMSI
Y_cmsi_train = df_train['fsv_cmsi_flag_y']
Y_cmsi_test = df_test['fsv_cmsi_flag_y']
lgr.fit(X_train_new_01, Y_cmsi_train)
cmsi_pred_01 = lgr.predict(X_test_new_01)
cmsi_pr_01 = lgr.predict_proba(X_test_new_01)
print(f1_score(Y_cmsi_test, cmsi_pred_01))
print(log_loss(Y_cmsi_test, cmsi_pr_01))
cmsi_pr_full_01 = lgr.predict_proba(df[X_new_01])
cfm = confusion_matrix(Y_cmsi_test, cmsi_pred_01)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log CMSI 01'])
coef_labels = pd.DataFrame(X_train_new_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Log CMSI 01.csv")
cmsi_pr_full_01 = lgr.predict_proba(df[X_new_01])[:,1]
cmsi_pr_df_01 = pd.DataFrame(cmsi_pr_full_01, columns = ['cmsi_pred_01'])
df = pd.concat([df, cmsi_pr_df_01], axis = 1)
# Logit for credit card
Y_credit_train = df_train['fsv_credit_card_flag_y']
Y_credit_test = df_test['fsv_credit_card_flag_y']
lgr.fit(X_train_new_01, Y_credit_train)
credit_pred_01 = lgr.predict(X_test_new_01)
credit_pr_01 = lgr.predict_proba(X_test_new_01)
print(f1_score(Y_credit_test, credit_pred_01))
print(log_loss(Y_credit_test, credit_pr_01))
credit_pr_full_01 = lgr.predict_proba(df[X_new_01])
cfm = confusion_matrix(Y_credit_test, credit_pred_01)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log Credit 01'])
coef_labels = pd.DataFrame(X_train_new_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Log Credit 01.csv")
credit_pr_full_01 = lgr.predict_proba(df[X_new_01])[:,1]
credit_pr_df_01 = pd.DataFrame(credit_pr_full_01, columns = ['credit_pred_01'])
df = pd.concat([df, credit_pr_df_01], axis = 1)
# ID theft
Y_id_train = df_train['fsv_id_theft_flag_y']
Y_id_test = df_test['fsv_id_theft_flag_y']
lgr.fit(X_train_new_01, Y_id_train)
id_pred_01 = lgr.predict(X_test_new_01)
id_pr_01 = lgr.predict_proba(X_test_new_01)
id_pr_full_01 = lgr.predict_proba(df[X_new_01])[:,1]
id_pr_df_01 = pd.DataFrame(id_pr_full_01, columns = ['id_pred_01'])
df = pd.concat([df, id_pr_df_01], axis = 1)
cfm = confusion_matrix(Y_id_test, id_pred_01)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log ID 01'])
coef_labels = pd.DataFrame(X_train_new_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef Log ID 01.csv")
print(f1_score(Y_id_test, id_pred_01))
print(log_loss(Y_id_test, id_pr_01))
id_pr_full_01 = lgr.predict_proba(df[X_new_01])
# Logit for other FSV
Y_fsv_rare_train = df_train['fsv_rare_dummy']
Y_fsv_rare_test = df_test['fsv_rare_dummy']
lgr.fit(X_train_new_01, Y_fsv_rare_train)
fsv_rare_pred_01 = lgr.predict(X_test_new_01)
fsv_rare_pr_01 = lgr.predict_proba(X_test_new_01)
fsv_rare_pr_full_01 = lgr.predict_proba(df[X_new_01])[:,1]
fsv_rare_pr_df_01 = pd.DataFrame(fsv_rare_pr_full_01, columns = ['fsv_rare_pred_01'])
df = pd.concat([df, fsv_rare_pr_df_01], axis = 1)
cfm = confusion_matrix(Y_fsv_rare_test, fsv_rare_pred_01)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log FSV rare 01'])
coef_labels = pd.DataFrame(X_train_new_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef FSV rare 01.csv")
print(f1_score(Y_fsv_rare_test, fsv_rare_pred_01))
print(log_loss(Y_fsv_rare_test, fsv_rare_pr_01))
fsv_rare_pr_full_01 = lgr.predict_proba(df[X_new_01])
# Logit Insurance
Y_ins_train = df_train['ins_client_flag_y']
Y_ins_test = df_test['ins_client_flag_y']
lgr.fit(X_train_new_01, Y_ins_train)
ins_pred_01 = lgr.predict(X_test_new_01)
ins_pr_01 = lgr.predict_proba(X_test_new_01)
ins_pr_full_01 = lgr.predict_proba(df[X_new_01])[:,1]
ins_pr_df_01 = pd.DataFrame(ins_pr_full_01, columns = ['ins_pred_01'])
df = pd.concat([df, ins_pr_df_01], axis = 1)
cfm = confusion_matrix(Y_ins_test, ins_pred_01)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log INS 01'])
coef_labels = pd.DataFrame(X_train_new_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef INS 01.csv")
print(f1_score(Y_ins_test, ins_pred_01))
print(log_loss(Y_ins_test, ins_pr_01))
ins_pr_full_01 = lgr.predict_proba(df[X_new_01])
# Logit for travel
Y_trv_train = df_train['trv_globalware_flag_y']
Y_trv_test = df_test['trv_globalware_flag_y']
lgr.fit(X_train_new_01, Y_trv_train)
trv_pred_01 = lgr.predict(X_test_new_01)
trv_pr_01 = lgr.predict_proba(X_test_new_01)
trv_pr_full_01 = lgr.predict_proba(df[X_new_01])[:,1]
trv_pr_df_01 = pd.DataFrame(trv_pr_full_01, columns = ['trv_pred_01'])
df = pd.concat([df, trv_pr_df_01], axis = 1)
cfm = confusion_matrix(Y_trv_test, trv_pred_01)
print(cfm)
coefs = pd.DataFrame(lgr.coef_.transpose(), columns = ['Log TRV 01'])
coef_labels = pd.DataFrame(X_train_new_01.columns, columns = ['Variable'])
coef_df = pd.concat([coef_labels, coefs], axis = 1)
export_csv = coef_df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/Coef TRV 01.csv")
print(f1_score(Y_trv_test, trv_pred_01))
print(log_loss(Y_trv_test, trv_pr_01))
trv_pr_full_01 = lgr.predict_proba(df[X_new_01])
export_csv = df.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/AAA for cluster.csv")
export_csv = df_train.to_csv("C:/Slava/08 Studies/00 Emeritus/04 - Capstone/AAA train.csv")
| 05. AAA Analysis Final.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Pandas Data Structure
# pandas.Series() - 1 Dimension<br>
# pandas.DataFrame() - 2 Dimensions<br>
# pandas.Panel() - 3 Dimensions<br>
# numpy.ndarray() - N Dimensions
import pandas as pd
stock_dict = {
'AMZN': pd.Series(
[346.15, 0.59, 459, 0.52, 589.8, 158.88],
index = ['Closing price', 'EPS', 'Shares Outstanding (M)', 'Beta', 'P/E', 'Market Cap (B)']
),
'GOOG': pd.Series(
[1133.43, 36.05, 335.83, 0.87, 31.44, 380.64],
index = ['Closing price', 'EPS', 'Shares Outstanding (M)', 'Beta', 'P/E', 'Market Cap (B)']
),
'FB': pd.Series(
[61.48, 0.59, 2450, 104.93, 150.92],
index = ['Closing price', 'EPS', 'Shares Outstanding (M)', 'P/E', 'Market Cap(B)']
),
'YHOO': pd.Series(
[34.90, 1.27, 1010, 27.48, 0.66, 35.36],
index = ['Closing price', 'EPS', 'Shares Outstanding (M)', 'P/E', 'Beta', 'Market Cap (B)']
),
'TWTR': pd.Series(
[65.25, -0.3, 555.2, 36.23],
index=['Closing price', 'EPS', 'Shares Outstanding (M)', 'Market Cap (B)']
),
'AAPL': pd.Series(
[501.53, 40.32, 892.45, 12.44, 447.59, 0.84],
index = ['Closing price', 'EPS', 'Shares Outstanding (M)', 'P/E', 'Market Cap (B)', 'Beta']
)
}
stock_df = pd.DataFrame(stock_dict)
stock_df
# ### Setting Indexes
stock_df = pd.DataFrame(stock_dict,
index = ['Closing price',
'EPS',
'Shares Outstanding (M)',
'P/E',
'Market Cap (B)',
'Beta'])
stock_df
# ### Setting Columns
stock_df = pd.DataFrame(stock_dict,
index = ['Closing price',
'EPS',
'Shares Outstanding (M)',
'P/E',
'Market Cap (B)',
'Beta'],
columns = ['FB', 'TWTR', 'SCNW'])
stock_df
# ### Checking Indexes and Columns
stock_df.index
stock_df.columns
| modules/01-data-manipulation/04-pandas-dataframes-structures.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.8.8 64-bit (''Qiskit_Ocean'': conda)'
# name: python388jvsc74a57bd0173f2ffbce537830dc37cc01123f1dcc118f483457eee13e6b392e68a5e39cc7
# ---
# +
import os
import shutil
import time
from random_lp.random_qp import RandomQuadraticProgram
DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y")
def getPath(filename = "", directory = ""):
return DIR + "/" + directory + "/" + filename
DIR
# -
shutil.rmtree(DIR, ignore_errors=True)
os.makedirs(getPath(directory = "DENSE"))
os.makedirs(getPath(directory = "SPARSE"))
# we want up to 33 qubits since ibmq_qasm_simulator has 32
max_qubits = 32
# create dense random binary quadratic programs
var = 3
while True:
cstr = int(var / 2)
qp_bin = RandomQuadraticProgram.create_random_binary_prog("test_dense_" + str(var), cstr, var)
qp_bin.write_to_lp_file(getPath(qp_bin.name, directory = "DENSE"))
if qp_bin.complexity() > max_qubits :
print(var)
break
var = var + 2
# +
# create sparse random binary quadratic programs
# 3 variables with 2 constraints each
var = 3
cstr = 2
multiple = 2
while True:
qp_bin = RandomQuadraticProgram.create_random_binary_prog("test_sparse_" + str(multiple), cstr, var, multiple=multiple)
qp_bin.write_to_lp_file(getPath(qp_bin.name, directory = "SPARSE"))
if qp_bin.complexity() > max_qubits :
print(multiple)
break
multiple = multiple + 1
# -
qp_bin.qubo.to_docplex().prettyprint()
| comparison/Qiskit/LinearProgramming/QAOA/RandomQP/Test_Data_Creation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import sys
import os
sys.path.append(os.path.join('D:\\', 'Documents', 'Programs', 'DisperScripts'))
# +
from experimentor.models.devices.cameras.basler.basler import BaslerCamera
import zmq
from multiprocessing import Event
from threading import Thread
import time
import numpy as np
from calibration.models.experiment import CalibrationSetup
from experimentor import Q_
from pypylon import pylon, _genicam
# -
stop_event = Event()
cam = BaslerCamera('ac')
cam.initialize()
cam.exposure = Q_('50ms')
def print_number_frames(stop_event, url):
topic = 'new_image'
frame_no = 0
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect(url)
socket.setsockopt(zmq.SUBSCRIBE, topic.encode('utf-8'))
img_old = None
while not stop_event.is_set():
event = socket.poll(0)
if not event:
time.sleep(.005)
continue
topic = socket.recv_string()
metadata = socket.recv_json(flags=0)
msg = socket.recv(flags=0, copy=True, track=False)
buf = memoryview(msg)
if img_old is None:
img_old = np.zeros(metadata['shape'])
img = np.frombuffer(buf, dtype=metadata['dtype'])
img = img.reshape(metadata['shape']).copy()
if np.all(img == img_old):
break
imd_old = img.copy()
frame_no+=1
if frame_no%100 == 0:
print(f'Acquired {frame_no} frames')
print(f'Acquired {frame_no} before getting repeated frames')
url = cam.get_publisher_url()
port = cam.get_publisher_port()
print(f'{url}:{port}')
thread = Thread(target=print_number_frames, args=(stop_event, f'{url}:{port}'))
thread.start()
cam.start_free_run()
cam.continuous_reads()
cam.stop_continuous_reads()
stop_event.set()
stop_event.clear()
cam.finalize()
import yaml
experiment = CalibrationSetup()
experiment.load_configuration('../dispertech.yml', yaml.UnsafeLoader)
future = experiment.initialize()
while future.running():
continue
experiment.get_latest_image('microscope_camera')
experiment.start_saving_images()
experiment.stop_saving_images()
experiment.finalize()
| notebooks/test_basler.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Exercise 3
# -------
# Create a function that:
# 1. Takes a variable number of string arguments
# 2. Concatenates all the string arguments by a comma (,)
# 3. Returns the concatenated string in uppercase letters
# +
def string_operator(*args):
concat = ","
result = concat.join(args).upper()
return result
string_operator("LiNkIt", "9", "3554PV")
# -
| Day1/day1-morning-exercises/exercise3_with_answer.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# Caesar Cipher
MAX_KEY_SIZE = 26
# -
def get_mode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
# +
def get_message():
print('Enter your message:')
return input()
def get_key():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
# -
def get_translated_message(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = get_mode()
message = get_message()
key = get_key()
print('Your translated text is:')
print(get_translated_message(mode, message, key))
| caesar_cipher.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import os, sys
sys.path.append(os.path.abspath('../../main/python'))
import thalesians.tsa.neural.tfwrapper as tfwrapper
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.random.normal(size=(100, 5))
y = np.empty((np.shape(x)[0], 3))
y[:,0] = np.exp(x[:,0])
y[:,1] = np.cos(x[:,1]) + np.sin(x[:,2])
y[:,2] = x[:,0] + x[:,1] + x[:,2] + x[:,3] + x[:,4]
n, p = np.shape(x)
q = np.shape(y)[1]
n_train = n // 2
n_test = n - n_train
x_train = x[:n_train,:]
y_train = y[:n_train,:]
x_test = x[n_train:,:]
y_test = y[n_train:,:]
model = tfwrapper.Sequential()
model.add(tfwrapper.Dense(100, input_dim=p, activation='tanh'))
model.add(tfwrapper.Dense(100, activation='tanh'))
model.add(tfwrapper.Dense(q, activation='linear'))
model.compile(loss='mean_squared_error', optimizer='sgd', lr=0.001)
y_train_pred = model.fit(x_train, y_train, epochs=10000)
plt.plot(y_train[:,0], y_train_pred[:,0], 'x');
plt.plot(y_train[:,1], y_train_pred[:,1], 'x');
plt.plot(y_train[:,2], y_train_pred[:,2], 'x');
y_test_pred = model.predict(x_test)
plt.plot(y_test[:,0], y_test_pred[:,0], 'x');
plt.plot(y_test[:,1], y_test_pred[:,1], 'x');
plt.plot(y_test[:,2], y_test_pred[:,2], 'x');
| src/jupyter/python/tfwrapper.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/JaninaMattes/detectron2_dla/blob/master/notebooks/Detectron2_FineTuning_PubLayNet_PT1.9_dataset2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="QHnVupBBn9eR"
# # Detectron2 Beginner's Tutorial
#
# <img src="https://dl.fbaipublicfiles.com/detectron2/Detectron2-Logo-Horz.png" width="500">
# + [markdown] id="vM54r6jlKTII"
# # Install detectron2
# + colab={"base_uri": "https://localhost:8080/"} id="4JxxLubvU4VA" outputId="492d1d9f-a402-4c3c-d9bd-f15882279ba1"
from google.colab import drive
drive.mount('/content/gdrive', force_remount=True)
# !nvidia-smi
# !nvcc -V
# + [markdown] id="AZfXeCpjihzc"
# ### Update and purge Nvidia Driver
# #### https://medium.com/analytics-vidhya/install-cuda-11-2-cudnn-8-1-0-and-python-3-9-on-rtx3090-for-deep-learning-fcf96c95f7a1
# + id="PH78B0LUU9cl" colab={"base_uri": "https://localhost:8080/"} outputId="3f45fa97-26c5-4d4c-e928-e208c729b0d0"
# !python -c "import torch; print(torch.__version__); import torchvision; print(torchvision.__version__)"
# + id="9_FzH13EjseR" colab={"base_uri": "https://localhost:8080/"} outputId="9f9609a2-2419-4979-8608-ee15e9b692d4"
# install dependencies:
# !pip install pyyaml==5.1
# !pip install cmake
# !pip install gdown
# !pip install mlflow
import torch, torchvision
print(torch.__version__, torch.cuda.is_available())
# !gcc --version
# opencv is pre-installed on colab
# + id="b-i4hmGYk1dL" colab={"base_uri": "https://localhost:8080/"} outputId="094a502a-b51d-41a6-f68f-d21e7fccb727"
# install detectron2: (Colab has CUDA 10.2 + torch 1.9)
# See https://detectron2.readthedocs.io/tutorials/install.html for instructions
# !git clone https://github.com/facebookresearch/detectron2.git
# !python -m pip install -e detectron2
# + id="XeJp986zrkVS" colab={"base_uri": "https://localhost:8080/"} outputId="66777451-0282-4622-9ddc-dd066597c2f0"
# !python -c 'from torch.utils.collect_env import main; main()'
# + [markdown] id="OrHf7T9_80YE"
# #### Clone Detectron2_DLA Repository
# + id="IZeLzshI40Le" colab={"base_uri": "https://localhost:8080/"} outputId="3f8e1bb4-0b49-42d6-8557-63453c88c051"
# !git clone https://github.com/JaninaMattes/detectron2_dla.git
# %cd detectron2_dla
# !ls -la
# + id="6D1SkayvrNmM" colab={"base_uri": "https://localhost:8080/"} outputId="49020532-6860-45f7-8774-12117bf274ce"
# download pre-trained model
# !mkdir -p ./pretrained_models
# !wget https://www.dropbox.com/sh/wgt9skz67usliei/AADGw0h1y7K5vO0akulyXm-qa/model_final.pth -P ./pretrained_models
# + id="pbjmgpTa9KEp" colab={"base_uri": "https://localhost:8080/"} outputId="19c47987-915a-49c5-8947-75a90347837a"
# !ls ./pretrained_models
# + id="Wrm0xaEDnat9" colab={"base_uri": "https://localhost:8080/"} outputId="4c72def0-0b03-4efb-aa36-16bf9acd555d"
# download, decompress the data
# !gdown https://drive.google.com/uc?id=1BxeihblmkRLRV1lr9Y2ii55cYrLO3C2W
# !unzip siemens.zip -d ./datasets
# !rm -r siemens.zip
# + id="nG--Dlyy9O30" colab={"base_uri": "https://localhost:8080/"} outputId="95847963-e4d7-4778-885c-3a3932606c5a"
# !ls ./datasets/siemens
# + id="-YcPNGjjc2Yw" colab={"base_uri": "https://localhost:8080/"} outputId="a797a925-31c7-48b6-daf2-1afbac89417b"
# !python finetune_net_dla.py
# + [markdown] id="y5Rr7gqlwdMi"
# ### Tensorboard
# + id="PxsCvb59wcVa" colab={"base_uri": "https://localhost:8080/", "height": 839} outputId="9b8e33b2-1053-4f75-9b55-cbd9831de241"
# Look at training curves in tensorboard:
# %load_ext tensorboard
# %tensorboard --logdir output
# + id="jUcW8n9dHSFV" colab={"base_uri": "https://localhost:8080/", "height": 193} outputId="189063b4-c89b-4c90-8da1-933b85516dce"
# !zip -r output.zip ./output/*
# !cp ./output/* '/content/gdrive/My Drive/downloads/model_dataset2'
# !ls -lt '/content/gdrive/My Drive/downloads/model_dataset2'
from google.colab import files
files.download("output.zip")
# + id="_sey9qFrxmr2"
while True: pass
| notebooks/Detectron2_FineTuning_PubLayNet_PT1.9_dataset2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <pre style='font-size : 25px; text-align : center '><b>ASSIGNMENT 3</b></pre>
# <pre style='font-size : 20px;'><b>INSPECTING AND SOLVING THE PROBLEM OF OVERFITTING</b></pre>
# <pre style='font-size : 15px'>This time we will try to solve the problem of overfitting
# which occurred during the training of our classifiers on boston housing data.
# In order to solve it we will use an l1 and l2 regularization.
# Moreover, we will scale our features in order to squash them into the [0,1] range.
# We then will compare the obtained results to the previous ones.</pre>
#
# <i>Note : that's a test version of a notebook</i>
# <pre style='font-size : 20px'><b>PART 1</b></pre>
# <pre style='font-size : 18px'><b>Linear regression with regularization</b></pre>
# <pre style='font-size : 15px;'>Firstly let's import necessary packages. </pre>
#Ridge - regression with l2 regularization, Lasso - regression with l1 regularization
from sklearn.linear_model import Ridge, Lasso
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# <pre style='font-size : 15px'>Now it's time to load our dataset</pre>
def load_boston_df():
from sklearn import datasets
boston_data = datasets.load_boston()
columns_to_use = ['data','target','feature_names']
boston_data = dict([(i,boston_data[i]) for i in columns_to_use])
df = pd.DataFrame(columns=boston_data['feature_names'], data=boston_data['data'])
df['target'] = boston_data['target']
return df
df = load_boston_df()
df.head()
# <pre style='font-size : 15px'>The next step is to process our features and split our data.</pre>
train_columns = list(df.columns)
target_column = train_columns.pop(-1)
seed=5
train_set, test_set = train_test_split(df,test_size=0.20, random_state=seed)
X_train, y_train, X_test, y_test = train_set[train_columns], train_set[target_column],\
test_set[train_columns], test_set[target_column]
# <pre style='font-size : 15px'>To scale our data we will use MinMaxScaler instance.
# We firstly fit it on train features and then scale both train and test ones. </pre>
scaler = MinMaxScaler().fit(X_train)
X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)
# <pre style='font-size :15px'>Firstly let's try out l1 regularization using Lasso regression. One thing we need to specify when using regularization is a value of alpha parameter, the intuition behind which the following : one alpha is large - the bigger regularization effect is and vice versa.</pre>
#alpha - regularization strength, feel free to play around with this parameter and see the results
alpha = 0.001
clf = Lasso(alpha=alpha,random_state=seed)
clf.fit(X_train,y_train)
y_predicted_train = clf.predict(X_train)
print("Mean squared error on train data : {0}".format(mean_squared_error(y_predicted_train,y_train)))
y_predicted_test = clf.predict(X_test)
print("Mean squared error on test data : {0}".format(mean_squared_error(y_predicted_test,y_test)))
# <pre style='font-size :15px'>Trying Lasso regression we see small changes in mse score for both test and train set, let's give l2 regularization a try (Ridge)<pre>
#alpha - regularization strength, feel free to play around with this parameter and see the results
alpha = 1
clf = Ridge(alpha=alpha,random_state=seed)
clf.fit(X_train,y_train)
y_predicted_train = clf.predict(X_train)
print("Mean squared error on train data : {0}".format(mean_squared_error(y_predicted_train,y_train)))
y_predicted_test = clf.predict(X_test)
print("Mean squared error on test data : {0}".format(mean_squared_error(y_predicted_test,y_test)))
# <pre style='font-size : 15px'>We also see no huge changes using regulariztion on linear regression, let's try it with polynomial regression.</pre>
# <pre style='font-size : 20px'><b>PART 2</b></pre>
# <pre style='font-size : 18px'><b>Polynomial regression with regularization</b></pre>
#
from sklearn.preprocessing import PolynomialFeatures
# <pre style='font-size : 15px'>As always we will firstly create our polynomial features.</pre>
#C- degree of polynom. Feel free to play around with number and see the perfomance of the model depending on it
C =2
poly = PolynomialFeatures(C)
poly_features_train = poly.fit_transform(X_train)
poly_features_test = poly.transform(X_test)
# <pre style='font-size :15px'>We will start with l1 (Lasso) regularization.</pre>
#alpha - regularization strength, feel free to play around with this parameter and see the results
#max_iter - number of iterations of the algorithm,feel free to play around with this parameter and see the results
alpha = 0.001
max_iter = 100000
clf = Lasso(alpha=alpha,max_iter=max_iter,random_state=seed)
clf.fit(poly_features_train,y_train)
y_predicted_train = clf.predict(poly_features_train)
print("Mean squared error on train data : {0}".format(mean_squared_error(y_predicted_train,y_train)))
y_predicted_test = clf.predict(poly_features_test)
print("Mean squared error on test data : {0}".format(mean_squared_error(y_predicted_test,y_test)))
# <pre style ='font-size:15px'>Finally the regularization for polynomial regresion worked and there is some intuition why it didn't work so well for linear regression.
# What really regularization does is making our decision boudaries simpler,
# to ecnourage the generalization to unseen data.
# And the decision boundary of linear regression is just a line,
# thus there is no way regularization can make it even simpler.
# To understand it beter, let's plot our predictions versus real target values on test set using the l1 regularization. The function <b>plot_boundaries</b> manages the highlited option
# (for convinience we will use RM feature as y). </pre>
import numpy as np
sns.set()
def plot_boundaries(alpha=0.1,C=2, max_iter=100000):
clf = Lasso(alpha=alpha,max_iter=max_iter)
poly = PolynomialFeatures(C)
poly_features_train = poly.fit_transform(X_train)
poly_features_test = poly.transform(X_test)
clf.fit(poly_features_train,y_train)
y_predicted_test = clf.predict(poly_features_test)
mae = mean_squared_error(y_predicted_test,y_test)
plt.figure(figsize=(15,12))
plt.title('Predictions on test data with alpha of {0} ; test mse score of {1} ; polynomial degree of {2}'.format(alpha,mae, C))
plt.scatter(y_test,test_set['RM'])
plt.scatter(y_predicted_test, test_set['RM'],color='g', marker='^')
plt.ylabel('Number of rooms')
plt.xlabel('Price')
plt.legend(['Real value','Predicted value'])
plot_boundaries(alpha=0.001,C=3)
plot_boundaries(alpha=1, C=3)
plot_boundaries(alpha=10, C=3)
# <pre style ='font-size:15px'>Note how the decision boundary changes with the amount of regularization.
# Increasing value of alpha makes our decision boundary more simpler.
# The effect of regularization is entirely empphisized on the third chart, where the alpha's value of
# 10 results in to the linear decision boundary. You should also pay attention to the fact that
# a lot of regularization is bad, because it could make classifier to simple, as we see on
# the third chart, where the mse score on test data is 78.</pre>
# <pre style='font-size :15px'>Now let's try to use l2 regularization (Ridge) and see the results!</pre>
#C- degree of polynom. Feel free to play around with number and see the perfomance of the model depending on it
C = 3
poly = PolynomialFeatures(C)
poly_features_train = poly.fit_transform(X_train)
poly_features_test = poly.transform(X_test)
#alpha - regularization strength, feel free to play around with this parameter and see the results
#max_iter - number of iterations of the algorithm,feel free to play around with this parameter and see the results
alpha = 0.1
max_iter = 1000000
clf = Ridge(alpha=alpha,max_iter=max_iter,random_state=seed)
clf.fit(poly_features_train,y_train)
y_predicted_train = clf.predict(poly_features_train)
print("Mean squared error on train data : {0}".format(mean_squared_error(y_predicted_train,y_train)))
y_predicted_test = clf.predict(poly_features_test)
print("Mean squared error on test data : {0}".format(mean_squared_error(y_predicted_test,y_test)))
# <pre style='font-size :15px'>Using Ridge regression with a polynomial degree of 3 we got 7 mse score on test data, thus l2 regularization also worked well. Let's see the comparison of Lasso and Ridge regression versus real target value using <b>plot_bestresults_comparison</b>. </pre>
def plot_bestresults_comparison():
clf = Ridge(alpha=0.1,max_iter=1000000,random_state=seed)
C = 3
poly = PolynomialFeatures(C)
poly_features_train = poly.fit_transform(X_train)
poly_features_test = poly.transform(X_test)
clf.fit(poly_features_train,y_train)
y_predicted_ridge = clf.predict(poly_features_test)
clf = Lasso(alpha=0.001,max_iter=1000000)
C = 3
poly = PolynomialFeatures(C)
poly_features_train = poly.fit_transform(X_train)
poly_features_test = poly.transform(X_test)
clf.fit(poly_features_train,y_train)
y_predicted_lasso = clf.predict(poly_features_test)
plt.figure(figsize=(15,12))
plt.title('Comparison of Lasso and Ridge regression versus real target value')
plt.scatter(y_test,test_set['RM'])
plt.scatter(y_predicted_lasso, test_set['RM'],color='g', marker='^')
plt.scatter(y_predicted_ridge,test_set['RM'],color='r',marker='x')
plt.ylabel('Number of rooms')
plt.xlabel('Price')
plt.legend(['Real valalue','Predicted value with Lasso (l1)','Predicted value with Ridge (l2)'])
plot_bestresults_comparison()
# <pre style='font-size : 15px'>Finally, we can see the real difference between predicted values and real ones, by printing them side by side using <b>show_dif</b> function. In our case we will use the prices predicted by polynomial regression with l1 regularization (Lasso), as it showed the best results on test data.</pre>
def show_dif():
clf = Ridge(alpha=0.1,max_iter=1000000)
C = 3
poly = PolynomialFeatures(C)
poly_features_train = poly.fit_transform(X_train)
poly_features_test = poly.transform(X_test)
clf.fit(poly_features_train,y_train)
y_predicted_lasso = clf.predict(poly_features_test)
df = pd.DataFrame({'Predicted price' : y_predicted_lasso, 'Real price' : y_test.values })
pd.set_option('display.max_rows', df.shape[0]+1)
display(df)
show_dif()
# <pre style='font-size :15px'>Today, we obeserved the result of applying regularization on both linear
# and polynomial regression.
# You understood that regularization should be applied in an adequate manner,
# as it can make our algorithm to simple and lead to the problem of underfitting.
# In the next lesson we will consider using SVM algorithm for solving this task.</pre>
| assignments/machine_learning/assignment_3_regression/.ipynb_checkpoints/assignment_3-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.8.5 64-bit (conda)
# name: python385jvsc74a57bd00238d5a7b1e34fe15d1565e2b0c665b26815cf8d2d83ee8f4f38fe51f22dbfbc
# ---
# ## The Data ##
# +
import pandas as pd
data_filepath = 'abcnews-date-text-2003.csv'
data = pd.read_csv(data_filepath, error_bad_lines=False);
data_text = data[['headline_text']]
data_text['index'] = data_text.index
documents = data_text
print(len(documents))
print(documents[:5])
# -
#
| Homework 11/test_abcnews/abcnews_lda.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import pandas as pd
import numpy as np
import math
import pickle
from datetime import datetime
from scipy import stats
import scipy.io
from scipy.spatial.distance import pdist
from scipy.linalg import cholesky
from scipy.io import loadmat
import matlab.engine as engi
import matlab as mat
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.metrics import classification_report,roc_auc_score,recall_score,precision_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.decomposition import PCA
from pyearth import Earth
from src import SMOTE
from src import CFS
from src import metrices_V2 as metrices
import platform
from os import listdir
from os.path import isfile, join
from glob import glob
from pathlib import Path
import sys
import os
import copy
import traceback
from pathlib import Path
import matplotlib.pyplot as plt
# +
def load_data(project):
understand_path = 'data/understand_files_all/' + project + '_understand.csv'
commit_guru_path = 'data/commit_guru/' + project + '.csv'
release_df = pd.read_pickle('data/release/' + project + '_release.pkl')
release_df = release_df.sort_values('created_at',ascending=False)
release_df = release_df.reset_index(drop=True)
# df_test_releases = release_df[0:5]
# df_test_releases.reset_index(inplace = True, drop=True)
# df_train_releases = release_df[5:]
# df_train_releases.reset_index(inplace = True, drop=True)
# last_train_release = datetime.strptime(df_train_releases.loc[0,'created_at'], '%Y-%m-%d').date()
understand_df = pd.read_csv(understand_path)
understand_df = understand_df.dropna(axis = 1,how='all')
cols_list = understand_df.columns.values.tolist()
for item in ['Kind', 'Name','commit_hash', 'Bugs']:
if item in cols_list:
cols_list.remove(item)
cols_list.insert(0,item)
understand_df = understand_df[cols_list]
commit_guru_df = pd.read_csv(commit_guru_path)
cols = understand_df.columns.tolist()
commit_guru_df['created_at'] = pd.to_datetime(commit_guru_df.author_date_unix_timestamp,unit='s')
commit_guru_df = commit_guru_df.drop(labels = ['parent_hashes','author_name','author_name',
'author_email','fileschanged','author_date',
'author_date_unix_timestamp', 'commit_message',
'classification', 'fix', 'contains_bug','fixes',],axis=1)
understand_df = understand_df.drop_duplicates(cols[4:len(cols)])
df = understand_df.merge(commit_guru_df,on='commit_hash')
cols = df.columns.tolist()
cols = cols[1:] + [cols[0]]
df = df[cols]
for item in ['Kind', 'Name','commit_hash']:
if item in cols:
df = df.drop(labels = [item],axis=1)
df.dropna(inplace=True)
df.reset_index(drop=True, inplace=True)
df.to_csv('data/converted/'+ project + '_understand.csv',index=False)
y = df.Bugs
df = df.drop('Bugs',axis = 1)
cols = df.columns
created_at = df.created_at
df = df.drop('created_at',axis = 1)
scaler = MinMaxScaler()
df = scaler.fit_transform(df)
df = pd.DataFrame(X,columns = cols[:-1])
df['created_at'] = created_at
df['Bugs'] = y
# df_last_commit_date = df.loc[df.shape[0],'created_at']
df_last_commit_date = df.loc[df.shape[0]-1,'created_at']
last_train_date = None
count = 0
for i in range(release_df.shape[0]):
release_date = datetime.strptime(release_df.loc[i,'created_at'], '%Y-%m-%d')
if release_date <= df_last_commit_date:
count += 1
if count == 5:
last_train_date = release_date
break
# print(last_train_date)
# print(df)
if last_train_date == None:
return df,df,0
df['created_at'] = pd.to_datetime(df.created_at,unit='s')
train_df = df[df.created_at < last_train_date]
test_df = df[df.created_at >= last_train_date]
train_df = train_df.drop('created_at',axis = 1)
test_df = test_df.drop('created_at',axis = 1)
if train_df.shape[0] == 0:
return df,df,0
if test_df.shape[0] == 0:
return df,df,0
return train_df,test_df,1
def apply_smote(df):
cols = df.columns
smt = SMOTE.smote(df)
df = smt.run()
df.columns = cols
return df
def apply_cfs(df):
y = df.Bugs.values
X = df.drop(labels = ['Bugs'],axis = 1)
X = X.values
selected_cols = CFS.cfs(X,y)
cols = df.columns[[selected_cols]].tolist()
cols.append('Bugs')
return df[cols],cols
# +
def run_self(project):
train_df, test_df,complete = load_data(project)
if complete == 0:
return None,None,None,None,None,None,None,None,None
loc = test_df.CountLineCode
df_smote = train_df
df_smote = apply_smote(df_smote)
# df_smote,cols = apply_cfs(df_smote)
y_train = df_smote.Bugs
X_train = df_smote.drop('Bugs',axis = 1)
clf = RandomForestClassifier()
clf.fit(X_train,y_train)
importance = 0
# test_df = test_df[cols]
y_test = test_df.Bugs
X_test = test_df.drop('Bugs',axis = 1)
predicted = clf.predict(X_test)
abcd = metrices.measures(y_test,predicted,loc)
pf = abcd.get_pf()
recall = abcd.calculate_recall()
precision = abcd.calculate_precision()
f1 = abcd.calculate_f1_score()
g_score = abcd.get_g_score()
pci_20 = abcd.get_pci_20()
ifa = abcd.get_ifa()
try:
auc = roc_auc_score(y_test, predicted)
except:
auc = 0
print(classification_report(y_test, predicted))
return recall,precision,pf,f1,g_score,auc,pci_20,ifa,importance
# -
proj_df = pd.read_csv('projects.csv')
projects = proj_df.repo_name.tolist()
count = 0
precision_list = {}
recall_list = {}
pf_list = {}
f1_list = {}
g_list = {}
auc_list = {}
pci_20_list = {}
ifa_list = {}
featue_importance = {}
for project in projects:
try:
if project == '.DS_Store':
continue
# if project != 'redis-manager':
# continue
if df.shape[0] > 10:
recall,precision,pf,f1,g_score,auc,pci_20,ifa,importance = run_self(project)
if recall == None:
continue
recall_list[project] = recall
precision_list[project] = precision
pf_list[project] = pf
f1_list[project] = f1
g_list[project] = g_score
auc_list[project] = auc
pci_20_list[project] = pci_20
ifa_list[project] = ifa
featue_importance[project] = importance
except Exception as e:
print(project,e)
continue
for project in projects:
if project == '.DS_Store':
continue
if project != 'maven-plugins':
continue
run_self(project)
np.nanmedian(list(precision_list.values())),np.nanmedian(list(recall_list.values())),np.nanmedian(list(pf_list.values()))
| Is metrics stable across release_v1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <h1> Libraries Needed for Script</h1>
# +
import numpy as np #Library containing advanced mathematical functions and other.
import pandas as pd #Library containing powerful datastructure called a DataFrame
# -
# <h1> Data Import<h1>
#
df_rawdata_testdataset = pd.read_csv('https://github.com/JonathanAspeling/zindi_sendychallange/blob/master/csv/Test.csv',encoding = 'ASCII')
print('Success importing')
df_rawdata_trainingdataset = pd.read_csv('https://github.com/JonathanAspeling/zindi_sendychallange/blob/master/csv/Train.csv',encoding = 'ASCII')
df_rawdata_driverinfo = pd.read_csv('https://github.com/JonathanAspeling/zindi_sendychallange/blob/master/csv/Riders.csv',encoding = 'ASCII')
| HackathonScript_Sendy_Zindi.ipynb |
# # Big data? ๐ค Datasets to the rescue!
# Install the Transformers and Datasets libraries to run this notebook.
# !pip install datasets transformers[sentencepiece]
# !pip install zstandard
# +
from datasets import load_dataset
# This takes a few minutes to run, so go grab a tea or coffee while you wait :)
data_files = "https://the-eye.eu/public/AI/pile_preliminary_components/PUBMED_title_abstracts_2019_baseline.jsonl.zst"
pubmed_dataset = load_dataset("json", data_files=data_files, split="train")
pubmed_dataset
# -
pubmed_dataset[0]
# !pip install psutil
# +
import psutil
# Process.memory_info is expressed in bytes, so convert to megabytes
print(f"RAM used: {psutil.Process().memory_info().rss / (1024 * 1024):.2f} MB")
# -
print(f"Number of files in dataset : {pubmed_dataset.dataset_size}")
size_gb = pubmed_dataset.dataset_size / (1024 ** 3)
print(f"Dataset size (cache file) : {size_gb:.2f} GB")
# +
import timeit
code_snippet = """batch_size = 1000
for idx in range(0, len(pubmed_dataset), batch_size):
_ = pubmed_dataset[idx:idx + batch_size]
"""
time = timeit.timeit(stmt=code_snippet, number=1, globals=globals())
print(
f"Iterated over {len(pubmed_dataset)} examples (about {size_gb:.1f} GB) in "
f"{time:.1f}s, i.e. {size_gb/time:.3f} GB/s"
)
# -
pubmed_dataset_streamed = load_dataset(
"json", data_files=data_files, split="train", streaming=True
)
next(iter(pubmed_dataset_streamed))
# +
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
tokenized_dataset = pubmed_dataset_streamed.map(lambda x: tokenizer(x["text"]))
next(iter(tokenized_dataset))
# -
shuffled_dataset = pubmed_dataset_streamed.shuffle(buffer_size=10_000, seed=42)
next(iter(shuffled_dataset))
dataset_head = pubmed_dataset_streamed.take(5)
list(dataset_head)
# Skip the first 1,000 examples and include the rest in the training set
train_dataset = shuffled_dataset.skip(1000)
# Take the first 1,000 examples for the validation set
validation_dataset = shuffled_dataset.take(1000)
law_dataset_streamed = load_dataset(
"json",
data_files="https://the-eye.eu/public/AI/pile_preliminary_components/FreeLaw_Opinions.jsonl.zst",
split="train",
streaming=True,
)
next(iter(law_dataset_streamed))
# +
from itertools import islice
from datasets import interleave_datasets
combined_dataset = interleave_datasets([pubmed_dataset_streamed, law_dataset_streamed])
list(islice(combined_dataset, 2))
# -
base_url = "https://the-eye.eu/public/AI/pile/"
data_files = {
"train": [base_url + "train/" + f"{idx:02d}.jsonl.zst" for idx in range(30)],
"validation": base_url + "val.jsonl.zst",
"test": base_url + "test.jsonl.zst",
}
pile_dataset = load_dataset("json", data_files=data_files, streaming=True)
next(iter(pile_dataset["train"]))
| course/chapter5/section4.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
#default_exp tensor
# -
#exports
from kesscore.imports import *
from kesscore.functional import *
from kesscore.tests import *
from functools import wraps
#exports
@patch(as_prop=True)
def lshape(self:Tensor): 'Like Tensor.shape but return a list'; return [*self.shape]
test_eq_type(torch.zeros(10,10).lshape, [10,10])
#exports
@patch
def shape_is(self:Tensor,*size): return list(self.lshape)==list(size)
assert torch.zeros(10,10).shape_is(10,10)
assert not torch.zeros(10,10).shape_is(10,5)
assert not torch.zeros(10,10).shape_is(10,10,10)
@patch
def assert_shape(self:Tensor,*size):
'Assert the tensor shape and produce a meaningfull assertion message in case it fails'
assert self.shape_is(*size), f'Expected tensor of shape {(*size,)} but got tensor of shape {(*self.shape,)}'
return self
test_eq(torch.zeros(10,20).assert_shape(10,20), torch.zeros(10,20))
test_fail(lambda: torch.zeros(10,20).assert_shape(10,30),
contains='Expected tensor of shape (10, 30) but got tensor of shape (10, 20)')
#exports
def interleaved(*args, dim):
'''Given `args`, all with same shapes, return them concatenated on `dim`, but interleaved'''
assert len(args) != 0
if len(args) == 1: return args[0]
test_all(*args, checker=isinstance(Tensor))
test_all_eq(*args, map=Self.size())
shape = args[0].lshape
shape[dim] *= len(args)
args = mapped(Self.unsqueeze(dim+1), args)
x = torch.cat(tuple(args), dim=dim+1)
return x.view(*shape)
test_eq_type(interleaved(*L([[1, 2]],[[3, 4]],[[5, 6]]).tensored(), dim=1), torch.tensor([[1,3,5,2,4,6]]))
test_eq_type(interleaved(*L([[1, 2]],[[3, 4]],[[5, 6]]).tensored(), dim=0), torch.tensor([[1,2],[3,4],[5,6]]))
from nbdev.sync import notebook2script;notebook2script()
| nbs/02_tensor.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## The SEIR model
#
# The SEIR model of epidemiology partitions the population into three compartments: susceptibles, S, who can catch the disease; exposed, E, that has caught the infection but is not infectious; infectives, I, who have already caught the disease and infect susceptibles; and removed individuals, R. Since the disease is assumed not to be fatal, the sum $N=S+I+R$ remains constant. The rate at which the susceptibles get infected is
# $$
# \lambda(t) = \frac{\beta I}{N}
# $$
# where the parameter $\beta$ is the probability of infection on contact. The infected individuals remove from the disease at a rate $\gamma$. Then, the ordinary differential equations of the SIR model are
#
# \begin{align}
# \dot S &= -\lambda(t)S \\
# \dot E &= \lambda(t)S - \gamma_E E \\
# \dot I &= \gamma_E E - \gamma I \\
# \dot R &= \gamma I
# \end{align}
#
# Here $ 1/\zeta$ can be interpreted as the average incubation period. This example integrates the above equations to obtain what is called the **epidemic curve**: a plot of the number of susceptibles and infectives as a function of time.
# %matplotlib inline
import numpy as np
import pyross
import matplotlib.pyplot as plt
#from matplotlib import rc; rc('text', usetex=True)
# +
M = 1 # the SIR model has no age structure
Ni = 1000*np.ones(M) # so there is only one age group
N = np.sum(Ni) # and the total population is the size of this age group
alpha = 0 # fraction of asymptomatic infectives
beta = 0.2 # infection rate
gIa = 0.1 # removal rate of asymptomatic infectives
gIs = 0.1 # removal rate of symptomatic infectives
gE = 0.04 # removal rate of E
fsa = 1 # the self-isolation parameter
E0 = np.array([0])
Ia0 = np.array([0]) # the SIR model has only one kind of infective
Is0 = np.array([1]) # we take these to be symptomatic
R0 = np.array([0]) # and assume there are no removed individuals initially
S0 = N-(Ia0+Is0+R0+E0) # so that the initial susceptibles are obtained from S + Ia + Is + R = N
# there is no contact structure
def contactMatrix(t):
return np.identity(M)
# duration of simulation and data file
Tf = 500; Nt=160;
# instantiate model
parameters = {'alpha':alpha, 'beta':beta, 'gIa':gIa, 'gIs':gIs, 'gE':gE, 'fsa':fsa}
model = pyross.deterministic.SEIR(parameters, M, Ni)
# simulate model
data=model.simulate(S0, E0, Ia0, Is0, contactMatrix, Tf, Nt)
# +
# plot the data and obtain the epidemic curve
S = data['X'][:,0].flatten()
E = data['X'][:,1].flatten()
Ia = data['X'][:,2].flatten()
Is = data['X'][:,3].flatten()
t = data['t']
fig = plt.figure(num=None, figsize=(10, 8), dpi=80, facecolor='w', edgecolor='k')
plt.rcParams.update({'font.size': 22})
plt.fill_between(t, 0, S/N, color="#348ABD", alpha=0.3)
plt.plot(t, S/N, '-', color="#348ABD", label='$S$', lw=4)
plt.plot(t, E/N, '-', color="green", label='$E$', lw=4)
plt.fill_between(t, 0, E/N, color='green', alpha=0.3)
plt.fill_between(t, 0, Is/N, color='#A60628', alpha=0.3)
plt.plot(t, Is/N, '-', color='#A60628', label='$I$', lw=4)
R=N-S-Ia-Is; plt.fill_between(t, 0, R/N, color="dimgrey", alpha=0.3)
plt.plot(t, R/N, '-', color="dimgrey", label='$R$', lw=4)
plt.legend(fontsize=26); plt.grid()
plt.autoscale(enable=True, axis='x', tight=True)
| examples/deterministic/ex05-SEIR.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:utm] *
# language: python
# name: conda-env-utm-py
# ---
# +
# LongLat.to_pickle('LongLat.pkl')
# -
import utm
import pandas as pd
LongLat = pd.read_pickle('LongLat.pkl')
LongLat.head()
utm.from_latlon(51.2, 7.5)
list(LongLat.LaLoPoint[0])
utm.from_latlon(LongLat.latitude[0], LongLat.longitude[0])
def rule(row):
x, y, val, letter = utm.from_latlon(row["latitude"], row["longitude"])
return pd.Series({"x": x, "y": y, "val": val, "letter": letter})
LongLatcd = LongLat[0:100]
LongLatcd = LongLatcd.merge(LongLatcd.apply(rule, axis=1), left_index= True, right_index= True)
LongLatcd.head()
LongLatcd.to_pickle('LongLat_UTM.pkl')
utm.to_latlon(913175.109008804, 120121.88125434518, '18')
| Presented Code/Spatial Server/Convert Long Lat to UTM.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
from matplotlib import pyplot as plt
train_data = np.load('cifar102_train.npz')
test_data = np.load('cifar102_test.npz')
plt.figure(figsize=[2,2])
ind = 999
plt.imshow(train_data['images'][ind])
plt.title(f"label={train_data['label_names'][train_data['labels'][ind]]}\n keyword={train_data['keywords'][ind]}\n TI index={train_data['ti_indices'][ind]}")
plt.axis('off')
plt.show()
| experiments/priv_fair/data/cifar-10.2-master/CIFAR-10.2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + id="InJ338DkfRm2" colab_type="code" outputId="d460d72a-31ee-42f5-d6ec-34c13282daf0" colab={"base_uri": "https://localhost:8080/", "height": 122}
import tensorflow as tf
from tensorflow.python.framework import ops
import matplotlib.pyplot as plt
from google.colab import drive
drive.mount('/content/drive/')
# + id="fRmHiut3fh8V" colab_type="code" colab={}
def create_placeholder(n_h,n_w,n_y):
X=tf.placeholder(tf.float32,shape=(None,n_h,n_w,1),name='X')
Y=tf.placeholder(tf.float32,shape=(None,n_y),name='Y')
return X,Y
# + id="xGql8LZEhWcn" colab_type="code" colab={}
os.chdir('drive/My Drive')
# + id="uthy0rJ0k1Ay" colab_type="code" outputId="31f3c61a-eb51-40b6-a189-29e52a67e018" colab={"base_uri": "https://localhost:8080/", "height": 34}
import os
cwd=os.getcwd()
print(cwd)
# + id="G-go6NHXtBf4" colab_type="code" outputId="a41cd820-b1dc-4eb3-ddbc-295b9cd725b9" colab={"base_uri": "https://localhost:8080/", "height": 34}
# !ls
# + id="hRH0G769qry2" colab_type="code" colab={}
def initialize_parameters():
W1=tf.get_variable("W1",[4,4,1,16],initializer=tf.contrib.layers.xavier_initializer())
W2=tf.get_variable("W2",[2,2,16,32],initializer=tf.contrib.layers.xavier_initializer())
parameters={"W1":W1,
"W2":W2}
return parameters
# + id="npnp1JHJl68S" colab_type="code" colab={}
def forward_propagate(X,parameters):
W1=parameters['W1']
W2=parameters['W2'] #retriving the parametrs
Z1=tf.nn.conv2d(X,W1,strides=[1,1,1,1],padding='SAME')
A1=tf.nn.relu(Z1)
P1=tf.nn.max_pool(A1,ksize=[1,4,4,1],strides=[1,4,4,1],padding='SAME')
Z2=tf.nn.conv2d(P1,W2,strides=[1,2,2,1],padding='VALID')
A2=tf.nn.relu(Z2)
F= tf.contrib.layers.flatten(A2)
Z3=tf.contrib.layers.fully_connected(F,10,activation_fn=None)
return Z3
# + id="1vLBE-duqTSs" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="45820ed8-0440-4a0c-e15b-8d4f0e5cfad8"
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train=x_train.reshape(-1,28,28,1) #Loading the dataset
x_test=x_test.reshape(-1,28,28,1)
# + id="_Q0Otm8nZ7-5" colab_type="code" colab={}
import numpy as np
def convert_to_one_hot(Y, C):
Y = np.eye(C)[Y.reshape(-1)].T
return Y
y_train=convert_to_one_hot(y_train,10)
y_test=convert_to_one_hot(y_test,10)
# + id="XDbAMQEMZ9g1" colab_type="code" colab={}
y_train=y_train.T
y_test=y_test.T
# + id="JMzlMEEEaRys" colab_type="code" outputId="0b15a9e3-58f0-4f10-bcc8-96a280c1eb86" colab={"base_uri": "https://localhost:8080/", "height": 51}
print(x_train.shape)
print(y_test.shape)
#X_train=x_train.reshape(-1,28,28,1)
#X_test=x_test.reshape(-1,28,28,1)
# + id="DGxVAv6BtaPo" colab_type="code" colab={}
def compute_cost(Z3,Y):
cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Z3,labels=Y))
return cost
# + id="QNOcCsz-IDT9" colab_type="code" colab={}
def model(x_train,y_train,x_test,y_test):
ops.reset_default_graph()
(m,n_h,n_w,n_c)=x_train.shape
n_y=10
costs=[]
X,Y=create_placeholder(n_h,n_w,n_y)
parameters=initialize_parameters()
Z3=forward_propagate(X,parameters)
cost=compute_cost(Z3,Y)
optimizer=tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
init=tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
saver.restore(sess, "Colab Notebooks/MNIST/MNIST.ckpt")
#saver.restore(sess,
for epoch in range(500):
_,temp_cost=sess.run([optimizer,cost],feed_dict={X:x_train,Y:y_train})
if epoch%20==0:
print ("Cost after epoch %i: %f" % (epoch, temp_cost))
if epoch % 1 == 0:
costs.append(temp_cost)
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
#plt.title("Learning rate =" + str(learning_rate))
plt.show()
# Calculate the correct predictions
predict_op = tf.argmax(Z3, 1)
correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))
# Calculate accuracy on the test set
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print(accuracy)
train_accuracy = accuracy.eval({X: x_train, Y: y_train})
test_accuracy = accuracy.eval({X: x_test, Y: y_test})
print("Train Accuracy:", train_accuracy)
print("Test Accuracy:", test_accuracy)
saver.save(sess, "Colab Notebooks/MNIST.ckpt")
return train_accuracy, test_accuracy, parameters
# + id="zDWuj17hNgw2" colab_type="code" outputId="55325199-f4a6-4362-ae57-6f2489592525" colab={"base_uri": "https://localhost:8080/", "height": 855}
_, _, parameters = model(x_train, y_train, x_test, y_test) #with channel number 16,32
# + id="hnKsFenVZBHQ" colab_type="code" colab={}
| MNIST.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import everest
import numpy as np
import matplotlib.pyplot as pl
# %matplotlib inline
# ## Load the light curve
# Choose from 201367065 205071984, 201546283, 210957318, 211916756, 201546283
star = everest.Everest(201367065)
# ## Plot the raw light curve
fig = pl.figure(figsize=(16,4))
pl.plot(star.time, star.fraw / np.nanmedian(star.fraw), 'k.', alpha = 0.3, ms = 3);
pl.ylim(0.995,1.005);
# ## Remove the really bad outliers and normalize
cut = np.where((star.fraw < 0.995) | (star.time < 1980))
time = np.delete(star.time, cut)
fpix = np.delete(star.fpix, cut, axis = 0)
ntime, npix = fpix.shape
fpix /= np.nanmedian(np.nansum(fpix, axis=1))
y = np.sum(fpix, axis = 1).reshape(-1, 1)
# ## The PLD design matrix
# PLD regressors
A = fpix / y.reshape(-1, 1)
fig = pl.figure(figsize=(16,8))
for n in range(npix):
pl.plot(time, A[:,n]);
# ## The rotation covariance matrix (not optimized!)
import george
K = george.GP(0.0001 ** 2 * george.kernels.Matern32Kernel(10. ** 2)).get_matrix(time)
pl.imshow(K);
# ## The diagonal regularization matrix (not optimized!)
L_diag = np.ones(A.shape[1]) * 0.005
# ## The full covariance
S = np.dot(A, L_diag[:, None] * A.T) + K
pl.imshow(S);
# ## The log likelihood
from scipy.linalg import cho_solve, cho_factor
choS = cho_factor(S)
def logL(model):
return -0.5 * np.dot((y - model).reshape(1,-1), cho_solve(choS, y - model))
# ## Likelihood for a simple box transit at every point
from tqdm import tqdm
lnL0 = logL(0)[0][0]
dchisq = np.zeros_like(time)
for i in tqdm(range(2, len(time) - 2)):
model = np.zeros_like(time)
model[i-2:i+2] = -1
model = model.reshape(-1, 1)
varw = 1. / np.dot(model.reshape(1, -1), cho_solve(choS, model))
w = varw * np.dot(model.reshape(1, -1), cho_solve(choS, y))
r = y - w * model
lnL = -0.5 * np.dot(r.reshape(1, -1), cho_solve(choS, r))
dchisq[i] = -2 * (lnL0 - lnL)
# Plot dchisq w/ planet b highlighted
fig, ax = pl.subplots(1, figsize=(15, 4))
pl.plot(time, dchisq);
pl.ylim(0, 1e10);
for i in range(8):
pl.axvline(1980.4173 + i * 10.0545, color='r', alpha=0.5)
# ## Not great, but given that we didn't optimize any of our matrices, it's not a bad start.
| easy_pld.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Setup
# %pylab inline
import matplotlib
import numpy as np
from PIL import Image
import time
# Open Image
filename = 'sobel.jpg'
im = Image.open(filename)
matplotlib.pyplot.imshow(im) # Check that image loaded properly
# Image Prep
im = np.array(im) # Change to Numpy Array
im = im[:,:,0] # From RGB to Grayscale
im = np.invert(im) # Invert Colors
matplotlib.pyplot.imshow(im) # Make sure numpy inverted colors
# ## Sobel Algorithm 1
# +
# Sobel Algorithm
startTime = time.time()
print('Started')
w, h = im.shape # Get Width and Height
imtot = np.zeros((w,h)) # Initialize New Image
for i in range(w-1): # Sobel Algoritm
for j in range(h-1):
if i > 0 and i < w-1 and j > 0 and j < h-1:
x = im[i+1][j+1] + im[i+1][j]*2 + im[i+1][j+1] - im[i-1][j+1] - im[i-1][j]*2 - im[i-1][j-1]
y = im[i-1][j-1] + im[i][j-1]*2 + im[i+1][j-1] - im[i-1][j+1] - im[i][j+1]*2 - im[i+1][j+1]
imtot[i][j] = np.sqrt(x**2 + y**2)
matplotlib.pyplot.imshow(imtot) # Show Results of Sobel
print('took {} seconds'.format(time.time()-startTime))
# -
# ## Sobel Algorithm 2
# +
# Sobel Algorithm 2
startTime = time.time()
print('Started')
kernelx = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
kernely = np.array([[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]])
m, n = kernelx.shape # Get Kernel Shape
imconv = np.zeros((w,h))
assert kernelx.shape == kernely.shape
for a in range(w-m+1):
for b in range(h-n+1):
imconv[a][b] = np.sqrt( np.sum( im[a:a+m, b:b+n]*kernelx )**2 + np.sum( im[a:a+m, b:b+n]*kernely )**2 )
matplotlib.pyplot.imshow(imconv) # Show Results of Sobel
print('took {} seconds'.format(time.time()-startTime))
# -
# Quicker ways to make Kernel Y
kernely = np.flip(kernelx.T)
# or
kernely = kernelx.T[::-1]
| cv/spatial/numpy-sobel.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + id="6jrIpN7ehBFs"
#wayback-machine-archiver install
# !pip install wayback-machine-archiver
import os
import re
import requests
# !apt-get install wget
from google.colab import drive
drive.mount('/content/drive')
# !mkdir urls
# %cd "/content/drive/My Drive/urls"
# !wget https://github.com/ankris812/wayback-machine-archiver/blob/master/urls.txt
# !archiver --file urls.txt
# + [markdown] id="mXKKCfCghQlU"
# Proyect backup script. Used for saving a list of pages into wayback machine. The list is located on https://github.com/ankris812/wayback-machine-archiver/blob/master/urls.txt you can suggest urls sending a message to t.me/ProyectBackupBot or with a pull request
| proyect-backup.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="sXhZm0kpPpH6"
# ##### Copyright 2021 Google LLC.
# + cellView="form" id="KfmzfvFxPuk7"
#@title Licensed under the Apache License, Version 2.0 (the "License");
# 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.
# + [markdown] id="iOVCm4CnP1Do"
# <a href="https://colab.research.google.com/github/google-research/vision_transformer/blob/master/vit_jax_augreg.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="8dkWVp5qbziu"
# ## How to train your ViT? Data, Augmentation, and Regularization in Vision Transformers
# + [markdown] id="ofwi7yvlx5hj"
# Model repository published with the paper
#
# [**How to train your ViT? Data, Augmentation, and Regularization in Vision
# Transformers**](https://arxiv.org/abs/2106.10270)
#
# This Colab shows how to
# [find checkpoints](#scrollTo=F4SLGDtFxlsC)
# in the repository, how to
# [select and load a model](#scrollTo=wh_SLkQtQ6K4)
# form the repository and use it for inference
# ([also with PyTorch](#scrollTo=1nMyWmDycpAo)),
# and how to
# [fine-tune on a dataset](#scrollTo=iAruT3YOxqB6).
#
# For more details, please refer to the repository:
#
# https://github.com/google-research/vision_transformer/
#
# Note that this Colab directly uses the unmodified code from the repository. If
# you want to modify the modules and persist your changes, you can do all that
# using free GPUs and TPUs without leaving the Colab environment - see
#
# https://colab.research.google.com/github/google-research/vision_transformer/blob/master/vit_jax.ipynb
# + [markdown] id="LPNkX_dfCNog"
# ### Imports
# + colab={"base_uri": "https://localhost:8080/"} id="_ihyJdwbCVmW" outputId="998b714c-ebaa-4ece-aaf1-533ef08b4d57"
# Fetch vision_transformer repository.
![ -d vision_transformer ] || git clone --depth=1 https://github.com/google-research/vision_transformer
# + colab={"base_uri": "https://localhost:8080/"} id="__7nV7c6C4Zn" outputId="cd868560-3aae-4887-e735-3a0a9d1ddef2"
# Install dependencies.
# !pip install -qr vision_transformer/vit_jax/requirements.txt
# + id="R9VrgMtUC2w-"
# Import files from repository.
import sys
if './vision_transformer' not in sys.path:
sys.path.append('./vision_transformer')
# %load_ext autoreload
# %autoreload 2
from vit_jax import checkpoint
from vit_jax import models
from vit_jax import train
from vit_jax.configs import augreg as augreg_config
from vit_jax.configs import models as models_config
# + colab={"base_uri": "https://localhost:8080/"} id="MpYDX1idbVxq" outputId="45a024e9-9b96-4a21-b0de-2d6e4c913f29"
# Connect to TPUs if runtime type is of type TPU.
import os
if 'google.colab' in str(get_ipython()) and 'COLAB_TPU_ADDR' in os.environ:
import jax
import jax.tools.colab_tpu
jax.tools.colab_tpu.setup_tpu()
print('Connected to TPU.')
else:
# Otherwise print information about GPU.
# !nvidia-smi
# + id="6xTeXue8DfwL"
# Some more imports used in this Colab.
import glob
import os
import random
import shutil
import time
from absl import logging
import pandas as pd
import seaborn as sns
import tensorflow as tf
import tensorflow_datasets as tfds
from matplotlib import pyplot as plt
pd.options.display.max_colwidth = None
logging.set_verbosity(logging.INFO) # Shows logs during training.
# + [markdown] id="F4SLGDtFxlsC"
# ### Explore checkpoints
#
# This section contains shows how to use the `index.csv` table for model
# selection.
#
# See
# [`vit_jax.checkpoint.get_augreg_df()`](https://github.com/google-research/vision_transformer/blob/ed1491238f5ff6099cca81087c575a215281ed14/vit_jax/checkpoint.py#L181-L228)
# for a detailed description of the individual columns
# + id="yy-cuGxyD6Xw"
# Load master table from Cloud.
with tf.io.gfile.GFile('gs://vit_models/augreg/index.csv') as f:
df = pd.read_csv(f)
# + colab={"base_uri": "https://localhost:8080/"} id="j8iAESfDKCQS" outputId="b92ef316-7df4-464c-9448-25d18dbde999"
# This is a pretty large table with lots of columns:
print(f'loaded {len(df):,} rows')
df.columns
# + colab={"base_uri": "https://localhost:8080/"} id="Wi4CwizkKIx_" outputId="22288fad-82c7-4c10-dcd6-763eb8f39547"
# Number of distinct checkpoints
len(tf.io.gfile.glob('gs://vit_models/augreg/*.npz'))
# + colab={"base_uri": "https://localhost:8080/"} id="FOM3HkkbKPdk" outputId="f54635ac-47f7-44b4-f2c1-6d352b16d12a"
# Any column prefixed with "adapt_" pertains to the fine-tuned checkpoints.
# Any column without that prefix pertains to the pre-trained checkpoints.
len(set(df.filename)), len(set(df.adapt_filename))
# + id="h3EyLd3S4XDS" outputId="6569412c-44da-4f8a-abd8-4c3b1318844b" colab={"base_uri": "https://localhost:8080/"}
df.name.unique()
# + colab={"base_uri": "https://localhost:8080/", "height": 359} id="w38Gjj-SGLVu" outputId="67776302-9f11-4cb0-8615-7f193b473f7d"
# Upstream AugReg parameters (section 3.3):
(
df.groupby(['ds', 'name', 'wd', 'do', 'sd', 'aug']).filename
.count().unstack().unstack().unstack()
.dropna(1, 'all').fillna(0).astype(int)
.iloc[:7] # Just show beginning of a long table.
)
# + colab={"base_uri": "https://localhost:8080/", "height": 421} id="PjI5jX36GeFr" outputId="27c96ac3-d61d-4974-f614-cc86456a673b"
# Downstream parameters (table 4)
# (Imbalance in 224 vs. 384 is due to recently added B/8 checkpoints)
(
df.groupby(['adapt_resolution', 'adapt_ds', 'adapt_lr', 'adapt_steps']).filename
.count().astype(str).unstack().unstack()
.dropna(1, 'all').fillna('')
)
# + colab={"base_uri": "https://localhost:8080/"} id="8Gbt7cdhEHg7" outputId="1d07cd9e-3b5f-4cdb-c38b-15bb3755843a"
# Let's first select the "best checkpoint" for every model. We show in the
# paper (section 4.5) that one can get a good performance by simply choosing the
# best model by final pre-train validation accuracy ("final-val" column).
# Pre-training with imagenet21k 300 epochs (ds=="i21k") gives the best
# performance in almost all cases (figure 6, table 5).
best_filenames = set(
df.query('ds=="i21k"')
.groupby('name')
.apply(lambda df: df.sort_values('final_val').iloc[-1])
.filename
)
# Select all finetunes from these models.
best_df = df.loc[df.filename.apply(lambda filename: filename in best_filenames)]
# Note: 9 * 68 == 612
len(best_filenames), len(best_df)
# + colab={"base_uri": "https://localhost:8080/"} id="poiez-EcZmtI" outputId="c6ab958a-3bc8-4d56-df11-fdc6a5f0ea83"
best_df.columns
# + colab={"base_uri": "https://localhost:8080/", "height": 730} id="MI_XTt1vX930" outputId="70747a26-5c5a-47b5-c269-12ef28848301"
# Note that this dataframe contains the models from the "i21k_300" column of
# table 3:
best_df.query('adapt_ds=="imagenet2012"').groupby('name').apply(
lambda df: df.sort_values('adapt_final_val').iloc[-1]
)[[
# Columns from upstream
'name', 'ds', 'filename',
# Columns from downstream
'adapt_resolution', 'infer_samples_per_sec','adapt_ds', 'adapt_final_test', 'adapt_filename',
]].sort_values('infer_samples_per_sec')
# + colab={"base_uri": "https://localhost:8080/", "height": 388} id="iPYUh4V1EdHg" outputId="fbe7aa0d-5ddd-46d3-c3bb-c6006a995ec2"
# Visualize the 2 (resolution) * 9 (models) * 8 (lr, steps) finetunings for a
# single dataset (Pets37).
# Note how larger models get better scores up to B/16 @384 even on this tiny
# dataset, if pre-trained sufficiently.
sns.relplot(
data=best_df.query('adapt_ds=="oxford_iiit_pet"'),
x='infer_samples_per_sec',
y='adapt_final_val',
hue='name',
style='adapt_resolution'
)
plt.gca().set_xscale('log');
# + colab={"base_uri": "https://localhost:8080/", "height": 817} id="9i7Y9AcpFtlr" outputId="1a92afd1-ce4f-4e3a-82c9-f0f0a8a11a99"
# More details for a single pre-trained checkpoint.
best_df.query('name=="R26+S/32" and adapt_ds=="oxford_iiit_pet"')[[
col for col in best_df.columns if col.startswith('adapt_')
]].sort_values('adapt_final_val')
# + [markdown] id="wh_SLkQtQ6K4"
# ### Load a checkpoint
# + colab={"base_uri": "https://localhost:8080/"} id="cwWBMJSpQ7EZ" outputId="c7e94c93-0e17-4209-bedf-c6a394c4a8cf"
# Select a value from "adapt_filename" above that is a fine-tuned checkpoint.
filename = 'R26_S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.1-do_0.0-sd_0.0--oxford_iiit_pet-steps_0k-lr_0.003-res_384'
tfds_name = filename.split('--')[1].split('-')[0]
model_config = models_config.AUGREG_CONFIGS[filename.split('-')[0]]
resolution = int(filename.split('_')[-1])
path = f'gs://vit_models/augreg/{filename}.npz'
print(f'{tf.io.gfile.stat(path).length / 1024 / 1024:.1f} MiB - {path}')
# + colab={"base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": ["225ebb8a26264dca90b312edb1e73fb6", "7d3d39e266ab4a81983fbf829795f3a7", "<KEY>", "d4e82b87ab4a485c9e15f3fd6e77a969", "<KEY>", "63c6ec28cbad46359e38d1f921b15ffa", "d9d5245d91fe42999d8b8693674880f7", "113db5d71db84749805a9394e89b9e0b", "<KEY>", "c2ce9e71f07a4be59374466f7a8f33ff", "608ff4fab08743d8ade2cf99ac8dcd69", "<KEY>", "0e51cd83a88140728b937542605c7e62", "a6f978d87f114e4ea5fd99ca45c67ba1", "<KEY>", "<KEY>", "132048250a42471785d742ecfa679a7b", "a9d7f91c071345ce9012a39adc3037b5", "79577fafaa0c46cc85e057d50e1f640f", "a0e3deff575141949907cb8647a769be", "770dd8577d454c2e82774043376809c1", "a73ff8ef581e44d8a8503f4cf25df02f", "<KEY>", "<KEY>", "43a06b56ab8742cabec36cd19b51945c", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "8f0adf499e434dc2863bdf6537c08454", "<KEY>", "f0da817110a947d2b0b54a43c7879ec6", "<KEY>", "5a54036091c84c6582ccf8ea545f7f4c", "ee0a499dc13b4a6eb36627a242d6e92a", "febe24498bc0445ab747c120c6abe261", "56f06ed9e69d40f9b5f39e1550fd2eb1", "<KEY>", "747b920f1510475dad43d49ba782be4d", "<KEY>", "<KEY>", "716975e14c8f4b59ade02dc968d58b5e", "<KEY>", "817ad1768fa14aa0b548e259d2162944", "413ba3075e7d4f54989b8de944aa0759", "<KEY>", "<KEY>", "ee27f121919d4345acd966ad98518b3a", "fa485b969a6c4893bbb42904fed24eeb", "7d4bff3e31c4431e91054562d51f80e8", "<KEY>", "<KEY>", "9ff4e5d0a6cd4953a9b04cdd115de440", "661c19ff44f048eaa8b21ee203319c68", "e9bc91cf5f67406689c7fe90800f729f"]} id="MKW2flB_Sk1u" outputId="f7be2692-d725-4799-f165-9724cd941799"
# Fetch dataset that the checkpoint was finetuned on.
# (Note that automatic download does not work with imagenet2012)
ds, ds_info = tfds.load(tfds_name, with_info=True)
ds_info
# + id="KtmV4tRCSX8n"
# Get model instance - no weights are initialized yet.
model = models.VisionTransformer(
num_classes=ds_info.features['label'].num_classes, **model_config)
# + id="GU6Tw1KvScBA"
# Load a checkpoint from cloud - for large checkpoints this can take a while...
params = checkpoint.load(path)
# + id="Js-QtAqeUJCo"
# Get a single example from dataset for inference.
d = next(iter(ds['test']))
# + colab={"base_uri": "https://localhost:8080/", "height": 269} id="xpovSMYFUHAj" outputId="b0a70f79-2ddb-40f7-9e48-16783404aeec"
def pp(img, sz):
"""Simple image preprocessing."""
img = tf.cast(img, float) / 255.0
img = tf.image.resize(img, [sz, sz])
return img
plt.imshow(pp(d['image'], resolution));
# + id="dBgTdceOT9vz" outputId="6bc9ec9b-8f30-4f8e-a820-08928f30ecaa" colab={"base_uri": "https://localhost:8080/"}
# Inferance on batch with single example.
logits, = model.apply({'params': params}, [pp(d['image'], resolution)], train=False)
# + colab={"base_uri": "https://localhost:8080/", "height": 382} id="QIQM--g4VwY9" outputId="57cb35e7-c9e3-45f2-8ead-38a21f6646d4"
# Plot logits (you can use tf.nn.softmax() to show probabilities instead).
plt.figure(figsize=(10, 4))
plt.bar(list(map(ds_info.features['label'].int2str, range(len(logits)))), logits)
plt.xticks(rotation=90);
# + [markdown] id="1nMyWmDycpAo"
# #### Using `timm`
#
# If you know PyTorch, you're probably already familiar with `timm`.
#
# If not yet - it's your lucky day! Please check out their docs here:
#
# https://rwightman.github.io/pytorch-image-models/
# + colab={"base_uri": "https://localhost:8080/"} id="yV6Sr1TdXUMp" outputId="5afc4a13-6c7e-4a01-cef0-27edf08a2a59"
# Checkpoints can also be loaded directly into timm...
# !pip install timm
import timm
import torch
# + colab={"base_uri": "https://localhost:8080/"} id="gwV4IvfYXioI" outputId="ca3651e1-b892-4218-d59e-bca10faaa7b5"
# For available model names, see here:
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer_hybrid.py
timm_model = timm.create_model(
'vit_small_r26_s32_384', num_classes=ds_info.features['label'].num_classes)
# Non-default checkpoints need to be loaded from local files.
if not tf.io.gfile.exists(f'{filename}.npz'):
tf.io.gfile.copy(f'gs://vit_models/augreg/{filename}.npz', f'{filename}.npz')
timm.models.load_checkpoint(timm_model, f'{filename}.npz')
# + id="gd6NVWNLYOSI"
def pp_torch(img, sz):
"""Simple image preprocessing for PyTorch."""
img = pp(img, sz)
img = img.numpy().transpose([2, 0, 1]) # PyTorch expects NCHW format.
return torch.tensor(img[None])
with torch.no_grad():
logits, = timm_model(pp_torch(d['image'], resolution)).detach().numpy()
# + colab={"base_uri": "https://localhost:8080/", "height": 382} id="vA-mEJofeHxd" outputId="883ea202-af9c-4be9-b80d-ff207b7208e8"
# Same results as above (since we loaded the same checkpoint).
plt.figure(figsize=(10, 4))
plt.bar(list(map(ds_info.features['label'].int2str, range(len(logits)))), logits)
plt.xticks(rotation=90);
# + [markdown] id="iAruT3YOxqB6"
# ### Fine-tune
#
# You want to be connected to a TPU or GPU runtime for fine-tuning.
#
# Note that here we're just calling into the code. For more details see the
# annotated Colab
#
# https://colab.sandbox.google.com/github/google-research/vision_transformer/blob/linen/vit_jax.ipynb
#
# Also note that Colab GPUs and TPUs are not very powerful. To run this code on
# more powerful machines, see:
#
# https://github.com/google-research/vision_transformer/#running-on-cloud
#
# In particular, note that due to the Colab "TPU Node" setup, transfering data to
# the TPUs is realtively slow (for example the smallest `R+Ti/16` model trains
# faster on a single GPU than on 8 TPUs...)
# + [markdown] id="TiHEFXlBbZiV"
# #### TensorBoard
# + id="Fu6uaCGDXLmr"
# Launch tensorboard before training - maybe click "reload" during training.
# %load_ext tensorboard
# %tensorboard --logdir=./workdirs
# + [markdown] id="KYU9EdV2bWV7"
# #### From tfds
# + colab={"base_uri": "https://localhost:8080/", "height": 35} id="Z1Ee2-GzZ9sl" outputId="bb6c3056-1e2d-4f76-f490-29daa38c30c8"
# Create a new temporary workdir.
workdir = f'./workdirs/{int(time.time())}'
workdir
# + id="SB73ZFGCxsXo"
# Get config for specified model.
# Note that we can specify simply the model name (in which case the recommended
# checkpoint for that model is taken), or it can be specified by its full
# name.
config = augreg_config.get_config('R_Ti_16')
# A very small tfds dataset that only has a "train" split. We use this single
# split both for training & evaluation by splitting it further into 90%/10%.
config.dataset = 'tf_flowers'
config.pp.train = 'train[:90%]'
config.pp.test = 'train[90%:]'
# tf_flowers only has 3670 images - so the 10% evaluation split will contain
# 360 images. We specify batch_eval=120 so we evaluate on all but 7 of those
# images (remainder is dropped).
config.batch_eval = 120
# Some more parameters that you will often want to set manually.
# For example for VTAB we used steps={500, 2500} and lr={.001, .003, .01, .03}
config.base_lr = 0.01
config.shuffle_buffer = 1000
config.total_steps = 100
config.warmup_steps = 10
config.accum_steps = 0 # Not needed with R+Ti/16 model.
config.pp['crop'] = 224
# + id="ldKZFMnmYjY_" colab={"base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": ["5ed291cf3157447684e4c732e15713b8", "06ea24f8073b4185965fb4b1494e0f19", "6b6f717b6613435ca113a68a1e1f4126", "a9deea48888c423cbb5b3e310b106147", "e2388f624f314ae68d3c6a84127ed400", "d51511f4aa504dc2a56c089a167b1c6a", "05ec97fde7084f5c9cf54b707bf0edf1", "61ee19bf89fb4955bda1e759dfd99cb7"]} outputId="d6fe8e95-83c1-4c55-e96f-1a0b57b7d84a"
# Call main training loop. See repository and above Colab for details.
state = train.train_and_evaluate(config, workdir)
# + [markdown] id="JOtCfWFOfVFq"
# #### From JPG files
#
# The codebase supports training directly form JPG files on the local filesystem
# instead of `tfds` datasets. Note that the throughput is somewhat reduced, but
# that only is noticeable for very small models.
#
# The main advantage of `tfds` datasets is that they are versioned and available
# globally.
# + id="5VxlDlnxKAa3"
base = '.' # Store data on VM (ephemeral).
# + id="yr6JY8OBmKkj"
# Uncomment below lines if you want to download & persist files in your Google
# Drive instead. Note that Colab VMs are reset (i.e. files are deleted) after
# some time of inactivity. Storing data to Google Drive guarantees that it is
# still available next time you connect from a new VM.
# Note that this is significantly slower than reading from the VMs locally
# attached file system!
# from google.colab import drive
# drive.mount('/gdrive')
# base = '/gdrive/My Drive/vision_transformer_images'
# + colab={"base_uri": "https://localhost:8080/"} id="VZJdKYv3mLqd" outputId="552207d7-cfbe-4a1f-e140-bbbbfd0da31c"
# Download some dataset & unzip.
# ! rm -rf '$base/flower_photos'; mkdir -p '$base'
! (cd '$base' && curl https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz | tar xz)
# + colab={"base_uri": "https://localhost:8080/"} id="0QRnYHLzmPxL" outputId="5d464050-9e3f-4ba0-eed6-ce49cfe01276"
# Since the default file format of above "tf_flowers" dataset is
# flower_photos/{class_name}/{filename}.jpg
# we first need to split it into a "train" (90%) and a "test" (10%) set:
# flower_photos/train/{class_name}/{filename}.jpg
# flower_photos/test/{class_name}/{filename}.jpg
def split(base_dir, test_ratio=0.1):
paths = glob.glob(f'{base_dir}/*/*.jpg')
random.shuffle(paths)
counts = dict(test=0, train=0)
for i, path in enumerate(paths):
split = 'test' if i < test_ratio * len(paths) else 'train'
*_, class_name, basename = path.split('/')
dst = f'{base_dir}/{split}/{class_name}/{basename}'
if not os.path.isdir(os.path.dirname(dst)):
os.makedirs(os.path.dirname(dst))
shutil.move(path, dst)
counts[split] += 1
print(f'Moved {counts["train"]:,} train and {counts["test"]:,} test images.')
split(f'{base}/flower_photos')
# + colab={"base_uri": "https://localhost:8080/", "height": 35} id="1DKwlCXTKJjJ" outputId="83f39dfb-e764-4bf8-e486-95d26db6e371"
# Create a new temporary workdir.
workdir = f'./workdirs/{int(time.time())}'
workdir
# + id="N2ojstZeKJjK"
# Read data from directory containing files.
# (See cell above for more config settings)
config.dataset = f'{base}/flower_photos'
# + id="L8hljjZlKJjK" colab={"base_uri": "https://localhost:8080/"} outputId="b9880743-3984-475e-a3f1-7c60b6f904e4"
# And fine-tune on images provided
opt = train.train_and_evaluate(config, workdir)
| vit_jax_augreg.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## As you saw from the last chapter, hypothesis testing can be a bit tricky. You need to define the null hypothesis, figure out how to simulate it, and define clearly what it means to be "more extreme" in order to compute the p-value. Like any skill, practice makes perfect, and this chapter gives you some good practice with hypothesis tests.
# ## The vote for the Civil Rights Act in 1964
# The Civil Rights Act of 1964 was one of the most important pieces of legislation ever passed in the USA. Excluding "present" and "abstain" votes, 153 House Democrats and 136 Republicans voted yea. However, 91 Democrats and 35 Republicans voted nay. Did party affiliation make a difference in the vote?
#
# To answer this question, you will evaluate the hypothesis that the party of a House member has no bearing on his or her vote. You will use the fraction of Democrats voting in favor as your test statistic and evaluate the probability of observing a fraction of Democrats voting in favor at least as small as the observed fraction of 153/244. (That's right, at least as small as. In 1964, it was the Democrats who were less progressive on civil rights issues.) To do this, permute the party labels of the House voters and then arbitrarily divide them into "Democrats" and "Republicans" and compute the fraction of Democrats voting yea.
# __Instructions__
# - Construct Boolean arrays, dems and reps that contain the votes of the respective parties; e.g., dems has 153 True entries and 91 False entries.
# - Write a function, frac_yea_dems(dems, reps) that returns the fraction of Democrats that voted yea. The first input is an array of Booleans, Two inputs are required to use your draw_perm_reps() function, but the second is not used.
# - Use your draw_perm_reps() function to draw 10,000 permutation replicates of the fraction of Democrat yea votes.
# - Compute and print the p-value.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from ipynb.fs.full.Module3_Introduction_to_hypothesis_testing import draw_perm_reps
# +
# Construct arrays of data: dems, reps
dems = np.array([True] * 153 + [False] * 91)
reps = np.array([True] * 136 + [False] * 35)
def frac_yea_dems(dems, reps):
"""Compute fraction of Democrat yea votes."""
frac = np.sum(dems) / len(dems)
return frac
# Acquire permutation samples: perm_replicates
perm_replicates = draw_perm_reps(dems, reps, frac_yea_dems, 10000)
# Compute and print p-value: p
p = np.sum(perm_replicates <= 153/244) / len(perm_replicates)
print('p-value =', p)
# + active=""
# Great work! This small p-value suggests that party identity had a lot to do with the voting. Importantly, the South had a higher fraction of Democrat representatives, and consequently also a more racist bias.
# -
# ## A time-on-website analog
# It turns out that you already did a hypothesis test analogous to an A/B test where you are interested in how much time is spent on the website before and after an ad campaign. The frog tongue force (a continuous quantity like time on the website) is an analog. "Before" = Frog A and "after" = Frog B. Let's practice this again with something that actually is a before/after scenario.
#
# We return to the no-hitter data set. In 1920, Major League Baseball implemented important rule changes that ended the so-called dead ball era. Importantly, the pitcher was no longer allowed to spit on or scuff the ball, an activity that greatly favors pitchers. In this problem you will perform an A/B test to determine if these rule changes resulted in a slower rate of no-hitters (i.e., longer average time between no-hitters) using the difference in mean inter-no-hitter time as your test statistic. The inter-no-hitter times for the respective eras are stored in the arrays nht_dead and nht_live, where "nht" is meant to stand for "no-hitter time."
# __Instructions__
# - Compute the observed difference in mean inter-nohitter time using diff_of_means().
# - Generate 10,000 permutation replicates of the difference of means using draw_perm_reps().
# - Compute and print the p-value.
from ipynb.fs.full.Module3_Introduction_to_hypothesis_testing import diff_of_means
nht_dead = np.array([ -1, 894, 10, 130, 1, 934, 29, 6, 485, 254, 372,
81, 191, 355, 180, 286, 47, 269, 361, 173, 246, 492,
462, 1319, 58, 297, 31, 2970, 640, 237, 434, 570, 77,
271, 563, 3365, 89, 0, 379, 221, 479, 367, 628, 843,
1613, 1101, 215, 684, 814, 278, 324, 161, 219, 545, 715,
966, 624, 29, 450, 107, 20, 91, 1325, 124, 1468, 104,
1309, 429, 62, 1878, 1104, 123, 251, 93, 188, 983, 166,
96, 702, 23, 524, 26, 299, 59, 39, 12, 2, 308,
1114, 813, 887])
nht_live = np.array([ 645, 2088, 42, 2090, 11, 886, 1665, 1084, 2900, 2432, 750,
4021, 1070, 1765, 1322, 26, 548, 1525, 77, 2181, 2752, 127,
2147, 211, 41, 1575, 151, 479, 697, 557, 2267, 542, 392,
73, 603, 233, 255, 528, 397, 1529, 1023, 1194, 462, 583,
37, 943, 996, 480, 1497, 717, 224, 219, 1531, 498, 44,
288, 267, 600, 52, 269, 1086, 386, 176, 2199, 216, 54,
675, 1243, 463, 650, 171, 327, 110, 774, 509, 8, 197,
136, 12, 1124, 64, 380, 811, 232, 192, 731, 715, 226,
605, 539, 1491, 323, 240, 179, 702, 156, 82, 1397, 354,
778, 603, 1001, 385, 986, 203, 149, 576, 445, 180, 1403,
252, 675, 1351, 2983, 1568, 45, 899, 3260, 1025, 31, 100,
2055, 4043, 79, 238, 3931, 2351, 595, 110, 215, 0, 563,
206, 660, 242, 577, 179, 157, 192, 192, 1848, 792, 1693,
55, 388, 225, 1134, 1172, 1555, 31, 1582, 1044, 378, 1687,
2915, 280, 765, 2819, 511, 1521, 745, 2491, 580, 2072, 6450,
578, 745, 1075, 1103, 1549, 1520, 138, 1202, 296, 277, 351,
391, 950, 459, 62, 1056, 1128, 139, 420, 87, 71, 814,
603, 1349, 162, 1027, 783, 326, 101, 876, 381, 905, 156,
419, 239, 119, 129, 467])
# +
# Compute the observed difference in mean inter-no-hitter times: nht_diff_obs
nht_diff_obs = diff_of_means(nht_dead, nht_live)
# Acquire 10,000 permutation replicates of difference in mean no-hitter time: perm_replicates
perm_replicates = draw_perm_reps(nht_dead, nht_live,
diff_of_means, size=10000)
# Compute and print the p-value: p
p = np.sum(perm_replicates <= nht_diff_obs) / len(perm_replicates)
print('p-val =', p)
# + active=""
# Your p-value is 0.0001, which means that only one out of your 10,000 replicates had a result as extreme as the actual difference between the dead ball and live ball eras. This suggests strong statistical significance. Watch out, though, you could very well have gotten zero replicates that were as extreme as the observed value. This just means that the p-value is quite small, almost certainly smaller than 0.001
# -
# ## Hypothesis test on Pearson correlation
# The observed correlation between female illiteracy and fertility may just be by chance; the fertility of a given country may actually be totally independent of its illiteracy. You will test this hypothesis. To do so, permute the illiteracy values but leave the fertility values fixed. This simulates the hypothesis that they are totally independent of each other. For each permutation, compute the Pearson correlation coefficient and assess how many of your permutation replicates have a Pearson correlation coefficient greater than the observed one.
#
# Import the function `pearson_r()` that you wrote in the chapter 1 of this course for computing the Pearson correlation coefficient
from ipynb.fs.full.Module1_Parameter_estimation_by_optimization import pearson_r
# __Instructions__
# - Compute the observed Pearson correlation between illiteracy and fertility.
# - Initialize an array to store your permutation replicates.
# - Write a for loop to draw 10,000 replicates:
# - Permute the illiteracy measurements using np.random.permutation().
# - Compute the Pearson correlation between the permuted illiteracy array, illiteracy_permuted, and fertility.
# - Compute and print the p-value from the replicates.
df = pd.read_csv('female_literacy_fertility.csv')
df.head()
fertility = df['fertility'].values
illiteracy = (100 - df['female literacy']).values
# +
# Compute observed correlation: r_obs
r_obs = pearson_r(illiteracy, fertility)
# Initialize permutation replicates: perm_replicates
perm_replicates = np.empty(10000)
# Draw replicates
for i in range(10000):
# Permute illiteracy measurments: illiteracy_permuted
illiteracy_permuted = np.random.permutation(illiteracy)
# Compute Pearson correlation
perm_replicates[i] = pearson_r(illiteracy_permuted, fertility)
# Compute p-value: p
p = np.sum(perm_replicates >= r_obs) / len(perm_replicates)
print('p-val =', p)
# + active=""
# You got a p-value of zero. In hacker statistics, this means that your p-value is very low, since you never got a single replicate in the 10,000 you took that had a Pearson correlation greater than the observed one. You could try increasing the number of replicates you take to continue to move the upper bound on your p-value lower and lower.
# -
# ## Do neonicotinoid insecticides have unintended consequences?
# As a final exercise in hypothesis testing before we put everything together in our case study in the next chapter, you will investigate the effects of neonicotinoid insecticides on bee reproduction. These insecticides are very widely used in the United States to combat aphids and other pests that damage plants.
#
# In a recent study, Straub, et al. (Proc. Roy. Soc. B, 2016) investigated the effects of neonicotinoids on the sperm of pollinating bees. In this and the next exercise, you will study how the pesticide treatment affected the count of live sperm per half milliliter of semen.
#
# First, we will do EDA, as usual. Plot ECDFs of the alive sperm count for untreated bees (stored in the Numpy array control) and bees treated with pesticide (stored in the Numpy array treated).
treated = np.array([1.342686, 1.058476, 3.793784, 0.40428 , 4.528388, 2.142966,
3.937742, 0.1375 , 6.919164, 0. , 3.597812, 5.196538,
2.78955 , 2.3229 , 1.090636, 5.323916, 1.021618, 0.931836,
2.78 , 0.412202, 1.180934, 2.8674 , 0. , 0.064354,
3.008348, 0.876634, 0. , 4.971712, 7.280658, 4.79732 ,
2.084956, 3.251514, 1.9405 , 1.566192, 0.58894 , 5.219658,
0.977976, 3.124584, 1.297564, 1.433328, 4.24337 , 0.880964,
2.376566, 3.763658, 1.918426, 3.74 , 3.841726, 4.69964 ,
4.386876, 0. , 1.127432, 1.845452, 0.690314, 4.185602,
2.284732, 7.237594, 2.185148, 2.799124, 3.43218 , 0.63354 ,
1.142496, 0.586 , 2.372858, 1.80032 , 3.329306, 4.028804,
3.474156, 7.508752, 2.032824, 1.336556, 1.906496, 1.396046,
2.488104, 4.759114, 1.07853 , 3.19927 , 3.814252, 4.275962,
2.817056, 0.552198, 3.27194 , 5.11525 , 2.064628, 0. ,
3.34101 , 6.177322, 0. , 3.66415 , 2.352582, 1.531696])
control = np.array([ 4.159234, 4.408002, 0.172812, 3.498278, 3.104912, 5.164174,
6.615262, 4.633066, 0.170408, 2.65 , 0.0875 , 1.997148,
6.92668 , 4.574932, 3.896466, 5.209814, 3.70625 , 0. ,
4.62545 , 3.01444 , 0.732652, 0.4 , 6.518382, 5.225 ,
6.218742, 6.840358, 1.211308, 0.368252, 3.59937 , 4.212158,
6.052364, 2.115532, 6.60413 , 5.26074 , 6.05695 , 6.481172,
3.171522, 3.057228, 0.218808, 5.215112, 4.465168, 2.28909 ,
3.732572, 2.17087 , 1.834326, 6.074862, 5.841978, 8.524892,
4.698492, 2.965624, 2.324206, 3.409412, 4.830726, 0.1 ,
0. , 4.101432, 3.478162, 1.009688, 4.999296, 4.32196 ,
0.299592, 3.606032, 7.54026 , 4.284024, 0.057494, 6.036668,
2.924084, 4.150144, 1.256926, 4.666502, 4.806594, 2.52478 ,
2.027654, 2.52283 , 4.735598, 2.033236, 0. , 6.177294,
2.601834, 3.544408, 3.6045 , 5.520346, 4.80698 , 3.002478,
3.559816, 7.075844, 10. , 0.139772, 6.17171 , 3.201232,
8.459546, 0.17857 , 7.088276, 5.496662, 5.415086, 1.932282,
3.02838 , 7.47996 , 1.86259 , 7.838498, 2.242718, 3.292958,
6.363644, 4.386898, 8.47533 , 4.156304, 1.463956, 4.533628,
5.573922, 1.29454 , 7.547504, 3.92466 , 5.820258, 4.118522,
4.125 , 2.286698, 0.591882, 1.273124, 0. , 0. ,
0. , 12.22502 , 7.601604, 5.56798 , 1.679914, 8.77096 ,
5.823942, 0.258374, 0. , 5.899236, 5.486354, 2.053148,
3.25541 , 2.72564 , 3.364066, 2.43427 , 5.282548, 3.963666,
0.24851 , 0.347916, 4.046862, 5.461436, 4.066104, 0. ,
0.065 ])
from ipynb.fs.full.Module1_Parameter_estimation_by_optimization import ecdf
# +
# Compute x,y values for ECDFs
x_control, y_control = ecdf(control)
x_treated, y_treated = ecdf(treated)
# Plot the ECDFs
plt.plot(x_control, y_control, marker='.', linestyle='none')
plt.plot(x_treated, y_treated, marker='.', linestyle='none')
# Set the margins
plt.margins(0.02)
# Add a legend
plt.legend(('control', 'treated'), loc='lower right')
# Label axes and show plot
plt.xlabel('millions of alive sperm per mL')
plt.ylabel('ECDF')
# + active=""
# Nice plot! The ECDFs show a pretty clear difference between the treatment and control; treated bees have fewer alive sperm. Let's now do a hypothesis test in the next exercise.
# -
# ## Bootstrap hypothesis test on bee sperm counts
# Now, you will test the following hypothesis: On average, male bees treated with neonicotinoid insecticide have the same number of active sperm per milliliter of semen than do untreated male bees. You will use the difference of means as your test statistic.
#
# For your reference, the call signature for the draw_bs_reps() function you wrote in chapter 2 is draw_bs_reps(data, func, size=1).
# __Instructions__
# - Compute the mean alive sperm count of control minus that of treated.
# - Compute the mean of all alive sperm counts. To do this, first concatenate control and treated and take the mean of the concatenated array.
# - Generate shifted data sets for both control and treated such that the shifted data sets have the same mean. This has already been done for you.
# - Generate 10,000 bootstrap replicates of the mean each for the two shifted arrays. Use your draw_bs_reps() function.
# - Compute the bootstrap replicates of the difference of means.
from ipynb.fs.full.Module2_Bootstrap_confidence_intervals import draw_bs_reps
# +
# Compute the difference in mean sperm count: diff_means
diff_means = np.mean(control) - np.mean(treated)
# Compute mean of pooled data: mean_count
mean_count = np.mean(np.concatenate((control, treated)))
# Generate shifted data sets
control_shifted = control - np.mean(control) + mean_count
treated_shifted = treated - np.mean(treated) + mean_count
# Generate bootstrap replicates
bs_reps_control = draw_bs_reps(control_shifted,
np.mean, size=10000)
bs_reps_treated = draw_bs_reps(treated_shifted,
np.mean, size=10000)
# Get replicates of difference of means: bs_replicates
bs_replicates = bs_reps_control - bs_reps_treated
# Compute and print p-value: p
p = np.sum(bs_replicates >= np.mean(control) - np.mean(treated)) \
/ len(bs_replicates)
print('p-value =', p)
# -
| Data Scientist with Python/Course 16 - Statistical Thinking in Python (Part 2)/Module4_Hypothesis test examples.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + deletable=true editable=true
import keras
import tensorflow as tf
from keras.applications.inception_v3 import InceptionV3, preprocess_input
from keras.preprocessing import image
from keras.layers import Dense, Lambda
from keras.models import Model
from keras import optimizers
import keras.backend as K
import numpy as np
from PIL import Image
import multiprocessing as mp
import math
import tqdm
from annoy import AnnoyIndex
import json
import PIL
from functools import partial, update_wrapper
# + deletable=true editable=true
img_size = 299 # input image size for network
margin = 0.3 # margin for triplet loss
batch_size = 42 # size of mini-batch
num_triplet = 700
valid_frequency = 100
num_epoch = 3600
log_dir = './logs/triplet_semihard_v3'
checkpoint_dir = 'checkpoints/'
recall_log_file = './logs/recall_triplet_semihard_v3.json'
recall_values = [1, 3, 5, 10, 25, 50, 100]
# + deletable=true editable=true
# + deletable=true editable=true
# utility function to freeze some portion of a function's arguments
def wrapped_partial(func, *args, **kwargs):
partial_func = partial(func, *args, **kwargs)
update_wrapper(partial_func, func)
return partial_func
# calculate recall score
def recall(y_true, y_pred):
return min(len(set(y_true) & set(y_pred)), 1)
# margin triplet loss
def margin_triplet_loss(y_true, y_pred, margin, batch_size):
out_a = tf.gather(y_pred, tf.range(0, batch_size, 3))
out_p = tf.gather(y_pred, tf.range(1, batch_size, 3))
out_n = tf.gather(y_pred, tf.range(2, batch_size, 3))
loss = K.maximum(margin
+ K.sum(K.square(out_a-out_p), axis=1)
- K.sum(K.square(out_a-out_n), axis=1),
0.0)
return K.mean(loss)
# + deletable=true editable=true
# + [markdown] deletable=true editable=true
# ### Define model architecture
# + deletable=true editable=true
def get_model():
no_top_model = InceptionV3(include_top=False, weights='imagenet', pooling='avg')
x = no_top_model.output
x = Dense(512, activation='elu', name='fc1')(x)
x = Dense(128, name='fc2')(x)
x = Lambda(lambda x: K.l2_normalize(x, axis=1), name='l2_norm')(x)
return Model(no_top_model.inputs, x)
# + deletable=true editable=true
model = get_model()
# -
# ### Compile model
# + deletable=true editable=true
opt = keras.optimizers.Adam(lr=0.0001)
model.compile(loss=wrapped_partial(margin_triplet_loss, margin=margin, batch_size=batch_size), optimizer=opt)
# + deletable=true editable=true
# + [markdown] deletable=true editable=true
# ### Load data
# -
# I have used mongodb to store dataset. Document structure:
# - type: define split on train, validation and test sets, possible values - 'train', 'val', 'test'
# - seller_img: list of IDs of seller's images
# - user_img: list of IDs of user's images
#
# Example:
# ```javascript
# {
# 'type': 'test',
# 'seller_img': ['HTB1s7ZiLFXXXXatXFXXq6xXFXXXu',
# 'HTB1pGaAKXXXXXczXXXXq6xXFXXXN'],
# 'user_img': ['<KEY>',
# '<KEY>',
# 'UTB8h7HUXnzIXKJkSafVq6yWgXXap',
# '<KEY>',
# '<KEY>',
# '<KEY>',
# '<KEY>']
# }
# ```
# + deletable=true editable=true
from pymongo import MongoClient
client = MongoClient(connect=False)
db = client['aliexpress']
coll = db['items']
# + deletable=true editable=true
train_seller_images = []
train_user_images = []
for item in coll.find({'type': 'train'}):
train_seller_images.append(item['seller_img'])
train_user_images.append(item['user_img'])
# + deletable=true editable=true
# + deletable=true editable=true
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer(sparse_output=True)
# + deletable=true editable=true
X_train_seller = mlb.fit_transform(train_seller_images)
# + deletable=true editable=true
train_images_seller = mlb.classes_
# + deletable=true editable=true
X_train_user = mlb.fit_transform(train_user_images)
# + deletable=true editable=true
train_images_user = mlb.classes_
# + deletable=true editable=true
num_images_by_class = np.asarray(X_train_user.sum(axis=1)).ravel()
# + deletable=true editable=true
# + deletable=true editable=true
val_images = [(x['seller_img'], x['user_img']) for x in coll.find({'type': 'val'})]
val_image_to_class = {}
for i, item in enumerate(val_images):
for x in item[0] + item[1]:
val_image_to_class[x] = i
val_images_clean = [(x['seller_img_clean'], x['user_img_clean']) for x in coll.find({'type': 'val', 'clean': True})]
val_image_clean_to_class = {}
for i, item in enumerate(val_images_clean):
for x in item[0] + item[1]:
val_image_clean_to_class[x] = i
test_images = [(x['seller_img'], x['user_img']) for x in coll.find({'type': 'test'})]
seller_images = [x for item in coll.find({}) for x in item['seller_img']]
val_user_images = [x for item in val_images for x in item[1]]
val_user_clean_images = [x for item in val_images_clean for x in item[1]]
# + deletable=true editable=true
# -
# ### Data loading utils
# + deletable=true editable=true
# load image by id without augmentations
def preprocess_image_worker(media_id):
img = Image.open(('./images/'+media_id+'.jpg')).convert('RGB')
img = img.resize((img_size, img_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
return x
# + deletable=true editable=true
# load image by id with augmentations
def preprocess_image_worker_aug(media_id):
img = Image.open(('./images/'+media_id+'.jpg')).convert('RGB')
img = img.crop((int(np.random.uniform(0, 0.05)*img.width), int(np.random.uniform(0, 0.05)*img.height),
int(np.random.uniform(0.95, 1.)*img.width), int(np.random.uniform(0.95, 1.)*img.height)))
if np.random.randint(2) == 0:
img = img.transpose(np.random.choice([PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90, PIL.Image.ROTATE_180, PIL.Image.ROTATE_270, PIL.Image.TRANSPOSE]))
img = img.resize((img_size, img_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
return x
# + deletable=true editable=true
# data generator, divides list images into mini-batches
def batch_generator_predict(pool, batch_size, images):
i = 0
while True:
batch = images[i:i+batch_size]
i += batch_size
if len(batch) == 0:
yield np.zeros((0, img_size, img_size, 3))
else:
result = pool.map(preprocess_image_worker, batch)
X_batch = np.concatenate(result, axis=0)
yield X_batch
# + deletable=true editable=true
# -
# ### Semi-hard negative mining
# + deletable=true editable=true
class SemiHardNegativeSampler:
def __init__(self, pool, batch_size, num_samples):
self.pool = pool
self.batch_size = batch_size
self.num_samples = num_samples
self.resample()
# sample triplets with semi-hard negatives
def resample(self):
sample_classes = np.random.choice(np.arange(X_train_user.shape[0]), p=num_images_by_class/num_images_by_class.sum(), size=self.num_samples)
sample_images = []
for i in sample_classes:
sample_images.append(train_images_user[np.random.choice(X_train_user[i].nonzero()[1], replace=False)])
sample_images.append(train_images_seller[np.random.choice(X_train_seller[i].nonzero()[1], replace=False)])
sample_images = np.array(sample_images)
pred_sample = model.predict_generator(batch_generator_predict(pool, 32, sample_images), math.ceil(len(sample_images)/32), max_q_size=1, workers=1)
a = pred_sample[np.arange(0, len(pred_sample), 2)]
p = pred_sample[np.arange(1, len(pred_sample), 2)]
triplets = []
self.dists = []
for i in range(self.num_samples):
d = np.square(a[i] - p[i]).sum()
neg_sample_classes = (sample_classes != sample_classes[i]).nonzero()[0]
neg = p[neg_sample_classes]
neg_ids = sample_images.reshape((-1, 2))[neg_sample_classes, 1]
d_neg = np.square(neg - a[i]).sum(axis=1)
semihard = np.where(d_neg > d)[0]
if len(semihard) == 0:
n = np.argmax(d_neg)
else:
n = semihard[np.argmin(d_neg[semihard])]
self.dists.append(d_neg[n]-d)
triplets.append(np.concatenate([sample_images.reshape((-1, 2))[i], np.array([neg_ids[n]])]))
self.triplets = np.array(triplets)
# data generator for triplets
def batch_generator(self):
i = 0
while True:
batch = self.triplets[i:i+self.batch_size//3].ravel()
i += self.batch_size//3
if len(batch) == 0:
yield np.zeros((0, img_size, img_size, 3))
else:
result = pool.map(preprocess_image_worker_aug, batch)
X_batch = np.concatenate(result, axis=0)
yield X_batch, np.zeros(len(batch))
# return data generator for triplets
def get_generator(self):
gen = self.batch_generator()
return gen
# + deletable=true editable=true
sampler = SemiHardNegativeSampler(pool, batch_size, num_triplets)
# -
# ### Create pool of processes for parallel data loading
# + deletable=true editable=true
pool = mp.Pool(processes=8)
# -
# ### Attach tensorboard to monitor learining process
# + deletable=true editable=true
tensorboard = keras.callbacks.TensorBoard(log_dir=log_dir,
histogram_freq=1,
write_graph=False,
write_images=False)
# + deletable=true editable=true
# -
# ### Training process
# Each epoch we
# - train model on triplets with semi-hard negatives from `sampler`
# - resample triplets
# - do validation and save model with frequency `valid_frequency`
#
# I use annoy index for nearest neighbors search to speedup validation
# + deletable=true editable=true
epoch = 0
# + deletable=true editable=true
for i in range(num_epoch):
train_gen = sampler.get_generator()
h = model.fit_generator(train_gen, steps_per_epoch=num_triplets//(batch_size//3), epochs=epoch+1, initial_epoch=epoch, verbose=2,
max_q_size=1, callbacks=[tensorboard,])
sampler.resample()
if epoch%valid_frequency == 0 and epoch != 0:
seller_pred = model.predict_generator(batch_generator_predict(pool, 32, seller_images), math.ceil(len(seller_images)/32), max_q_size=1, workers=1)
val_user_pred = model.predict_generator(batch_generator_predict(pool, 32, val_user_images), math.ceil(len(val_user_images)/32), max_q_size=1, workers=1)
val_user_clean_pred = model.predict_generator(batch_generator_predict(pool, 32, val_user_clean_images), math.ceil(len(val_user_clean_images)/32), max_q_size=1, workers=1)
search_index = AnnoyIndex(128, metric='euclidean')
for i in range(len(seller_pred)):
search_index.add_item(i, seller_pred[i])
search_index.build(50)
recall_scores = {i: [] for i in recall_values}
for i in range(len(val_user_pred)):
r = search_index.get_nns_by_vector(val_user_pred[i], 100)
val_cl = val_image_to_class[val_user_images[i]]
for k in recall_values:
recall_scores[k].append(recall(val_images[val_cl][0], [seller_images[i] for i in r[:k]]))
print ('val on full')
for k in recall_values:
print (k, np.mean(recall_scores[k]))
val_recall = [(k, np.mean(recall_scores[k])) for k in recall_values]
recall_scores = {i: [] for i in recall_values}
for i in range(len(val_user_clean_pred)):
r = search_index.get_nns_by_vector(val_user_clean_pred[i], 100)
val_cl = val_image_clean_to_class[val_user_clean_images[i]]
for k in recall_values:
recall_scores[k].append(recall(val_images_clean[val_cl][0], [seller_images[i] for i in r[:k]]))
print ('val on clean')
for k in recall_values:
print (k, np.mean(recall_scores[k]))
val_recall_clean = [(k, np.mean(recall_scores[k])) for k in recall_values]
try:
with open(recall_log_file, 'r') as f:
recall_log = json.load(f)
except:
recall_log = []
recall_log.append((epoch, val_recall, val_recall_clean))
with open(recall_log_file, 'w') as f:
json.dump(recall_log, f)
model.save_weights(os.path.join(checkpoint_dir, 'triplet_semihard_%d.keras'%epoch))
epoch += 1
| triplet_semihard_training.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: css
# language: python
# name: css
# ---
# +
import datetime
import statsmodels.formula.api as smf
import numpy as np
import pandas as pd
import polars as pl
import sqlite3
DATA_PATH = "../../data/users/"
recent_posts = DATA_PATH + "recent/recent-posts-batch-*.csv"
DB_PATH = DATA_PATH + "users.sqlite.db"
# -
# ## Combining all information into a dataset for regression
conn = sqlite3.connect(DB_PATH)
posts = pl.scan_csv(recent_posts).collect()
posts.to_pandas().to_sql("posts", conn, index=False)
# +
sql = """
SELECT
posts.post_id, posts.post_karma, posts.user_name,
users_cutoff.no_posts, users_cutoff.no_comments, users_cutoff.avg_post_karma,
users_cutoff.post_karma as total_post_karma, users_cutoff.longevity,
users.indirect_pg,
topics.topic
FROM posts
JOIN users_cutoff ON users_cutoff.user_name = posts.user_name
JOIN users ON users.user_name = users_cutoff.user_name
LEFT JOIN topics ON topics.id = posts.post_id
"""
joined = pd.read_sql(sql, conn)
# -
# ## Regression analysis
data = joined.drop(["post_id", "user_name"], axis=1)
data['topic'] = data['topic'].astype("category")
data = pd.get_dummies(data)
topic_cols = {"topic_" + str(float(i)) : "topic_" + str(i) for i in range(25)}
data = data.rename(topic_cols, axis=1)
# ## Log-based specification
#
# `'log(post_karma) ~ log(no_posts) + log(no_comments) + avg_post_karma + log(total_post_kmarma) + log(longevity) + topic'`
# +
formula = """np.log(post_karma + 0.001) ~ np.log(no_posts + 0.001) +
np.log(no_comments + 0.001) + avg_post_karma +
np.log(total_post_karma + 0.001) + np.log(longevity + 0.000) + np.log(indirect_pg)"""
formula = formula + " + " + " + ".join(topic_cols.values())
results = smf.ols(formula, data=data).fit()
print(results.summary())
# -
# ## Different model specifications
# ### Simple linear model as per Kilgo et al.
# `'post_karma ~ total_post_karma + longevity'`
# +
formula = 'post_karma ~ total_post_karma + longevity'
results = smf.ols(formula, data=data).fit()
print(results.summary())
| src/user-popularity/user_influence_regressions.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Implรฉmenter la classe arbre binaire
# > Cours NSI Terminale - Thรจme 1.
# - toc: true
# - badges: true
# - comments: false
# - categories: [python, NSI, Terminale, Structure_donnees, POO, TP]
# - image: images/nsi1.png
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "a481351352d92fb2e8971080f7725530", "grade": false, "grade_id": "cell-adf696006515d75e", "locked": true, "schema_version": 3, "solution": false, "task": false}
# Validez cette cellule pour importer graphviz
# Ce module permet de dessiner des arbres et des graphes
from graphviz import Digraph
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "29d54e09d95c4a2bcc6dfe41cc84b6ed", "grade": false, "grade_id": "cell-c9c5cedffbb0eb20", "locked": true, "schema_version": 3, "solution": false}
# Dans ce TP nous allons implรฉmenter une classe permettant de reprรฉsenter un arbre binaire.
#
# On va pour cela crรฉer un objet **Noeud** qui aura 3 propriรฉtรฉs (ou attributs) :
# - La propriรฉtรฉ **valeur** contiendra la valeur associรฉe au noeud.
# - Les propriรฉtรฉs **gauche** et **droit** seront les sous arbres gauche et droit.
#
# Les deux propriรฉtรฉs **gauche** et **droit** seront des instances de la classe **Noeud**. Si il n'y a pas de sous arbre gauche ou droit, on indiquera la valeur **None** dans les propriรฉtรฉs correspondantes.
#
#
# Dans notre classe **Noeud**, nous crรฉerons 3 mรฉthodes :
# - La mรฉthode **est_feuille()** renverra un boulรฉen selon que l'objet est une feuille ou non.
# - La mรฉthode **cree_feuille_gauche()** prend en paramรจtre une valeur et crรฉe une feuille ร gauche dont la valeur est passรฉe en paramรจtres.
# - La mรฉthode **cree_feuille_droite()** est construite sur le mรชme modรจle que **cree_feuille_gauche()**.
#
# ## Exemple d'utilisation de la classe Noeud
#
# En supposant la classe **Noeud** crรฉรฉe, voici comment on l'utilise pour crรฉer cet arbre
# 
# ```python
# arbre = Noeud("A")
# sous_arbre_gauche = arbre.cree_fils_gauche("B")
# sous_arbre_gauche.cree_fils_gauche("D")
# arbre.cree_fils_droit("C")
#
# # Quelques vรฉrifications possibles
# print(arbre.est_feuille())
# print(arbre.droit.est_feuille())
# print(arbre.gauche.valeur)
# # Affiche False True B
# ```
# + deletable=false nbgrader={"cell_type": "code", "checksum": "01e3f14977dffd5eec876121d3846169", "grade": false, "grade_id": "cell-b31cbad2840f3f42", "locked": false, "schema_version": 3, "solution": true, "task": false}
class Noeud():
# la mรฉthode __repr__ dรฉfinit ce qui sera affichรฉ
# lorsqu'on tapera l'objet dans Jupyter ou un terminal
# Ici, on affiche juste la valeur du noeud
def __repr__(self):
return str(self.valeur)
# Codez ici les mรฉthodes demandรฉes
# YOUR CODE HERE
raise NotImplementedError()
# -
# Testez ici les mรฉthodes de votre classe
a = Noeud(2)
a
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "d3076cc5dbd33b7a22cc79471ed2b44c", "grade": true, "grade_id": "cell-eee2cb758a9af1f2", "locked": true, "points": 1, "schema_version": 3, "solution": false}
# Tester l'exemple de dรฉpart
racine = Noeud("A")
sous_arbre_gauche = racine.cree_fils_gauche("B")
sous_arbre_gauche.cree_fils_gauche("D")
racine.cree_fils_droit("C")
assert not racine.est_feuille()
assert racine.droit.est_feuille()
assert racine.gauche.valeur == "B"
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "f21b8facb30deab73fc0eef315e319aa", "grade": false, "grade_id": "cell-de66d8305c8373b0", "locked": true, "schema_version": 3, "solution": false, "task": false}
# ## Pour aller plus loin
#
# On peut complรฉter cette classe **Noeud** par une nouvelle classe dรฉcrivant un objet **Arbrebin**. Un arbre va contenir le **Noeud** racine ainsi que des mรฉthodes permettant l'affichage de l'arbre ou appliquant des algorithmes sur cet arbre.
#
# Nous verrons un peu plus tard dans l'annรฉe quelques uns de ces algorithmes. Nรฉanmoins, pour vous donner un aperรงu, voici une premiรจre รฉbauche de la classe **Arbrebin** qui nous sera utile pour visualiser facilement les arbres sur lesquels nous travaillerons.
#
# Dans un premier temps, il n'est pas strictement nรฉcessaire de comprendre les dรฉtails du fonctionnement de la mรฉthode **show** car celle-ci fait appel ร de la *rรฉcursivitรฉ* qui sera รฉtudiรฉe un peu plus tard.
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "75e9e116841ced907048b5ae1f75cbe7", "grade": false, "grade_id": "cell-bbbe2da25e6200c1", "locked": true, "schema_version": 3, "solution": false, "task": false}
class Arbrebin:
"""Reprรฉsente un objet arbre binaire
- Propriรฉtรฉs :
* racine : objet de type Noeud dรฉsignant la racine de l'arbre
- Mรฉthodes :
* show() : reprรฉsentation graphique de l'arbre ร l'aide de graphviz
"""
def __init__(self, racine):
self.racine = racine
def show(self):
"""Renvoie un objet graphviz pour la visualisation graphique de l'arbre"""
def representation(dot, noeud, aretes):
# Ajoute la reprรฉsentation du noeud ร la reprรฉsentation dot de l'arbre
if noeud is not None:
dot.node(str(id(noeud)), str(noeud.valeur))
# Appel rรฉcursif de la fonction representation
if noeud.gauche is not None:
representation(dot, noeud.gauche, aretes)
aretes.append((str(id(noeud)) , str(id(noeud.gauche))))
if noeud.droit is not None:
representation(dot, noeud.droit, aretes)
aretes.append((str(id(noeud)) , str(id(noeud.droit))))
dot = Digraph(comment="Arbre binaire", format='svg')
aretes = []
representation(dot, self.racine, aretes)
dot.edges(aretes)
return dot
# -
arbre = Arbrebin(racine)
arbre.show()
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "1c2a01b3a3f33ad3952eb1e4e9ecc713", "grade": false, "grade_id": "cell-818c401cf1271819", "locked": true, "schema_version": 3, "solution": false}
# ## A vous de jouer
#
# A prรฉsent, vous utiliserez la classe **Noeud** et **Arbrebin** et les mรฉthodes que vous avez dรฉveloppรฉes pour reprรฉsenter l'arbre suivant dans la variable `expr`
# 
#
# Les opรฉrations seront reprรฉsentรฉes par des chaรฎnes de caractรจres. Les feuilles seront des entiers.
# + deletable=false nbgrader={"cell_type": "code", "checksum": "64a0eb4c96db1882d9e6ee9464c396cf", "grade": false, "grade_id": "cell-506da61b6d6152d2", "locked": false, "schema_version": 3, "solution": true}
# YOUR CODE HERE
raise NotImplementedError()
expr = Arbrebin(racine)
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "674737bc3e96616285bd6bc1120f3bbe", "grade": true, "grade_id": "cell-012eb21015157518", "locked": true, "points": 2, "schema_version": 3, "solution": false}
# Validation de la rรฉponse
assert racine.valeur == "+"
assert racine.droit.valeur == 1
expr.show()
# -
# Afficher le sous arbre gauche :
Arbrebin(racine.gauche).show()
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "190d270e75d3becf02b3bef0db88a3ac", "grade": false, "grade_id": "cell-8cad58a94eb47ea7", "locked": true, "schema_version": 3, "solution": false, "task": false}
# # Conclusion
#
# Nous en resterons la pour le moment. Nous reviendrons sur les arbres plusieurs fois au cours de l'annรฉe car cette structure permet de mettre en oeuvre des algorithmes intรฉressants. Nous complรจterons donc notre classe arbre au fur ร mesure de la progression de nos conaissance, en particulier lorsque nous รฉtudierons la rรฉcursivitรฉ.
# -
| _notebooks/2020-08-02-nsi_t_poo_arbre.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import tensorflow as tf
import gin
mol = gin.i_o.from_smiles.to_mol('CC')
mol = gin.deterministic.hydrogen.add_hydrogen(mol)
atoms, adjacency_map = mol
gin.deterministic.mm.alkane_energy.alkane_energy(atoms, adjacency_map, tf.zeros((1, 8, 3)))
class GraphConv(tf.keras.Model):
""" Spectral graph convolution.
https://arxiv.org/pdf/1609.02907.pdf
"""
def __init__(self, units=64, depth=10):
super(GraphConv, self).__init__()
self.d0 = tf.keras.layers.Dense(
units=units,
activation='tanh')
self.d1 = tf.keras.layers.Dense(
units=units,
activation='tanh')
self.d2 = tf.keras.layers.Dense(
units=units,
activation='tanh')
self.depth=depth
def call(self, atoms, adjacency_map):
a = tf.math.add(
adjacency_map,
tf.transpose(
adjacency_map))
a_tilde = tf.math.add(
a,
tf.eye(
tf.shape(a)[0]))
d_tilde_n_1_2 = tf.linalg.diag(
tf.math.pow(
tf.reduce_sum(
a_tilde,
axis=0),
tf.constant(
-0.5,
dtype=tf.float32)))
x = tf.matmul(
tf.matmul(
d_tilde_n_1_2,
a),
d_tilde_n_1_2)
return self.d2(
tf.matmul(
x,
self.d1(
tf.matmul(
x,
self.d0(
tf.matmul(
x,
tf.one_hot(
atoms,
self.depth)))))))
# +
class GraphFlow(tf.keras.Model):
""" Graph Flow model.
"""
def __init__(
self,
units=64,
depth=3,
max_degree=4):
super(GraphFlow, self).__init__()
self.units = units
self.depth = depth
self.gru_xyz = tf.keras.layers.GRU(units=units)
self.gru_graph = tf.keras.layers.GRU(
units=units,
return_sequences=True,
return_states=True)
for degree in range(1, max_degree+1):
for existing_degree in range(degree):
setattr(
self,
'd_1_' + str(degree) + '_' + str(existing_degree),
tf.keras.layers.Dense(
depth * (3 * (degree - existing_degree)) ** 2))
setattr(
self,
'd_0_' + str(degree) + '_' + str(existing_degree),
tf.keras.layers.Dense(
units,
activation='tanh'))
@staticmethod
def gen_child_xyz(
z,
degree,
existing_degree,
parent_xyz, # (3, )
parnet_h_gru_graph, # (d_h, )
parnet_h_gru_xyz, # (d_h, )
other_child_xyz, # (n_child, 3)
other_child_h_gru_graph, # (n_child, d_h),
other_child_h_gru_xyz, # (n_child, d_h),
global_h_gru,
):
h = tf.reshape(
tf.concat(
[
parent_xyz,
parent_h_gru_graph,
parnet_h_gru_xyz,
tf.reshape(other_child_xyz, [-1]),
tf.reshape(other_child_xyz - parent_xyz, [-1]),
tf.reshape(other_child_h_gru_graph, [-1]),
tf.reshape(other_child_h_gru_xyz, [-1]),
global_gru
],
axis=0),
[1, -1])
w = tf.reshape(
getattr(
self,
'd_1_' + str(degree) + '_' + str(existing_degree))(
getattr(
self,
'd_0_' + str(degree) + '_' + str(existing_degree))(
h)),
[-1, 3 * (degree - existing_degree), 3 * (degree - existing_degree)])
# -
graph_flow = GraphFlow()
| lime/scripts/graph_boltzmann_generator/200124_yuanqing_graph_boltzmann_generator.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# +
dataset = pd.read_csv('studentscores.csv')
X = dataset.iloc[:, :1].values
Y = dataset.iloc[:, 1].values
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)
# -
regressor = LinearRegression()
regressor = regressor.fit(X_train, Y_train)
Y_pred = regressor.predict(X_test)
plt.scatter(X_train , Y_train, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.scatter(X_test, Y_test, color = 'red')
plt.plot(X_test, Y_pred, color = 'blue')
| myCode/Day2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import re
import os
import json
import time
def get_text(text):
text = re.sub('\n+', ' ', text.strip())
text = re.sub('\r+', ' ', text.strip())
text = ' '.join(map(lambda x: x.strip(), text.strip().split('\r\n')))
clean_text, start = '', 0
while text:
text = text.split('<', 1)
clean_text += text[0]
if len(text) < 2:
break
tmp = text[1].split('>', 1)
if len(tmp) < 2:
break
text = tmp[1]
clean_text = re.sub(' +', ' ', clean_text)
clean_text = unicode(clean_text, errors='ignore')
return clean_text
def parse_item(filename):
filetype = filename.split('/')[-1]
date = ''.join(filename.split('/evolution/')[-1].split('/')[0].split('-'))
if filetype == 'feedback' or filetype == 'return-policy':
itemID = date + filename.split('/')[-2]
else:
itemID = date + filename.split('/')[-1]
# filename='/media/intel/m2/evolution/2014-06-04/listing/12030'
with open(filename) as fp:
content = fp.read()
if (not content) or content.find('Error in exception handler') >= 0:
return None
title, content = content.split('<title>')[1].split('</title>')
title = get_text(title)
if title == 'Evolution :: Login':
return None
tmp = content.split('>Home</a></li> <li><a')
if len(tmp) == 1:
return None
cat, content = tmp[1].split('>', 1)[1].split('<', 1)
tmp = content.split('<a class="thumbnail" href="', 1)
if len(tmp) == 1:
return None
tmp = tmp[1].split('"', 1)
if len(tmp) == 1:
return None
img_path, content = tmp
img_path = None if 'none' in img_path.split('/') else img_path.split('/evolution/')[-1]
if img_path is not None:
img_path = img_path.split('.onion/')[-1]
if date > '20140809':
tmp = content.split('<p>By <a')
if len(tmp) == 1:
return None
seller, content = tmp[1].split('>', 1)[1].split('</a>', 1)
else:
tmp = content.split('<div class="seller-info text-muted">Seller:')
if len(tmp) == 1:
return None
seller, content = tmp[1].split('</a>', 1)
seller = get_text(seller)
tmp = content.split('>Level', 1)
if len(tmp) == 1:
item_sold = None
else:
item_sold, content = tmp[1].split('(', 1)[1].split(')', 1)
item_sold = int(item_sold)
tmp = content.split('>BTC ', 1)
if len(tmp) == 1:
price_btc = None
else:
price_btc, content = tmp[1].split('<', 1)
price_btc = float(price_btc)
if date > '20140809':
tmp = content.split('>Ships From<')
if len(tmp) == 1:
ship_from = None
else:
ship_from, content = tmp[1].split('<', 1)[1].split('<', 1)
# print ship_from
ship_from = get_text('<' + ship_from)
if len(content.split('>Description<', 1)) > 1:
tmp = content.split('>Description<', 1)[1].split('>', 1)[1].split('</div>', 1)
if len(tmp) == 1:
raw_text = tmp[0]
else:
raw_text, content = tmp
# return raw_text
tmp = raw_text.split('>Ships To<')
if len(tmp) == 1:
text = get_text(tmp[0])
else:
text = get_text(tmp[0] + '>')
text = text.strip()
else:
text = None
if date <= '20140809':
tmp = content.split('>Ships From<')
if len(tmp) == 1:
ship_from = None
else:
ship_from, content = tmp[1].split('<', 1)[1].split('<', 1)
# print ship_from
ship_from = get_text('<' + ship_from)
iteminfo = {}
iteminfo['title'] = title
iteminfo['itemID'] = itemID
iteminfo['btc_price'] = price_btc
iteminfo['cat'] = cat
iteminfo['description'] = text
iteminfo['seller'] = seller
iteminfo['seller_dealmade'] = item_sold
iteminfo['seller_location'] = ship_from
iteminfo['date'] = date
iteminfo['img'] = img_path
return iteminfo
# -
root_path = '/media/intel/m2/evolution/'
item = {}
error_count = 0
def analyze(path):
# print path
global error_count
webpage_folder_path = os.path.join(path, 'listing')
if not os.path.isdir(webpage_folder_path):
return None
filenames = map(lambda wp: os.path.join(path, 'listing', wp),
os.listdir(webpage_folder_path))
for filename in filenames:
try:
if not os.path.isfile(filename):
filename = os.path.join(filename, 'feedback')
if not os.path.isfile(filename):
filename = filename.replace('feedback', 'return-policy')
parse_res = parse_item(filename)
if parse_res is not None:
item[filename] = parse_res
except:
print filename
error_count += 1
if error_count == 10000:
break
return 1
paths = [os.path.join(root_path, x) for x in os.listdir(root_path)]
paths = sorted(paths)
time0 = time.time()
for path in paths:
if os.path.isdir(path):
analyze(path)
if error_count == 10000:
break
print time.time() - time0
len(item)
with open('evolution.json', 'w') as fp:
json.dump(item, fp)
parse_item('/media/intel/m2/evolution/2014-10-04/listing/41764')
parse_item('/media/intel/m2/evolution/2014-07-28/listing/9767')
parse_item('/media/intel/m2/evolution/2014-07-26/listing/22354/feedback')
parse_item('/media/intel/m2/evolution/2014-06-24/listing/7678')
parse_item('/media/intel/m2/evolution/2014-01-21/listing/69')
parse_item('/media/intel/m2/evolution/2015-01-10/listing/71712/feedback')
parse_item('/media/intel/m2/evolution/2014-01-21/listing/15')
import pandas as pd
import re
import os
import json
import time
from shutil import copy2
import shutil
# +
data = pd.read_json('evolution.json', orient='index')
len(data)
# -
len(data.seller.unique())
# +
df_unique = data.drop_duplicates(['seller', 'title'])
df_unique = df_unique[df_unique.img.notnull()]
df_unique = df_unique.sort_index()
df_unique['itemID'] = df_unique.itemID.astype(int)
df_unique = df_unique.drop_duplicates('itemID')
len(df_unique)
# -
f_date = lambda x: x[:4] + '-' + x[4:6] + '-' + x[6:]
df_unique['date'] = df_unique.date.astype(str).apply(f_date)
root_path = '/media/intel/m2/evolution/'
df_unique['image_location'] = root_path + df_unique.date + '/' + df_unique.img
f_path = lambda x: '/'.join(x.split('/')[:-2])
df_unique['image_location'] = df_unique.image_location.apply(f_path)
# +
seller_name_list = list(df_unique.seller)
image_location = list(df_unique.image_location)
itemID = list(df_unique.itemID.astype(str))
# +
# import collections
# print [item for item, count in collections.Counter(itemID).items() if count > 1]
# -
target_path = '/media/intel/m2/imgEvo'
try:
os.mkdir(target_path)
except:
pass
seller_paths = [os.path.join(target_path, re.sub('[\W_]+', '00', x)) for x in seller_name_list]
def image_seller_path(itemID, image_location, seller_path):
ori_tar_pair = []
img_folder_name = [x for x in os.listdir(image_location) if x != 'none']
img_folder_path = [os.path.join(image_location, x) for x in img_folder_name]
for i in range(len(img_folder_path)):
folder_path = img_folder_path[i]
if os.path.isfile(os.path.join(folder_path, 'large')):
oriname = 'large'
elif os.path.isfile(os.path.join(folder_path, 'large.jpg')):
oriname = 'large.jpg'
elif os.path.isfile(os.path.join(folder_path, 'tiny')):
oriname = 'tiny'
elif os.path.isfile(os.path.join(folder_path, 'tiny.jpg')):
oriname = 'tiny.jpg'
else:
oriname = ''
if oriname:
img_ori_path = os.path.join(folder_path, oriname)
img_tar_path = os.path.join(seller_path,
itemID + 'X' + img_folder_name[i]
+ oriname.split('.')[0])
ori_tar_pair.append([img_ori_path, img_tar_path])
return ori_tar_pair
time0 = time.time()
uniq_item_count = len(itemID)
img_count = 0
for i in xrange(uniq_item_count):
if not os.path.isdir(image_location[i]):
continue
if not os.path.isdir(seller_paths[i]):
os.makedirs(seller_paths[i])
ori_tar_cp_res = image_seller_path(itemID[i], image_location[i],
seller_paths[i])
for (img_ori_path, img_tar_path) in ori_tar_cp_res:
copy2(img_ori_path, img_tar_path)
img_count += 1
print time.time() - time0, img_count
import pandas as pd
import re
import os
import json
import time
from shutil import copy2
from shutil import copyfile
import shutil
from PIL import Image
# +
data = pd.read_json('evolution.json', orient='index', dtype={'itemID':str})
len(data)
# -
data['dayID'] = data.itemID.apply(lambda x: x[8:])
data = data[data.img.notnull()]
data = data.sort_index()
f_date = lambda x: x[:4] + '-' + x[4:6] + '-' + x[6:]
data['date'] = data.date.astype(str).apply(f_date)
root_path = '/media/intel/m2/evolution/'
data['image_location'] = root_path + data.date + '/' + data.img
f_path = lambda x: '/'.join(x.split('/')[:-2])
data['image_location'] = data.image_location.apply(f_path)
data2 = data.copy()
# ### seller identification
data2 = data2[data2.seller.notnull()]
# +
target_path = '/media/intel/m2/imgEvo'
try:
os.makedirs(target_path)
except:
pass
data2['seller_name'] = data2.seller.apply(lambda x: os.path.join(target_path, re.sub('[\W_]+', '00', x)))
valid_item_img = set()
for index, row in data2.iterrows():
img_f = row.image_location
if not os.path.isdir(img_f):
continue
for img_index in os.listdir(img_f):
if img_index == 'none':
continue
if (row.seller, row.title, row.dayID, img_index) not in valid_item_img:
if os.path.isfile(os.path.join(img_f, img_index, 'large')):
oriname = 'large'
elif os.path.isfile(os.path.join(img_f, img_index, 'large.jpg')):
oriname = 'large.jpg'
'''
elif os.path.isfile(os.path.join(img_f, img_index, 'tiny')):
oriname = 'tiny'
elif os.path.isfile(os.path.join(img_f, img_index, 'tiny.jpg')):
oriname = 'tiny.jpg'
'''
else:
continue
img_path = os.path.join(img_f, img_index, oriname)
try:
img = Image.open(img_path)
img.load()
img.close()
except IOError:
img.close()
continue
if not os.path.isdir(row.seller_name):
os.makedirs(row.seller_name)
tar_file = os.path.join(row.seller_name, img_f.split('/')[-1] + 'xxxx' + img_index)
i = 0
while os.path.isfile("%sxxxx%d.jpg" % (tar_file, i)):
i += 1
copyfile(img_path, "%sxxxx%d.jpg" % (tar_file, i))
valid_item_img.add((row.seller, row.title, row.dayID, img_index))
# -
# +
target_path = '/media/intel/m2/imgEvodedup'
try:
os.mkdir(target_path)
except:
pass
data2['seller_name'] = data2.seller.apply(lambda x: os.path.join(target_path, re.sub('[\W_]+', '00', x)))
for index, row in data2.iterrows():
img_f = row.image_location
if not os.path.isdir(img_f):
continue
for img_index in os.listdir(img_f):
if img_index == 'none':
continue
if os.path.isfile(os.path.join(img_f, img_index, 'large')):
oriname = 'large'
elif os.path.isfile(os.path.join(img_f, img_index, 'large.jpg')):
oriname = 'large.jpg'
'''
elif os.path.isfile(os.path.join(img_f, img_index, 'tiny')):
oriname = 'tiny'
elif os.path.isfile(os.path.join(img_f, img_index, 'tiny.jpg')):
oriname = 'tiny.jpg'
'''
else:
continue
img_path = os.path.join(img_f, img_index, oriname)
try:
img = Image.open(img_path)
img.load()
img.close()
except IOError:
img.close()
continue
if not os.path.isdir(row.seller_name):
os.makedirs(row.seller_name)
tar_file = os.path.join(row.seller_name, img_f.split('/')[-1] + 'xxxx' + img_index)
i = 0
while os.path.isfile("%sxxxx%d.jpg" % (tar_file, i)):
i += 1
copyfile(img_path, "%sxxxx%d.jpg" % (tar_file, i))
# -
import hashlib
def md5sum(filename, blocksize=65536):
hash = hashlib.md5()
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
hash.update(block)
return hash.hexdigest()
root_dir = '/media/intel/m2/imgEvodedup'
seller_name = [os.path.join(root_dir, x) for x in os.listdir(root_dir)]
for seller_folder in set(seller_name):
filenames = map(lambda x: os.path.join(seller_folder, x), os.listdir(seller_folder))
md5value = {}
for filename in filenames:
md5curr = md5sum(filename)
if md5curr in md5value:
os.remove(filename)
else:
md5value[md5curr] = filename
# ### category prediction
data3 = data.copy()
data3 = data3[data3.cat.notnull()]
data3.cat.unique()
# +
target_path = '/media/intel/m2/imgEvoCat'
try:
os.mkdir(target_path)
except:
pass
data3['cat_name'] = data3.cat.apply(lambda x: os.path.join(target_path, re.sub('[\W_]+', '00', x)))
for index, row in data3.iterrows():
img_f = row.image_location
if not os.path.isdir(img_f):
continue
for img_index in os.listdir(img_f):
if img_index == 'none':
continue
if os.path.isfile(os.path.join(img_f, img_index, 'large')):
oriname = 'large'
elif os.path.isfile(os.path.join(img_f, img_index, 'large.jpg')):
oriname = 'large.jpg'
'''
elif os.path.isfile(os.path.join(img_f, img_index, 'tiny')):
oriname = 'tiny'
elif os.path.isfile(os.path.join(img_f, img_index, 'tiny.jpg')):
oriname = 'tiny.jpg'
'''
else:
continue
img_path = os.path.join(img_f, img_index, oriname)
try:
img = Image.open(img_path)
img.load()
img.close()
except IOError:
img.close()
continue
if not os.path.isdir(row.cat_name):
os.makedirs(row.cat_name)
tar_file = os.path.join(row.cat_name, img_f.split('/')[-1] + 'xxxx' + img_index)
i = 0
while os.path.isfile("%sxxxx%d.jpg" % (tar_file, i)):
i += 1
copyfile(img_path, "%sxxxx%d.jpg" % (tar_file, i))
# -
import hashlib
def md5sum(filename, blocksize=65536):
hash = hashlib.md5()
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
hash.update(block)
return hash.hexdigest()
root_dir = '/media/intel/m2/imgEvoCat'
seller_name = [os.path.join(root_dir, x) for x in os.listdir(root_dir)]
for seller_folder in set(seller_name):
filenames = map(lambda x: os.path.join(seller_folder, x), os.listdir(seller_folder))
md5value = {}
for filename in filenames:
md5curr = md5sum(filename)
if md5curr in md5value:
os.remove(filename)
else:
md5value[md5curr] = filename
| parser/evolution/parser.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/ddodds42/DS-Unit-4-Sprint-3-Deep-Learning/blob/master/module1-rnn-and-lstm/DAVID_DODDS_DS_431_RNN_and_LSTM_Assignment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="m8IS5d9FY7LH" colab_type="text"
# <img align="left" src="https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png" width=200>
# <br></br>
# <br></br>
#
# ## *Data Science Unit 4 Sprint 3 Assignment 1*
#
# # Recurrent Neural Networks and Long Short Term Memory (LSTM)
#
# 
#
# It is said that [infinite monkeys typing for an infinite amount of time](https://en.wikipedia.org/wiki/Infinite_monkey_theorem) will eventually type, among other things, the complete works of Wiliam Shakespeare. Let's see if we can get there a bit faster, with the power of Recurrent Neural Networks and LSTM.
#
# This text file contains the complete works of Shakespeare: https://www.gutenberg.org/files/100/100-0.txt
#
# - [ ] Use it as training data for an RNN - you can keep it simple and train character level, and that is suggested as an initial approach.
#
# - [ ] Then, use that trained RNN to generate Shakespearean-ish text.
#
# - [ ] Your goal - a function that can take, as an argument, the size of text (e.g. number of characters or lines) to generate, and returns generated text of that size.
#
# - [ ] Note - Shakespeare wrote an awful lot. It's OK, especially initially, to sample/use smaller data and parameters, so you can have a tighter feedback loop when you're trying to get things running.
#
# - [ ] Then, once you've got a proof of concept - start pushing it more!
# + colab_type="code" id="Ltj1je1fp5rO" colab={}
from __future__ import print_function
from tensorflow.keras.callbacks import LambdaCallback, EarlyStopping
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.optimizers import RMSprop
import numpy as np
import random
import sys
import os
import pandas as pd
# + id="yQUJn_fuMq6m" colab_type="code" colab={}
import requests
# + id="HFGTdSP-ySx6" colab_type="code" colab={}
# from google.colab import files
# uploaded = files.upload()
# + id="MHjIkdLux9Ir" colab_type="code" colab={}
url = 'https://raw.githubusercontent.com/ddodds42/DS-Unit-4-Sprint-3-Deep-Learning/master/module1-rnn-and-lstm/spearshake.txt'
r = requests.get(url)
# + id="tOKo_U6nQqZp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 195} outputId="4d593a8a-bf78-495e-8ac0-02bd1dd19779"
spearshake = r.text
print(spearshake[:100])
# + id="cHmx1u3CBX-Y" colab_type="code" outputId="d1447fe1-bfe6-4640-fb96-d3552d053d7c" colab={"base_uri": "https://localhost:8080/", "height": 35}
type(spearshake)
# + id="xOkb-EAv32Kc" colab_type="code" outputId="ae65f7b5-5a7f-4535-a19e-afa4863688a0" colab={"base_uri": "https://localhost:8080/", "height": 35}
spearshake0 = spearshake.replace('\n',' ')
spearshake0 = spearshake0.replace('\r',' ')
spearshake0[:100]
# + id="9xFNo612L5oS" colab_type="code" outputId="76e3a2f4-a3ba-4bef-ab9a-d39d43d7c275" colab={"base_uri": "https://localhost:8080/", "height": 55}
spearshake0[:1000]
# + id="_pzpn0nJ22Ca" colab_type="code" colab={}
chars = list(set(spearshake0))
# + id="ibHkwJ7HyJ6j" colab_type="code" colab={}
char_int = {c:i for i, c in enumerate(chars)}
int_char = {i:c for i, c in enumerate(chars)}
# + id="HbMD1duVAg6D" colab_type="code" outputId="3d333461-5bfc-4403-f2fe-9ca75bd04e4a" colab={"base_uri": "https://localhost:8080/", "height": 35}
len(chars)
# + id="2eTbnHGP4sVN" colab_type="code" colab={}
maxlen = 40
step = 5
# + id="dv8DPEb7HZVP" colab_type="code" colab={}
encoded = [char_int[c] for c in spearshake0]
# + id="jTE35eO0HnWd" colab_type="code" colab={}
sequences = []
next_char = []
for i in range(0, len(encoded) - maxlen, step):
sequences.append(encoded[i : i+maxlen])
next_char.append(encoded[i+maxlen])
# + id="VnYu12u-JMov" colab_type="code" outputId="09140a55-9457-4dd7-a0ab-79951bbab8c6" colab={"base_uri": "https://localhost:8080/", "height": 35}
len(sequences)
# + id="qm1ZVEFtJQfg" colab_type="code" colab={}
X = np.zeros((len(sequences), maxlen, len(chars)), dtype=np.bool)
y = np.zeros((len(sequences), len(chars)), dtype=np.bool)
# + id="1eaQveorJ5Ca" colab_type="code" outputId="f93e6784-88a1-44cd-9500-1bc134425462" colab={"base_uri": "https://localhost:8080/", "height": 35}
X.shape, y.shape
# + id="XTWu08vsJ-gE" colab_type="code" colab={}
for i, sequence in enumerate(sequences):
for t, char in enumerate(sequence):
X[i,t,char] = 1
y[i, next_char[i]] = 1
# + id="dnDvFBTpKkon" colab_type="code" outputId="c8092804-3a9f-4640-854f-d0ade1e70888" colab={"base_uri": "https://localhost:8080/", "height": 35}
X.shape, y.shape
# + id="aeUlzwyFKqbJ" colab_type="code" outputId="ee654250-a8af-4b9e-9425-352a1c1c5535" colab={"base_uri": "https://localhost:8080/", "height": 35}
len(X[0,0])
# + id="aj1IssBtK2g9" colab_type="code" outputId="771a18f1-22eb-4d5a-93d2-8d7ba3ef4fc4" colab={"base_uri": "https://localhost:8080/", "height": 230}
X[0,0]
# + id="ca1IhVLYK5z0" colab_type="code" outputId="bfb96c8d-acd0-428c-e510-c7663f7a230f" colab={"base_uri": "https://localhost:8080/", "height": 35}
len(y[0])
# + id="ytMjckM9LAK2" colab_type="code" outputId="8cc76ee3-4a9f-4aa3-fd97-51e722eedf7d" colab={"base_uri": "https://localhost:8080/", "height": 230}
y[0]
# + id="405Llv5HLCVE" colab_type="code" colab={}
model = Sequential()
model.add(LSTM(128, input_shape=(maxlen, len(chars))))
model.add(Dense(len(chars), activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='nadam')
# + id="-5XDnI1DMASG" colab_type="code" colab={}
def sample(preds):
preds = np.asarray(preds).astype('float64')
preds = np.log(preds) / 1
exp_preds = np.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probas = np.random.multinomial(1, preds, 1)
return np.argmax(probas)
# + id="KtPYKhxiN1LX" colab_type="code" colab={}
def on_epoch_end(epoch, _):
print()
print('==== Generating text after Epoch %d' % epoch)
start_index = random.randint(0, len(spearshake0) - maxlen - 1)
generated = ''
sentence = spearshake0[start_index: start_index+maxlen]
generated += sentence
print('==== Generating with seed: "'+ sentence +'"')
sys.stdout.write(generated)
for i in range(400):
X_pred = np.zeros((1, maxlen, len(chars)))
for t, char in enumerate(sentence):
X_pred[0, t, char_int[char]] = 1
preds = model.predict(X_pred, verbose=0)[0]
next_index = sample(preds)
next_char = int_char[next_index]
sentence = sentence[1:]+next_char
sys.stdout.write(next_char)
sys.stdout.flush()
print()
print_callback = LambdaCallback(on_epoch_end=on_epoch_end)
# + id="kpwQeRMORM5P" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="698c84c3-f142-4976-f0a0-caf14faa70d6"
model.fit(
X, y, batch_size=256, epochs=10, #validation_split = 0.2,
callbacks=[print_callback]
)
# + id="R1YkmCvA9iVn" colab_type="code" colab={}
pred = model.predict(X[[0]])
# + id="2BKrmPc6A5m3" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 479} outputId="9e4acfd8-73ba-4ba1-f898-84053198a0d7"
pred[0]
# + id="sxWqUJ0_EomA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="d01d0280-c817-47c4-8ba5-8fe94541e251"
pred[0].sum()
# + id="tn4TkzTCSsT2" colab_type="code" colab={}
def joust(integer):
start_index = random.randint(0, len(spearshake0) - maxlen - 1)
generated = ''
sentence = spearshake0[start_index: start_index+maxlen]
seed_text = 'Seed text: "'+ sentence +'"'
# sys.stdout.write(generated)
for i in range(integer):
X_pred = np.zeros((1, maxlen, len(chars)))
for t, char in enumerate(sentence):
X_pred[0, t, char_int[char]] = 1
preds = model.predict(X_pred, verbose=0)[0]
next_index = sample(preds)
next_char = int_char[next_index]
generated += next_char
sentence = sentence[1:]+next_char
return print(seed_text, '\n', 'Shaken Speare:', generated)
# + id="wDzB5oXdIb03" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 52} outputId="c581aa9c-59dc-4206-a891-22abbeb2ad4c"
joust(40)
# + id="AFn7tO3bIiju" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 72} outputId="e2f51b29-92dc-49cf-a14e-35c60e8a6b9e"
joust(400)
# + [markdown] id="SRdv7XXI0lNA" colab_type="text"
# This text file contains the complete works of Shakespeare: https://www.gutenberg.org/files/100/100-0.txt
#
# - [x] Use it as training data for an RNN - you can keep it simple and train character level, and that is suggested as an initial approach.
#
# - [x] Then, use that trained RNN to generate Shakespearean-ish text.
#
# - [x] Your goal - a function that can take, as an argument, the size of text (e.g. number of characters or lines) to generate, and returns generated text of that size.
#
# - [x] Note - Shakespeare wrote an awful lot. It's OK, especially initially, to sample/use smaller data and parameters, so you can have a tighter feedback loop when you're trying to get things running.
#
# - [x] Then, once you've got a proof of concept - start pushing it more!
# + [markdown] colab_type="text" id="zE4a4O7Bp5x1"
# # Resources and Stretch Goals
# + [markdown] colab_type="text" id="uT3UV3gap9H6"
# ## Stretch goals:
# - Refine the training and generation of text to be able to ask for different genres/styles of Shakespearean text (e.g. plays versus sonnets)
# - Train a classification model that takes text and returns which work of Shakespeare it is most likely to be from
# - Make it more performant! Many possible routes here - lean on Keras, optimize the code, and/or use more resources (AWS, etc.)
# - Revisit the news example from class, and improve it - use categories or tags to refine the model/generation, or train a news classifier
# - Run on bigger, better data
#
# ## Resources:
# - [The Unreasonable Effectiveness of Recurrent Neural Networks](https://karpathy.github.io/2015/05/21/rnn-effectiveness/) - a seminal writeup demonstrating a simple but effective character-level NLP RNN
# - [Simple NumPy implementation of RNN](https://github.com/JY-Yoon/RNN-Implementation-using-NumPy/blob/master/RNN%20Implementation%20using%20NumPy.ipynb) - Python 3 version of the code from "Unreasonable Effectiveness"
# - [TensorFlow RNN Tutorial](https://github.com/tensorflow/models/tree/master/tutorials/rnn) - code for training a RNN on the Penn Tree Bank language dataset
# - [4 part tutorial on RNN](http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-1-introduction-to-rnns/) - relates RNN to the vanishing gradient problem, and provides example implementation
# - [RNN training tips and tricks](https://github.com/karpathy/char-rnn#tips-and-tricks) - some rules of thumb for parameterizing and training your RNN
| module1-rnn-and-lstm/DAVID_DODDS_DS_431_RNN_and_LSTM_Assignment.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + slideshow={"slide_type": "skip"}
from IPython.core.display import HTML
def css_styling():
styles = open("./styles/custom.css", "r").read()
return HTML(styles)
css_styling()
# + [markdown] slideshow={"slide_type": "slide"}
# ### BEFORE YOU DO ANYTHING...
# In the terminal:
# 1. Navigate to __inside__ your ILAS_Python repository.
# 2. __COMMIT__ any un-commited work on your personal computer.
# 3. __PULL__ any changes *you* have made using another computer.
# 4. __PULL__ textbook updates (including homework answers).
# + [markdown] slideshow={"slide_type": "slide"}
# 1. __Open Jupyter notebook:__ Start >> Programs (ใในใฆใฎใใญใฐใฉใ ) >> Programming >> Anaconda3 >> JupyterNotebook
# 1. __Navigate to the ILAS_Python folder__.
# 1. __Open today's seminar__ by clicking on 7_Numerical_computation_with_Numpy.
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Numerical Computation with Numpy</h1>
#
# <h1>Lesson Goal</h1>
#
# To make solutions to mathematical problems involving large data sets, multiple repeated computations and simultaneous solutions more efficient using programming.
#
# To acheive this we will cover an overview of some widely used tools from the Python Numpy package and related packages such as Matplotlib (plotting), Scipy (scientific computation) and Sympy (symbolic).
# + [markdown] slideshow={"slide_type": "slide"}
# ## Lesson Structure
# - The `array` data structure for numerical computation.
# - Subpackages
# - Array manipulation (independent study)
# - Introduction to plotting.
# - Mathematics with arrays
# - Mathematics with vectors
# - Mathematics with matrices
# - Useful matrix operations (independent study)
# - Simultaneous equations
# - Rates of change
# - Vectorised functions
# - Broadcasting
# - Reshaping and resizing
# + [markdown] slideshow={"slide_type": "slide"}
# ## Why are we studying this?
# Numerical computation is central to almost all scientific and engineering problems.
#
# There are programming languages specifically designed for numerical computation:
# - Fortran
# - MATLAB
#
# There are libraries dedicated to efficient numerical computations:
# - Numpy
# - Scipy
# - Sympy ...
# + [markdown] slideshow={"slide_type": "subslide"}
# NumPy (http://www.numpy.org/)
# - The most widely used Python library for numerical computations.
# - Large, extensive library of data structures and functions for numerical computation.
# - Useful for perfoming operation you will learn on mathematics-based courses.
#
#
# Scipy (https://www.scipy.org/)
# - Builds on Numpy, additional functionality
# - More specialised data structures and functions over NumPy.
#
# Matplotlib (https://matplotlib.org/)
# - A library for generating plots.
# - Complementary to numerical computation libraries.
# + [markdown] slideshow={"slide_type": "subslide"}
# If you are familiar with MATLAB, NumPy and SciPy provide similar functionality.
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# Last week we covered an introduction to some basic functions of Numpy.
#
# NumPy is a very extensive library.
#
# This seminar will:
# - Introduce some useful functions
# - Briefly discuss how to search for additional functions you may need.
#
# Use online resources to search for functions you need e.g. http://stackoverflow.com/.
#
#
# + [markdown] slideshow={"slide_type": "slide"}
# ## Importing the NumPy module
#
# To make NumPy functions and variables available to use in our program in our programs, we need to __import__ it using.
#
# `import numpy`
#
# We typically import all modules at the start of a program or notebook.
# + slideshow={"slide_type": "subslide"}
import numpy as np
# + [markdown] slideshow={"slide_type": "subslide"}
# The shortened name `np` is often used for numpy.
# + [markdown] slideshow={"slide_type": "subslide"}
# All Numpy functions can be called using `np.function()`.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Data Structure: The Numpy `array`
#
# ### Why do we need another data structure?
#
# Python lists hold 'arrays' of data.
#
# Lists are very flexible. e.g. holding mixed data type.
#
# There is a trade off between flexibility and performance e.g. speed.
# + [markdown] slideshow={"slide_type": "subslide"}
# Science engineering and mathematics problems often involve large amounts of data and numerous operations.
#
# We therefore use specialised functions and data structures for numerical computation.
# -
# + [markdown] slideshow={"slide_type": "slide"}
# ## Numpy array
#
# A numpy array is a grid of values, *all of the same type*.
# + [markdown] slideshow={"slide_type": "subslide"}
# To create an array we use the Numpy `np.array()` function.
#
# We can create an array in a number of ways.
#
# Let's start with something that is already familiar to you...
# + [markdown] slideshow={"slide_type": "subslide"}
# We can give a data structure (list, tuple) as an *argument* to convert it to a numpy array:
# + slideshow={"slide_type": "subslide"}
a = (4.0,)
b = np.array(a)
print(type(a))
print(type(b))
print(b.dtype)
# + [markdown] slideshow={"slide_type": "subslide"}
# The method `dtype` tells us the type of the data contained in the array.
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# __Note:__The data type can be optionally set by the user when creating the array. This can be useful when you need more control over how your data is stored in memory and on disk. Especially in cases where youโre working with large data, itโs good that you know to control the storage type.
#
# + slideshow={"slide_type": "subslide"}
c = [4.0, 5, 6.0]
d = np.array(c)
print(type(c))
print(type(d))
print(d.dtype)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Multi-dimensional arrays.
#
# Unlike the data types we have studied so far, arrays can have multiple dimensions.
#
# __`shape`:__ a *tuple* of *integers* giving the *size* of the array along each *dimension*.
#
# We define the dimensions of an array using square brackets
# + slideshow={"slide_type": "subslide"}
# 1-dimensional array
a = np.array([1, 2, 3])
# 2-dimensional array
b = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.shape)
print(b.shape)
# + slideshow={"slide_type": "subslide"}
# 2-dimensional array
c = np.array([[1, 2, 3]])
# 2-dimensional array
d = np.array([[1],
[4]])
print(c.shape)
print(d.shape)
# + slideshow={"slide_type": "subslide"}
# 3-dimensional array
c = np.array(
[[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]]])
print(c.shape)
c = np.array(
[[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]]])
print(c.shape)
# + slideshow={"slide_type": "subslide"}
# 3-dimensional array
c = np.array(
[[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]]])
# 4-dimensional array
d = np.array(
[[[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]]],
[[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]]]])
print(c.shape)
print(d.shape)
# + [markdown] slideshow={"slide_type": "slide"}
# <a name="CreatingArray"></a>
# ## Creating a numpy array.
#
# We don't always have to manually create the individual elements of an array.
#
# There are several other ways to do this.
#
# For example, if you donโt know what data you want to put in your array you can initialise it with placeholders and load the data you want to use later.
#
# + slideshow={"slide_type": "subslide"}
# Create an empty matrix
# The empty() function argument is the shape.
# Shape: tuple of integers giving the size along each dimension.
import numpy as np
x = np.empty((4))
print(x)
print()
x = np.empty((4,4))
print(x)
# + slideshow={"slide_type": "subslide"}
# Create an array of elements with the same value
# The full() function arguments are
# 1) Shape: tuple of integers giving the size along each dimension.
# 2) The constant value
y = np.full((1,1), 3)
print(y)
print(y.shape)
print()
y = np.full((2,2), 4)
print(y)
# + slideshow={"slide_type": "subslide"}
# Create a 1D array of evenly spaced values
# The arange() function arguments are the same as the range() function.
# Shape: tuple of integers giving the size along each dimension.
z = np.arange(5,10)
print(z)
print()
z = np.arange(5, 10, 2)
print(z)
# + slideshow={"slide_type": "subslide"}
# Create a 1D array of evenly spaced values
# The linspace() function arguments are
# The lower limit of the range of values
# The upper limit of the range of values (inclusive)
# The desired number of equally spaced values
z = np.linspace(-4, 4, 5)
print(z)
# + slideshow={"slide_type": "subslide"}
# Create an array of all zeros
# The zeros() function argument is the shape.
# Shape: tuple of integers giving the size along each dimension.
a = np.zeros(5)
print(a)
print()
a = np.zeros((2,2))
print(a)
# + slideshow={"slide_type": "subslide"}
# Create an array of all ones
b = np.ones(5)
print(b)
print()
b = np.ones((1, 4))
print(b)
# + slideshow={"slide_type": "subslide"}
# Create a constant array
# The second function argument is the constant value
c = np.full(6, 8)
print(c)
print()
c = np.full((2,2,2), 7)
print(c)
# + [markdown] slideshow={"slide_type": "slide"}
# <a name="Subpackages"></a>
# ## Subpackages
# Packages can also have subpackages.
#
# The `numpy` package has a subpackage called `random`.
#
# It contains functions to deal with random variables.
#
# If the `numpy` package is imported with `import numpy as np`, functions in the `random` subpackage can be called using `np.random.function()`.
# + slideshow={"slide_type": "subslide"}
# Create an array filled with random values in the range 0.0 to 1.0
e = np.random.rand(1)
print(e)
print()
e = np.random.rand(3,2,1)
print(e)
print()
e = np.random.random((2,2))
print(e)
# + slideshow={"slide_type": "subslide"}
# Create an array filled with random integer values
e = np.random.randint(1,24,size=(4,))
print(e)
# + slideshow={"slide_type": "subslide"}
# integer values between 4 and 16
e = np.random.randint(4, 16, size=(4,4))
print(e)
print()
# integer values between 1 and 8
e = np.random.randint(1, 8, size=(2, 2, 2))
print(e)
# + [markdown] slideshow={"slide_type": "slide"}
# <a id='Indexing'></a>
# ## Indexing into multi-dimensional arrays.
#
# We can index into an array exactly the same way as the other data structures we have studied.
# + slideshow={"slide_type": "subslide"}
x = np.array([1, 2, 3, 4, 5])
# Select a single element
print(x[4])
# Select elements from 2 to the end
print(x[2:])
# + [markdown] slideshow={"slide_type": "subslide"}
# For an n-dimensional (nD) matrix we need n index values to address an element or range of elements.
#
# Example: The index of a 2D array is specified with two values:
# - first the row index
# - then the column index.
#
# Note the order in which dimensions are addressed.
# + slideshow={"slide_type": "subslide"}
# 2 dimensional array
y = np.array([[1, 2, 3],
[4, 5, 6]])
# Select a single element
print(y[1,2])
# Select elements that are both in rows 1 to the end AND columns 0 to 2
print(y[1:, 0:2])
# + [markdown] slideshow={"slide_type": "subslide"}
# We can address elements by selecting a range with a step:
#
# For example the index:
#
# `z[0, 0:]`
#
# selects every element of row 0 in array, `z`
#
# The index:
#
# `z[0, 0::2]`
#
# selects every *other* element of row 0 in array, `z`
# + slideshow={"slide_type": "subslide"}
# 2 dimensional array
z = np.zeros((4,8))
# Change every element of row 0
z[0,0:] = 10
# Change every other element of row 1
z[1, 0::2] = 10
print(z)
# + slideshow={"slide_type": "subslide"}
z = np.zeros((4,8))
# Change the last 4 elements of row 2, in negative direction
# You MUST include a step to count in the negative direction
z[2, -1:-5:-1] = 10
# Change every other element of the last 6 elements of row 3
# in negative direction
z[3, -2:-7:-2] = 10
print(z)
# + slideshow={"slide_type": "subslide"}
# 3-dimensional array
c = np.array(
[[[2, 1, 4],
[2, 6, 8]],
[[0, 1, 5],
[7, 8, 9]]])
print(c[0, 1, 2])
# + [markdown] slideshow={"slide_type": "subslide"}
# Where we want to select all elements in one dimension we can use :
#
# __Exception__: If it is the last element , we can omit it.
# + slideshow={"slide_type": "subslide"}
print(c[0, 1])
print(c[0, :, 1])
# + [markdown] slideshow={"slide_type": "slide"}
# <a name="BooleanIndexing"></a>
# ### Boolean array indexing
#
# Recall that we can use *conditional operators* to check the value of a single variable against a condition.
#
# The value returned is a Boolean True or False value.
#
# + slideshow={"slide_type": "subslide"}
a = 4
print('a < 2:', a < 2)
print('a > 2:', a > 2)
# + [markdown] slideshow={"slide_type": "subslide"}
# If we instead use *conditional operators* to check the value of an array against a condition.
#
# The value returned is an *array* of Boolean True or False values.
# + slideshow={"slide_type": "subslide"}
a = np.array([[1,2],
[3, 4],
[5, 6]])
idx = a > 2
print(idx)
# + [markdown] slideshow={"slide_type": "subslide"}
# A particular elements of an array can be are specified by using a boolean array as an index.
#
# Only the values of the array where the boolean array is `True` are selected.
# + [markdown] slideshow={"slide_type": "subslide"}
# The varaible `idx` can therefore now be used as the index to select all elements greater than 2.
# + slideshow={"slide_type": "subslide"}
print(a[idx])
# + [markdown] slideshow={"slide_type": "subslide"}
# To do the whole process in a single step
# + slideshow={"slide_type": "subslide"}
print(a[a > 2])
# + [markdown] slideshow={"slide_type": "subslide"}
# To apply multiple conditions, use () parentheses to sperate different conditions.
#
# Use `&` for elementwise `and`.
#
# Use `|` for elementwise `or`.
# + slideshow={"slide_type": "subslide"}
x = np.array([[4, 2, 3, 1],
[2, 4, 2, 8],
[2, 3, 3, 27],
[4, 1, 4, 64]])
# elements of x that are greater then 2 AND less than 10
print(x[(2 < x) & (x < 10)])
# elements of x that are less then 2 OR greater than 10
print(x[(x < 2) | (x > 10)])
# + [markdown] slideshow={"slide_type": "subslide"}
# Multiple conditions can also be applied to a subsection of an array.
# <br>For example to select elements $>2$ and $<4$ in the first row of `x` only (`x[0]`):
# + slideshow={"slide_type": "subslide"}
x = np.array([[4, 2, 3, 1],
[2, 4, 2, 8],
[2, 3, 3, 27],
[4, 1, 4, 64]])
print(x[0][(2 < x[0]) & (x[0] < 4)])
# + [markdown] slideshow={"slide_type": "slide"}
# ## Iterating over multi-dimensional arrays.
# We can iterate over a 1D array in the same way as the data structures we have previously studied.
# + slideshow={"slide_type": "subslide"}
A = np.array([1, 2, 3, 4, 5])
# + slideshow={"slide_type": "subslide"}
for a in A:
print(a)
# + [markdown] slideshow={"slide_type": "subslide"}
# To loop through individual elements of a multi-dimensional array, we use a nested loop for each dimension of the array.
# + slideshow={"slide_type": "subslide"}
B = np.array([[1, 2, 3],
[4, 5, 6]])
for row in B:
print("-----")
for col in row:
print(col)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Manipulating arrays
# We can use many of the same operations to manipulate arrays as we use for lists.
#
# However, it is important to note a few subtle differences in how array manipulations behave.
# + slideshow={"slide_type": "subslide"}
# Length of an array
a = np.array([1, 3, 4, 17, 3, 21, 2, 12])
b = np.array([[1, 3, 4, 17],
[3, 21, 2, 12]])
print(len(a))
print(len(b))
# + [markdown] slideshow={"slide_type": "subslide"}
# Note the length is the length of the first dimension (e.g. indexing).
# + slideshow={"slide_type": "subslide"}
# Sort an array
a = np.array([1, 3, 4, 17, 3, 21, 2, 12])
b = np.array([[1, 3, 4, 17],
[3, 21, 2, 12]])
# The function sorted applies to 1D data structures only
print(sorted(a))
print(sorted(b[1]))
# The method sort() applies to arrays of any size
a.sort()
b.sort()
print(a)
print(b)
# + [markdown] slideshow={"slide_type": "subslide"}
# Arrays are *immutable* (unchangeable).
#
# Technically you cannot add or delete items of an array.
#
# However, you can make a *new* array (which may have the same name as the original array), with the values ammended as required:
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Appending Arrays
# Appending connects array-like (integer, list....) value to the *end* of the original array.
# + [markdown] slideshow={"slide_type": "subslide"}
# By default, 2D arrays are appended as if joining lists.
# The new array is a 1D array
# + slideshow={"slide_type": "subslide"}
# 2D array
a = np.array([[0], [1], [2]])
print(a)
print()
# 2D array
b = np.array([[3], [4]])
print(b)
print()
# 1D array
c = np.array([3, 4])
print(c)
print()
# integer
d = 1
print(d)
print(f"original 2D array shapes: a = {a.shape}, b = {b.shape}")
print()
X = np.append(a, b)
print(X)
print(f"new array shape: {X.shape}")
print()
X = np.append(b, d)
print(X)
print(f"new array shape: {X.shape}")
print()
X = np.append(c, d)
print(X)
print(f"new array shape: {X.shape}")
print()
# + [markdown] slideshow={"slide_type": "subslide"}
# The axis on which to append an array can be optionally specified.
#
# e.g. 2D array:
# - 0: columns
# - 1: rows
#
# The arrays must have the same shape, except in the dimension corresponding to the specified axis
# + slideshow={"slide_type": "subslide"}
# 2D array
a = np.array([[0], [1], [2]])
print(a)
print()
# 2D array
b = np.array([[3], [4]])
print(b)
print()
new2d = np.append(a, b, axis=0)
print(new2d)
print(f"new array shape: {new2d.shape}")
# + [markdown] slideshow={"slide_type": "subslide"}
# For example, in the cell above, if you change `axis=0` to `axis=1`,
# <br>you are trying to connect the side of `a` with length=3 to the side of `b` with length=2.
# + [markdown] slideshow={"slide_type": "subslide"}
# There are dedicated functions to simplify joining or merging arrays.
# <br>If you are interested to expeirment further with joiing arrays you can try out the following functions:
# - `np.concatenate()` : Joins a sequence of arrays along an existing axis.
# - `np.vstack()` or `np.r_[]`: Stacks arrays row-wise
# - `np.hstack()` : Stacks arrays horizontally
# - `np.column_stack()` or `np.c_[]` : Stacks arrays column-wise
# Refer to last week's seminar for how to inpterpret the function documentation.
# + [markdown] slideshow={"slide_type": "subslide"}
# It can also be useful to remove individual (single or multiple) elements.
#
# For example, the following expand the locations within the array that you can change beyond the location at the *end* of the array.
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Adding elements to an array
# + slideshow={"slide_type": "subslide"}
# Add items to an array
# The insert() function arguments are
# 1) The array to insert to
# 2) The index of the inserted element
# 3) The value of the inserted element
a = ([1, 2, 3])
a = np.insert(a, 1, 4)
print(a)
# + [markdown] slideshow={"slide_type": "subslide"}
# Notice that, again, the output is a 1D aray by default
# + slideshow={"slide_type": "subslide"}
# Add items to an array
b = np.array([[1, 1],
[2, 2],
[3, 3]])
print(f"original array shape: {b.shape}")
b = np.insert(b, 1, [4, 4])
print(b)
print(f"new array shape: {b.shape}")
# + [markdown] slideshow={"slide_type": "subslide"}
# To preserve the multi-dimensional structure of an array, we can specify the axis on which to insert an element or range of elements.
# <br> In the example below, a column is inserted at element 1 of axis 1.
# + slideshow={"slide_type": "subslide"}
# Add items to an array
b = np.array([[1, 1],
[2, 2],
[3, 3]])
b = np.insert(b, 1, [3, 2, 1], axis=1)
print(b)
# + [markdown] slideshow={"slide_type": "subslide"}
# Notice what happens when we insert a *single* value on a specified axis
# + slideshow={"slide_type": "subslide"}
b = np.insert(b, 1, 4, axis=1)
print(b)
# + [markdown] slideshow={"slide_type": "subslide"}
# This behaviour is due to a very useful property called *broadcasting*.
# <br>We will study the rules governing broadcasting later in this seminar.
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Deleting items from an array
# + slideshow={"slide_type": "subslide"}
# Items are deleted from their position in a 1D array by default
z = np.array([1, 3, 4, 5, 6, 7, 8, 9])
z = np.delete(z, 3)
print(z)
z = np.delete(z, [0, 1, 2])
print(z)
# + slideshow={"slide_type": "subslide"}
# Again, axes to delete can be optionally specified:
z = np.array([[1, 3, 4, 5], [6, 7, 8, 9]])
print(z)
print()
z = np.delete(z, 3, axis=1)
print(z)
print()
z = np.delete(z, [0,1,2], axis=1)
print(z)
print()
# + [markdown] slideshow={"slide_type": "subslide"}
# <a name="Changing"></a>
# #### Changing items in an array
#
# + slideshow={"slide_type": "subslide"}
c = np.array([1, 2, 3])
c[1] = 4
print(c)
# + [markdown] slideshow={"slide_type": "slide"}
# <a id='Plotting'></a>
# ## Introduction to Plotting
# It is often useful to represent data visually.
#
# Matplotlib is a library for creating beautiful graphics.
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# First we will import the plotting part of `matplotlib`, renaming it `plt`.
#
# Second we will use a command which tells Python to show any graphs inside the Notebook(not in a separate window).
# -
import matplotlib.pyplot as plt
# %matplotlib inline
# + [markdown] slideshow={"slide_type": "subslide"}
# <a id='LinePlot'></a>
# ### A simple line plot
# It is very easy to generate simlpe plots from arrays or other data structures.
# + [markdown] slideshow={"slide_type": "subslide"}
# A single parameter is automatically plotted against the index of each element.
# -
x = np.array([1,7,2,3,3,4,5])
plt.plot(x)
# + [markdown] slideshow={"slide_type": "subslide"}
# To plot one parameter against another parameter:
# -
x = [1, 2, 5, 7, 12]
y = [3, 2, 0.7, 0.6, 0.1]
plt.plot(x, y)
# + [markdown] slideshow={"slide_type": "subslide"}
# <a id='ScatterPlot'></a>
# ### A scatter plot
# To plot a scatter plot of points instead of a connected line add a `formatstring`:
# -
x = [1, 2, 5, 7, 12]
y = [3, 2, 0.7, 0.6, 0.1]
plt.plot(x, y, 'o')
# + [markdown] slideshow={"slide_type": "slide"}
# ## Mathematics with arrays.
#
# Unlike lists, NumPy arrays support common arithmetic operations, such as addition of two arrays.
# + slideshow={"slide_type": "subslide"}
# To add the elements of two lists we need the Numpy function: add
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
c = np.add(a, b)
print(c)
# + [markdown] slideshow={"slide_type": "subslide"}
# To add the elements of two arrays we can just use regular arithmetic operators.
#
# The two arrays should have the same dimensions.
# +
a = np.array([1, 2, 3])
b = np.ones((1,3))
c = a + b
print(c)
# + [markdown] slideshow={"slide_type": "subslide"}
# Algebraic operations are appled *elementwise* to an array.
#
# This means the function is applied individually to each element in the list.
# +
a = np.array([1.0, 0.2, 1.2])
b = np.array([2.0, 0.1, 2.1])
print(a - b)
print(np.subtract(a, b))
# + slideshow={"slide_type": "subslide"}
a = np.array([[1.0, 0.2, 1],
[1.0, 0.2, 1]])
b = np.array([[2.0, 0.1, 2],
[1.0, 0.2, 1]])
# Elementwise multiplication of a and b
print(a * b)
print()
print(np.multiply(a, b))
print(),print()
# Elementwise division of a and b
print(a / b)
print()
print(np.divide(a, b))
# + [markdown] slideshow={"slide_type": "subslide"}
# Apply a mathematical function to a range of values.
#
# Example: Evaluate $y = x^4 - 16$ between $x=-10$ and $x=10$
# +
x = np.linspace(-10, 10, 100)
y = x**4 - 16
plt.plot(x, y)
# + slideshow={"slide_type": "subslide"}
x = np.linspace(-2*np.pi, 2*np.pi, 100)
y = np.cos(x)
plt.plot(x, y)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Mathematics with Vectors (1D arrays)
# 1D arrays are a useful ways to represent vectors.
#
# A vector is a quantity with a direction and a magnitude.
#
# Let's look at a previous example for computing the dot product of two vectors.
# + [markdown] slideshow={"slide_type": "subslide"}
# The dot product of two $n$-length-vectors:
# <br> $ \mathbf{A} = [A_1, A_2, ... A_n]$
# <br> $ \mathbf{B} = [B_1, B_2, ... B_n]$
#
# \begin{align}
# \mathbf{A} \cdot \mathbf{B} = \sum_{i=1}^n A_i B_i.
# \end{align}
# + [markdown] slideshow={"slide_type": "subslide"}
# We learnt to solve this very easily using a Python `for` loop.
#
# With each iteration of the loop we increase the value of `dot_product` (initial value = 0.0) by the product of `a` and `b`.
#
# ```python
# A = [1.0, 3.0, -5.0]
# B = [4.0, -2.0, -1.0]
#
# # Create a variable called dot_product with value, 0.
# dot_product = 0.0
#
# for a, b in zip(A, B):
# dot_product += a * b
#
# print(dot_product)
# ```
# + [markdown] slideshow={"slide_type": "subslide"}
# Numpy makes solving the dot product even easier.
#
# We can use the Numpy function `dot()`.
# <br>`dot()` can also takes lists as inputs.
#
# We can also use `@`
# <br>`@` does not work on lists or in Python 2
# + [markdown] slideshow={"slide_type": "subslide"}
# Example: Computing the dot product of two vectors.
# <img src="img/dot-product-diagram.gif" alt="Drawing" style="width: 300px;"/>
# + slideshow={"slide_type": "subslide"}
import numpy as np
A = [9, 2, 7]
B = [4, 8, 10]
print(np.dot(A,B))
A = np.array([9, 2, 7])
B = np.array([4, 8, 10])
print(np.dot(A,B))
print(A @ B)
# + [markdown] slideshow={"slide_type": "subslide"}
# __Try it yourself__
#
# In the cell below write a user-defined function that takes two lists and returns the dot product.
#
# *Hint: use the code from Seminar 4: Data Structures (shown above).*
#
# Use the magic function `%timeit` to compare the speed of the for loop with the Numpy `dot()` function for solving the dot product.
# +
# Write a function for the dot product of two vectors expressed as lists
def dot_product(A,B):
AB = 0
for a,b in zip(A,B):
AB += a*b
return AB
# Compare the speed of your function to the Numpy function
A = [9, 2, 7]
B = [4, 8, 10]
# %timeit dot_product(A,B)
# %timeit np.dot(A,B)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Mathematics with Matrices (2D arrays)
# If you have previously studied matrices, the operations in this section will be familiar.
#
# If you have not yet studied matrices, you may want to refer back to this section once matrices have been covered in your mathematics classes.
#
# Matrix operations will not be included in the exam.
# + [markdown] slideshow={"slide_type": "subslide"}
# 2D arrays are a convenient way to represents matrices.
#
# For example, the 2x3 matrix
#
# $$
# A =
# \begin{bmatrix}
# 3 & 5 & 7\\
# 2 & 4 & 6
# \end{bmatrix}
# $$
#
# can be represented as a 2D array.
# -
A = np.array([[3, 5, 7],
[2, 4, 6]])
print(A)
# + [markdown] slideshow={"slide_type": "subslide"}
# We can use shape to return the matrix dimensions.
# -
print(A.shape)
print(f"Number of rows is {A.shape[0]}, number of columns is {A.shape[1]}")
print(f"A is an {A.shape[0]} by {A.shape[1]} matrix")
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Matrix multiplication rules.
# If the number of __columns in A__
# <br>is the same as number of __rows in B__,
# <br>we can find the matrix product of $\mathbf{A}$ and $\mathbf{B}$.
# <br> $\mathbf{C} = \mathbf{A} \cdot \mathbf{B}$
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# For example:
# <br>$\mathbf{A}$ has 3 rows and __3 columns__
# <br>$\mathbf{B}$ has __3 rows__ and 1 column
# <br>($\mathbf{B}$ is a vector represented as a matrix)
#
# \begin{equation*}
# \underbrace{
# \begin{bmatrix}
# 1 & 2 & 3 \\
# 4 & 5 & 6 \\
# 7 & 8 & 9 \\
# \end{bmatrix}
# }_{\mathbf{A} \text{ 3 rows} \text{ 3 columns}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# 10 \\
# 20 \\
# 30 \\
# \end{bmatrix}
# }_{\mathbf{B} \text{ 3 rows} \text{ 1 column}}
# \end{equation*}
#
# So we can multiply them...
# + [markdown] slideshow={"slide_type": "subslide"}
# In matrix $\mathbf{C}$, the element in __row $i$__, __column $j$__
#
# is equal to the dot product of the $i$th __row__ of $\mathbf{A}$, $j$th __column__ of $\mathbf{B}$.m
# + [markdown] slideshow={"slide_type": "subslide"}
#
#
# \begin{equation*}
# \underbrace{
# \begin{bmatrix}
# \color{red}1 & \color{red}2 & \color{red}3 \\
# 4 & 5 & 6 \\
# 7 & 8 & 9 \\
# \end{bmatrix}
# }_{\mathbf{A} \text{ 3 rows} \text{ 3 columns}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# \color{red}{10} \\
# \color{red}{20} \\
# \color{red}{30} \\
# \end{bmatrix}
# }_{\mathbf{B} \text{ 3 rows} \text{ 1 column}}
# =\underbrace{
# \begin{bmatrix}
# \color{red}{1 \cdot 10 \quad + \quad 2 \cdot 20 \quad + \quad 3 \cdot 30} \\
# 4 \cdot 10 \quad + \quad 5 \cdot 20 \quad + \quad 6 \cdot 30 \\
# 7 \cdot 10 \quad + \quad 8 \cdot 20 \quad + \quad 9 \cdot 30 \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 3 rows} \text{ 1 column}}
# =\underbrace{
# \begin{bmatrix}
# \color{red}{140} \\
# 320 \\
# 500 \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 3 rows} \text{ 1 column1}}
# \end{equation*}
# + [markdown] slideshow={"slide_type": "subslide"}
# \begin{equation*}
# \underbrace{
# \begin{bmatrix}
# 1 & 2 & 3 \\
# \color{red}4 & \color{red}5 & \color{red}6 \\
# 7 & 8 & 9 \\
# \end{bmatrix}
# }_{\mathbf{A} \text{ 3 rows} \text{ 3 columns}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# \color{red}{10} \\
# \color{red}{20} \\
# \color{red}{30} \\
# \end{bmatrix}
# }_{\mathbf{B} \text{ 3 rows} \text{ 1 column}}
# =\underbrace{
# \begin{bmatrix}
# 1 \cdot 10 \quad + \quad 2 \cdot 20 \quad + \quad 3 \cdot 30 \\
# \color{red}{4 \cdot 10 \quad + \quad 5 \cdot 20 \quad + \quad 6 \cdot 30} \\
# 7 \cdot 10 \quad + \quad 8 \cdot 20 \quad + \quad 9 \cdot 30 \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 3 rows} \text{ 1 column}}
# =\underbrace{
# \begin{bmatrix}
# 140 \\
# \color{red}{320} \\
# 500 \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 3 rows} \text{ 1 column1}}
# \end{equation*}
# + [markdown] slideshow={"slide_type": "subslide"}
# \begin{equation*}
# \underbrace{
# \begin{bmatrix}
# 1 & 2 & 3 \\
# 4 & 5 & 6 \\
# \color{red}7 & \color{red}8 & \color{red}9 \\
# \end{bmatrix}
# }_{\mathbf{A} \text{ 3 rows} \text{ 3 columns}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# \color{red}{10} \\
# \color{red}{20} \\
# \color{red}{30} \\
# \end{bmatrix}
# }_{\mathbf{B} \text{ 3 rows} \text{ 1 column}}
# =\underbrace{
# \begin{bmatrix}
# 1 \cdot 10 \quad + \quad 2 \cdot 20 \quad + \quad 3 \cdot 30 \\
# 4 \cdot 10 \quad + \quad 5 \cdot 20 \quad + \quad 6 \cdot 30 \\
# \color{red}{7 \cdot 10 \quad + \quad 8 \cdot 20 \quad + \quad 9 \cdot 30} \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 3 rows} \text{ 1 column}}
# =\underbrace{
# \begin{bmatrix}
# 140 \\
# 320 \\
# \color{red}{500} \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 3 rows} \text{ 1 column1}}
# \end{equation*}
# + [markdown] slideshow={"slide_type": "subslide"}
# \begin{equation*}
# \underbrace{
# \begin{bmatrix}
# 1 & 2 & 3 \\
# 4 & 5 & 6 \\
# 7 & 8 & 9 \\
# \end{bmatrix}
# }_{\mathbf{A} \text{ 3 rows} \text{ 3 columns}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# 10 \\
# 20 \\
# 30 \\
# \end{bmatrix}
# }_{\mathbf{B} \text{ 3 rows} \text{ 1 column}}
# =\underbrace{
# \begin{bmatrix}
# 1 \cdot 10 \quad + \quad 2 \cdot 20 \quad + \quad 3 \cdot 30 \\
# 4 \cdot 10 \quad + \quad 5 \cdot 20 \quad + \quad 6 \cdot 30 \\
# 7 \cdot 10 \quad + \quad 8 \cdot 20 \quad + \quad 9 \cdot 30 \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 3 rows} \text{ 1 column}}
# =\underbrace{
# \begin{bmatrix}
# 140 \\
# 320 \\
# 500 \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 3 rows} \text{ 1 column1}}
# \end{equation*}
#
# Matrix $\mathbf{C}$ therefore has:
# - the same number of __rows__ as $\mathbf{A}$,
# - the same number of __columns__ as $\mathbf{B}$.
# + slideshow={"slide_type": "subslide"}
# In the equation above, vector B must be represented as a column vector
A = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# In Python, 1D arrays are ALWAYS represented horizontally
# This does not define the array as a row vector
B = np.array([10, 20, 30])
# For example, C is represented horizontally
C = np.dot(A,B)
print(C)
# + [markdown] slideshow={"slide_type": "subslide"}
# As an example, if $\mathbf{B}$ were a row vector:
#
# \begin{equation*}
# \underbrace{
# \begin{bmatrix}
# 1 & 2 & 3 \\
# 4 & 5 & 6 \\
# 7 & 8 & 9 \\
# \end{bmatrix}
# }_{\mathbf{A} \text{ 3 rows} \text{ 3 columns}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# 10 & 20 & 30 \\
# \end{bmatrix}
# }_{\mathbf{B} \text{ 1 row} \text{ 3 columns}}
# \end{equation*}
#
# We *cannot* find the dot product $\mathbf{B}\cdot\mathbf{A}$.
# <br>The number of columns in $\mathbf{A}$ __is not__ the same as number of rows in $\mathbf{B}$.
# + [markdown] slideshow={"slide_type": "subslide"}
# We can swap the order of $\mathbf{A}$ and $\mathbf{B}$.
# <br>The multiplication is now possible.
# <br>However, the outcome is different.
#
#
# \begin{equation*}
# \underbrace{
# \begin{bmatrix}
# 10 & 20 & 30 \\
# \end{bmatrix}
# }_{\mathbf{B} \text{ 1 row} \text{ 3 columns}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# \color{red}1 & \color{blue}2 & \color{green}3 \\
# \color{red}4 & \color{blue}5 & \color{green}6 \\
# \color{red}7 & \color{blue}8 & \color{green}9 \\
# \end{bmatrix}
# }_{\mathbf{A} \text{ 3 rows} \text{ 3 columns}}
# =\underbrace{
# \begin{bmatrix}
# \color{red}{10 \cdot 1 + 20 \cdot 4 + 30 \cdot 7} &
# \color{blue}{4 \cdot 10 + 5 \cdot 20 + 6 \cdot 30} &
# \color{green}{7 \cdot 10 + 8 \cdot 20 + 9 \cdot 30} \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 1 row} \text{ 3 columns}}
# =\underbrace{
# \begin{bmatrix}
# \color{red}{140} &
# \color{blue}{320} &
# \color{green}{500} \\
# \end{bmatrix}
# }_{\mathbf{C} \text{ 3 rows} \text{ 1 column1}}
# \end{equation*}
# + [markdown] slideshow={"slide_type": "subslide"}
# In Python, normal matrix multiplication rules apply to 2D arrays.
# <br>This holds even if the length of one of the dimensions of the 2D array is equal to 1.
#
#
# +
A = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 2D array
X = np.array([[10, 20, 30]])
# 2D array
Y = np.array([[10],
[20],
[30]])
print(np.dot(X,A)) #, print(np.dot(A, X))
print(np.dot(A, Y)) #, print(np.dot(Y, A))
# + [markdown] slideshow={"slide_type": "subslide"}
# However, the orientation with which 1D arrays are shown (always horizontal) does not impact their allowbale placement in an expression.
#
# Python will automatially treat the 1D as a column where appropriate.
# + slideshow={"slide_type": "-"}
A = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 1D array
Z = np.array([10, 20, 30])
print(np.dot(Z, A))
print(np.dot(A, Z))
# + [markdown] slideshow={"slide_type": "slide"}
# ### Useful Matrix Operations
# #### Inverse of a square matrix
# + slideshow={"slide_type": "subslide"}
A = np.array([[1,2],
[3, 4]])
Ainv = np.linalg.inv(A)
print(f"A = \n {A}")
print(f"Inverse of A = \n {Ainv}")
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Determinant of a square matrix
# +
A = np.array([[1,2],
[3, 4]])
Adet = np.linalg.det(A)
print(f"A = \n {A}")
print(f"Determinant of A = {round(Adet, 2)}")
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Transpose of a matrix
#
# - The columns of the transpose matrix are the rows of the original matrix.
# - The rows of the transopse matrix are the columns of the original matrix.
# +
a = np.zeros((2,4))
print(a)
print()
print(a.T)
print()
#or
print(np.transpose(a))
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Generate Identity Matrix
# +
I = np.eye(2)
print(I)
print()
I = np.eye(4)
print(I)
# + [markdown] slideshow={"slide_type": "slide"}
# <a id='SimultaneousEqtns'></a>
#
# ### Useful Matrix Applications: Solving Simultaneous Equations
#
# A mathematical problem that arises in a wide range of engineering applications; the simultaneous solution to a set of n linear equations with n unknown values.
#
# Matrices are a widely used and popular technique for solving this type of problem.
# + [markdown] slideshow={"slide_type": "subslide"}
# Solving problems of this __computationally__ is particularly useful where:
# - we need to solve a large number of equations simultaneously e.g.
# - the force distribution in a truss structure <img src="img/truss.gif" alt="Drawing" style="width: 300px;"/>
# - the electrical current flowing in and out of each node in a circuit.
# <img src="img/current_flow.png" alt="Drawing" style="width: 150px;"/>
# - we need to solve the equations over multiple steps<br>e.g. observing the progression of a system over time.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Systems of Equations Example: An Electrical Circuit
#
# In electrical systems, network theory is the study of how to solve circuit problems.
# <br>The voltage and current in a closed circuit obey two simple rules;
# - Kirchoff's current law (first law)
# - Kirchhoff's voltage law (second law)
# <img src="img/kirchhoffLaws.png" alt="Drawing" style="width: 300px;"/>
#
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Kichoff's Current Law
#
# The algebraic sum of ALL the currents entering and leaving a junction must be equal to zero.
#
# $\sum i_{in} - \sum i_{out} = 0 $
#
#
# <img src="img/kirchhoffCurrentLaw.png" alt="Drawing" style="width: 200px;"/>
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Kirchhoff's Voltage Law
# For a closed loop series path the algebraic sum of all the *voltages* and *voltage drops* around any closed loop in a circuit is equal to zero.
#
# $\sum E - \sum V = 0 $
#
# <img src="img/kirchhoffVoltageLaw.png" alt="Drawing" style="width: 200px;"/>
#
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Electrical Elements Obey Ohm's Law
# The current through a conductor (I, units amps) is the voltage measured across the conductor (V, units volts) divided by the resistance (R, units Ohms).
#
# $$V = IR$$
#
# + [markdown] slideshow={"slide_type": "subslide"}
# A Wheatstone bridge circuit is a very widely used circuit in scientific equipment.
#
# It is found in strain gauges, heart rate monitors, wind tunnels....etc.
#
# Fundamentally, it is used to measure resistance.
#
# <img src="img/Wheat4.png" alt="Drawing" style="width: 200px;"/>
# + [markdown] slideshow={"slide_type": "subslide"}
# A wheatstone bridge circuit has mutiple loops and nodes.
#
# <img src="img/Wheat1.png" alt="Drawing" style="width: 200px;"/>
#
# It has one voltage source, $E$.
#
# It has five resisters $R_1, R_2, R_3, R_4, R_5, R_6$.
#
# <br>
# *Let's say we want to find the current in each branch $i_{1-6}$...*
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# The circuit has:
# - 4 loops (A-D)
# - a nodes (a-d)
#
#
# <img src="img/Wheat2.png" alt="Drawing" style="width: 200px;"/>
#
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
#
# We can use Kirchhoff's laws and Ohm's law with $E$ and $R_{1-6}$.
#
# $\sum i_{in} - \sum i_{out} = 0 $
#
# $\sum E - \sum V = 0 $
#
# $V = IR$
#
# <img src="img/Wheat2.png" alt="Drawing" style="width: 200px;"/>
#
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# 6 unknown values ($i_{1-6}$), 6 simultaneous equations.
# <img src="img/Wheat3.png" alt="Drawing" style="width: 200px;"/>
#
# __Loop A:__ $R_1 i_1 + R_2 i_2 + R_5 i_5 = E$<br>
# __Loop B:__ $R_4 i_4 - R_5 i_5 + R_6 i_6 = 0$<br>
# __Loop C:__ $R_2 i_2 - R_3 i_3 + R_4 i_4 = 0$
#
# __Node a:__ $i_2 - i_4 - i_5 = 0$<br>
# __Node b:__ $i_1 - i_2 - i_3 = 0$<br>
# __Node c:__ $i_5 + i_6 - i_1 = 0$<br>
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# We can express these equations as matrices:
#
# \begin{equation*}
# \underbrace{
# \begin{bmatrix}
# R_1 & R_2 & 0 & 0 & R_5 & 0 \\
# 0 & 0 & 0 & R_4 & -R_5 & R_6 \\
# 0 & R_2 & -R_3 & R_4 & 0 & 0 \\
# 0 & 1 & 0 & -1 & -1 & 0 \\
# 1 & -1 & -1 & 0 & 0 & 0 \\
# -1 & 0 & 0 & 0 & 1 & 1 \\
# \end{bmatrix}
# }_{\mathbf{R}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# i_1 \\
# i_2 \\
# i_3 \\
# i_4 \\
# i_5 \\
# i_6 \\
# \end{bmatrix}
# }_{\mathbf{I}}
# =\underbrace{
# \begin{bmatrix}
# E \\
# 0 \\
# 0 \\
# 0 \\
# 0 \\
# 0 \\
# \end{bmatrix}
# }_{\mathbf{V}}
# \end{equation*}
# + slideshow={"slide_type": "subslide"}
# Let's assign some values to our known variables:
E = 5
R1, R2, R3, R4, R5, R6 = 300, 500, 1000, 500, 1000, 500
R = np.array([[R1, R2, 0, 0, R5, 0 ],
[0, 0, 0, R4, -R5, R6],
[0, R2, -R3, R4, 0, 0 ],
[0, 1, 0, -1, -1, 0 ],
[1, -1, -1, 0, 0, 0 ],
[-1, 0, 0, 0, 1, 1]])
V = np.array([E, 0, 0, 0, 0, 0])
# + [markdown] slideshow={"slide_type": "subslide"}
# We can find $\mathbf{I}$ by matrix multiplication:
# \begin{align*}
# \mathbf{R}\cdot\mathbf{I}&=\mathbf{V}\\
# \end{align*}
#
# but we have to rearrange the equation.
#
# \begin{align*}
# \mathbf{I} &=\frac{\mathbf{V}}{\mathbf{R}}\\
# &=\mathbf{R^{-1}}\cdot\mathbf{V}\\
# \end{align*}
#
# + slideshow={"slide_type": "subslide"}
R_inv = np.linalg.inv(R)
I = np.dot(R_inv, V)
print(I)
# + [markdown] slideshow={"slide_type": "subslide"}
# Numpy conveniently solves linear matrix equations of the form `ax = b` so we don't need to rearrange.
# + slideshow={"slide_type": "subslide"}
I = np.linalg.solve(R, V)
print(I)
# -
# You can check your answer by confirming that the dot product, $\mathbf{R}\cdot\mathbf{I}$ is equal to $\mathbf{V}$.
# + slideshow={"slide_type": "subslide"}
print(R @ I)
print(np.around(R @ I, 2))
# + [markdown] slideshow={"slide_type": "subslide"}
# This process is a fast and simple way to solve simultaneous linear equations, for example when compared to eilimination methods.
# + [markdown] slideshow={"slide_type": "slide"}
# <a id='DiffEqtns'></a>
#
# ### Systems of Equations Example: Rates of Change
# A well known problem concerns an imaginary country with three cities, A, B and C.
# <br>At the end of each year, a fraction, $n$ of the people must leave each city.
# <br>Half of the people leaving a city move to one of the two options, and half to the other.
#
# <img src="img/cities3.png" alt="Drawing" style="width: 400px;"/>
# + [markdown] slideshow={"slide_type": "subslide"}
# This gives us a system of simultaneous equations
#
# \begin{align*}
# \Delta A = \frac{Bn}{2} + \frac{Cn}{2} - An \\
# \Delta B = \frac{An}{2} + \frac{Cn}{2} - Bn\\
# \Delta C = \frac{An}{2} + \frac{Bn}{2} -Cn \\
# \end{align*}
#
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# Matrices are a convenient way to represent this problem.
# + [markdown] slideshow={"slide_type": "subslide"}
# \begin{equation*}
# \begin{bmatrix}
# \Delta A \\
# \Delta B \\
# \Delta C \\
# \end{bmatrix}
# =
# \underbrace{
# \begin{bmatrix}
# -n & \frac{n}{2} & \frac{n}{2} \\
# \frac{n}{2} & -n & \frac{n}{2} \\
# \frac{n}{2} & \frac{n}{2} & -n \\
# \end{bmatrix}
# }_{\mathbf{migration}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# A \\
# B \\
# C \\
# \end{bmatrix}
# }_{\mathbf{population}}
# \end{equation*}
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# Assigning values to $\mathbf{M}$ and $\mathbf{P}$.
# -
# \begin{equation*}
# \begin{bmatrix}
# \Delta a \\
# \Delta b \\
# \Delta c \\
# \end{bmatrix}
# =
# \underbrace{
# \begin{bmatrix}
# -0.2 & 0.1 & 0.1 \\
# 0.1 & -0.2 & 0.1 \\
# 0.1 & 0.1 & -0.2 \\
# \end{bmatrix}
# }_{\mathbf{M}}
# \cdot
# \underbrace{
# \begin{bmatrix}
# A \\
# B \\
# C \\
# \end{bmatrix}
# }_{\mathbf{P}}
# \end{equation*}
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# By solving the problem computationally, we can quickly solve multiple iterations.
#
# In the example below there are two functions.
#
# The first, `pop_change` computes the rate of change of the population.
#
# The second, `pop_plot`:
# - calls `pop_change` inside of it
# - generates a line plot showing the population change over time
# + slideshow={"slide_type": "subslide"}
# Initial population
P0 = np.array([190.0, 500.0, 30.0])
# Matrix migration or M
migration = np.full((3, 3), 0.01)
np.fill_diagonal(migration, -0.02)
def pop_change(P, M=migration):
"Computes the change in population of three cities"
return np.dot(P, M)
# + slideshow={"slide_type": "subslide"}
def pop_plot(iterations, population):
"Plots the population over the number of iterations specified"
# make 2D array to append values to a column for each city
record_pop = population.reshape((1,3))
for i in range(iterations):
# Increment population size
population = population + pop_change(population)
# Save the population data
record_pop = (np.append(record_pop,
population.reshape((1,3)), # make 2D array
axis = 0))
plt.plot(record_pop[:,0] , label="A")
plt.plot(record_pop[:,1] , label="B")
plt.plot(record_pop[:,2] , label="C")
plt.xlabel("Years")
plt.ylabel("Population")
plt.legend();
#plt.plot(record_pop)
#print(record_pop)
# + slideshow={"slide_type": "subslide"}
# Plot the change in the populations of the cities over time
pop_plot(iterations=120, population=P0)
print(f"total population = {np.sum(P0)}")
# + [markdown] slideshow={"slide_type": "subslide"}
# In the example above the array `migration` or `M` just describes the change in a quantity; the population of each city.
#
# When a change in quantity is measured against a change in __time__ it describes the rate of change or flow of that quantity.
# + [markdown] slideshow={"slide_type": "subslide"}
# Rates are expressed as differential equations: the change in one parameter in relation to a change in another parameter. e.g.
# - velocity = change in position / change in time
# - acceleration = change in velocity / change in time
# + [markdown] slideshow={"slide_type": "subslide"}
# The Scipy library has easy to use tools for estimating the solutions to systems of (or single) differential equations like the example we just looked at.
#
# The function `odeint` solves first order differential equations.
# + slideshow={"slide_type": "-"}
from scipy.integrate import odeint
# + [markdown] slideshow={"slide_type": "subslide"}
# The function `odeint` takes a user-defined function as an argument.
#
# This input function should simply define the derivative (e.g. rate of change) you want to solve.
#
# For example, a function to calculate the derivative:
#
# $\frac{dx}{dt} = t - x$
#
# with initial value $x(0) = 1$
#
# we can use:
# -
def dx_dt(x,t):
return t - x
# + [markdown] slideshow={"slide_type": "subslide"}
# Two additional arguments are needed:
# - the value(s) of t at which to evaluate x, starting with the initial value
# - the initial value
# - (if `dx_dt` takes any other argumemts they are entered as a tuple as the third argument)
# + slideshow={"slide_type": "subslide"}
ts = np.linspace(0,5,100) # the value(s) of t at which to evaluate x
x0 = 1.0 # the initial value
# odeint returns x at each value of t
xs = odeint(dx_dt, x0, ts)
# + [markdown] slideshow={"slide_type": "subslide"}
# The function `odeint` returns an nx1 array (2D column).
# <br>To plot the output we have to "flatten" it to a 1D array.
# + slideshow={"slide_type": "subslide"}
# The function
#print(xs)
xs = np.array(xs).flatten()
#print(xs)
# plot the function
plt.xlabel("x")
plt.ylabel("t")
plt.plot(ts, xs);
# + [markdown] slideshow={"slide_type": "subslide"}
# We can use `odeint` to solve mulitple ordinary differential equations simultaneously (systems of ODEs).
#
# In this case the value of each variable at the initial position should be input as a single data structure.
#
# The function should output the rate of change of each variable as a single list.
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# For example we can use `odeint` to solve the population problem from earlier.
#
# The function dP_dt is exactly the same as the function `change_pop` that we used earlier. The only difference is that `dP_dt` returns the individual rates of chnage of each population as a list.
# + slideshow={"slide_type": "subslide"}
migration = np.full((3, 3), 0.01)
np.fill_diagonal(migration, -0.02)
# Initial population
P0 = np.array([190.0, 500.0, 30.0])
# Time steps to evaluate
ts = np.arange(0, 150)
def dP_dt(P, t, M):
dP_dt = np.dot(P, M)
return [dP_dt[0],
dP_dt[1],
dP_dt[2]]
Ps = odeint(dP_dt, P0, ts, args=(migration,))
plt.plot(ts, Ps[:,0], label="A")
plt.plot(ts, Ps[:,1], label="B")
plt.plot(ts, Ps[:,2], label="C")
plt.xlabel("Time")
plt.ylabel("Population")
plt.legend();
# + [markdown] slideshow={"slide_type": "subslide"}
# For comparison, here is the original solution, generated using the user-defined `pop_plot`function.
# -
pop_init = np.array([190.0, 500.0, 30.0])
pop_plot(iterations=150, population=pop_init)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Curve Fitting
# When using functions to produce mathematical models of practical problems we often need to 'fit' the function to experimental data.
#
# Python has several tools to find the curve which best describes the data set.
# + [markdown] slideshow={"slide_type": "subslide"}
# An example of this might be the data read from a sensor during an experiment.
#
# In the experiment shown below, the bend in the arm is used to control the LED light.
#
# <img src="img/wearable_tech.png" alt="Drawing" style="width: 400px;"/>
# The sensor used to detect the bend in the arm is made from conductive paint.
#
# The resistance of the paint changes with the bend in the arm.
#
# This change in resistance is detected as a voltage.
#
# A microcontroller adjusts the light in repsonse to the voltage.
# + [markdown] slideshow={"slide_type": "subslide"}
# The circuit on which the sensor is based is very similar to the Wheatsone bridge circuit.
#
# When calibrating a sensor like this, we need to find a relationship between the bend in the arm and the change in resisitance.
#
# After that the voltage alone can be used to 'read' the bend in the arm.
# + [markdown] slideshow={"slide_type": "subslide"}
# This section will cover some useful Numpy features for curve fitting.
#
#
# + [markdown] slideshow={"slide_type": "slide"}
# ### Root mean square error (RMSE)
# One way to quantify the fit between data and a model is to compute the RMSE.
#
# __Error/residual:__ the difference between the observed value $y_i$ at $x$ and the modeled value $a(x_i)$
#
# $$
# \varepsilon_i = a(x_i) - y_i
# $$
# + [markdown] slideshow={"slide_type": "subslide"}
# For $N$ data points, the *sum* of the squared errors is
#
# $$S = \sum_{i=1}^{N}\varepsilon_i^2$$
#
# The RMSE $E$ is computed as
#
# $$E=\sqrt{\frac{1}{N}S}=\sqrt{\frac{1}{N}\sum{\varepsilon_i^2}}$$
# + [markdown] slideshow={"slide_type": "subslide"}
# The RMSE can be computed for any model and any data set as an indicator of the "goodness of fit".
#
# We will use it to assess the fit of the curves that we generate using Numpy.
#
# The optimisation approach that involves minimising the sum of the squared errors (minimising the RMSE) is often referred to as a *least squares* approach.
# + slideshow={"slide_type": "subslide"}
# Example data set
x = [0.000000000000000000e+00, 1.052631578947368363e+00, 2.105263157894736725e+00, 3.157894736842105310e+00,4.210526315789473450e+00, 5.263157894736841591e+00, 6.315789473684210620e+00,7.368421052631578760e+00,8.421052631578946901e+00,9.473684210526315042e+00,1.052631578947368318e+01,1.157894736842105132e+01,1.263157894736842124e+01,1.368421052631578938e+01,1.473684210526315752e+01, 1.578947368421052566e+01,1.684210526315789380e+01,1.789473684210526372e+01,1.894736842105263008e+01,2.000000000000000000e+01]
y = [7.445192947240600745e+01, 4.834835792411828947e+01, 6.873305436340778840e+01, 5.979576407972768948e+01,6.404530772390434379e+01,6.090548420541189500e+01, 7.157546008677115879e+01, 8.620253336570679892e+01, 1.138154622045899913e+02, 8.493639813028174501e+01, 9.783457330550828601e+01, 1.082064229481453594e+02, 1.063876210674365979e+02, 1.001971993955305038e+02, 1.061496321788094832e+02, 1.279575585921491836e+02, 1.556956405962417875e+02, 1.584164804859289859e+02, 1.753888794716459358e+02, 1.980941276403034124e+02]
x = np.array(x)
y = np.array(y)
# + [markdown] slideshow={"slide_type": "subslide"}
# <a id='FittingLinear'></a>
# ### Fitting a Linear Function
# A straight line can be fitted through a data set using the `linregress` function from `scipy.stats`.
#
#
# -
from scipy.stats import linregress
# + [markdown] slideshow={"slide_type": "subslide"}
# Example: `linregress(x, y)` returns the components of an equation of the form:
# $$
# y = mx + c
# $$
#
# It returns five values.
# <br>The first two are the gradient $m$ and y-intercept $c$ of the line.
# <br>The last three are statistical parameters that are outside of the scope of this class.
# +
m, c, r_value, p_value, std_err = linregress(x, y)
yfit = float(m) * x + c
# plot a scatter plot by setting 'o' as the marker
plt.plot(x, y, 'o', label='experiment data')
# plot the fitted linear function
plt.plot(x, yfit, label='fit');
plt.legend();
# + [markdown] slideshow={"slide_type": "subslide"}
# <a id='RMSE'></a>
#
# The "goodness of fit" than then be assessed by calculating the RMSE.
#
# Error, $\varepsilon_i = a(x_i) - y_i$
#
# RMSE, $E=\sqrt{\frac{1}{N}\sum{\varepsilon_i^2}}$
#
#
# + slideshow={"slide_type": "subslide"}
# error
e = (yfit - y)
# RMSE
rmse = np.sqrt(np.sum(e**2)/ len(y))
# + [markdown] slideshow={"slide_type": "subslide"}
# <a id='Title'></a>
# #### Adding a title
# We can then a title.
# +
plt.plot(x, y, 'o', label='experiment data')
plt.plot(x, yfit, label='fit')
plt.legend()
# print the RMSE as the title
plt.title('RMSE: '+str(rmse))
# + [markdown] slideshow={"slide_type": "subslide"}
# <a id='FittingPolynomial'></a>
# ### Fitting a polynomial function
# A polynomial curve can be fitted through a data set using the `polyfit` function from `numpy`.
#
# The function arguments are:
# - the two variables to analyse
# - the order of the polynomial
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# The function returns:
# <br>the coefficients of each term of the polynomial. <br> e.g. if we request a polynomial of order 2, we will have terms for, - x^2, x and x^0 and we should expect 3 return arguments.
# +
c, d, e = np.polyfit(x, y, 2)
f, g, h, i = np.polyfit(x, y, 3)
j, k, l, m, n = np.polyfit(x, y, 4)
# + [markdown] slideshow={"slide_type": "subslide"}
# The function `poly1D` can then be used to find the solution to y for all x, using the polynomial generated.
# +
yfit2 = np.poly1d([c, d, e])(x)
yfit3 = np.poly1d([f, g, h, i])(x)
yfit4 = np.poly1d([j, k, l, m, n])(x)
# Which produces the same output as
yfit2 = c*x**2 + d*x + e
yfit3 = f*x**3 + g*x**2 + h*x + i
yfit4 = j*x**4 + k*x**3 + l*x**2 + m*x + n
# + [markdown] slideshow={"slide_type": "subslide"}
# The RMSE can be found as before.
# <br>__NOTE__ It is neater to write a function to do this.
# -
# error
rmse2 = round(np.sqrt(np.sum((yfit2 - y)**2)/ len(y)), 2)
rmse3 = round(np.sqrt(np.sum((yfit3 - y)**2)/ len(y)), 2)
rmse4 = round(np.sqrt(np.sum((yfit4 - y)**2)/ len(y)), 2)
# + [markdown] slideshow={"slide_type": "subslide"}
# <a id='Legend'></a>
# #### Adding a legend
# We can add a legend to label each line on the graph.
# <br>Add a `label` when creating each plot.
# <br>Finally add the `legend` to the plot.
# <br>The argument `loc='best'` chooses the 'best' location for the legend to avoid obscuring your plotted data.
# + slideshow={"slide_type": "subslide"}
# plot a scatter plot by setting 'o' as the marker
plt.plot(x, y, 'o', label='experiment data')
# plot the fitted 2nd order function
plt.plot(x, yfit2, label= f'2nd order RMSE{rmse2}')
# plot the fitted 3rd order function
plt.plot(x, yfit3, label= f'3rd order RMSE{rmse3}')
# plot the fitted 4th order function
plt.plot(x, yfit4, label= f'4th order RMSE{rmse4}')
# add a legend
plt.legend(loc='best')
# + [markdown] slideshow={"slide_type": "subslide"}
# <a id='FittingArbitrary'></a>
# ### Fitting an arbitrary function
# There are many Python functions available for curve fitting.
#
# The function `curve_fit` can be used to fit a user-defined fuction.
#
# We first define a function that we want to fit.
#
# __Example 1__
# ```Python
# def linear(x, a, b):
# return a * x + b
# ```
# >`curve_fit(func, x, y)` will find values of `a` and `b` that fits the curve $y = ax + b$ to our data.
#
# + [markdown] slideshow={"slide_type": "subslide"}
# __Example 2__
# ```Python
# def exponential(x, a, b):
# y = a * np.exp(b*x)
# return y
# ```
# >`curve_fit(func, x, y)` will find values of `a` and `b` that fits the curve $y = a e^{bx}$ to our data.
#
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# `curve_fit` then returns two arguments:
# - an array with the optimised parameters
# - the covariance of the parameters (a statistical measure of accuracy)
# + slideshow={"slide_type": "subslide"}
from scipy.optimize import curve_fit
def exponential(x, a, b):
y = a * np.exp(b*x)
return y
opt, cov = curve_fit(exponential, x, y)
# value of x for all x investigated
yfit = exponential(x, *opt)
plt.plot(x, y, 'o', label='experiment data')
plt.plot(x, yfit, 'r', label='fit')
plt.legend(loc='best')
rmse = np.sqrt(np.sum((yfit - y) ** 2) / len(y))
plt.title('RMSE: '+str(rmse));
print(f"y = {round(opt[0],2)} * e**({round(opt[1],2)}*x)")
# + [markdown] slideshow={"slide_type": "slide"}
# <a name="Vectorising"></a>
#
# ## Vectorising Functions
#
# Numpy functions applied to a single array, will be performed on each element in the array.
#
# The function takes an array of values as an input argument.
# + slideshow={"slide_type": "-"}
print(np.sqrt(a))
print(a ** (1/2))
# + [markdown] slideshow={"slide_type": "subslide"}
# For example, we can apply trigonometric functions, elementwise, to arrays, lists and tuples.
# +
x = np.array([0.0, np.pi/2, np.pi, 3*np.pi/2])
y = [0.0, np.pi/2, np.pi, 3*np.pi/2]
z = (0.0, np.pi/2, np.pi, 3*np.pi/2)
print(np.sin(x))
print(np.cos(y))
print(np.tan(z))
# + [markdown] slideshow={"slide_type": "subslide"}
# An array of values does not work as an input for all functions.
# +
def func(x):
if x < 0:
f = 2 * x
else:
f = 3 * x
return f
x = np.array([2, -2])
# y = func(x) # Run this line after removing the # to see the error generated
# + [markdown] slideshow={"slide_type": "subslide"}
# This doesn't work because Python doesn't know what to do with the line
#
# `if x < 0`
#
# when `x` contains many values.
#
# For some values of `x` the `if` statement may be `True`, for others it may be `False`.
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# A simple way around this problem is to vectorise the function.
#
# We create a new function that is a *vectorized* form of the original function.
#
# The new function and can be called with an array as an argument.
# +
funcvec = np.vectorize(func)
print(funcvec(x))
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Functions as function arguments
# Functions that receive vectorised arguments are automatically applied to all elements of array inputs.
#
# This is better exlpained with an example.
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# Recall the function `is_positive` from Seminar 5: Functions
# + slideshow={"slide_type": "-"}
def is_positive(f, a):
"Checks if the function value f(x) is positive"
return f(a) > 0
# Apply is_positive to a non-vectorised function
print(is_positive(func, -3))
print()
# Apply is_positive to a vectorised function
print(x)
is_positive(funcvec, x)
# + [markdown] slideshow={"slide_type": "slide"}
# <a name="Broadcasting"></a>
# ## Broadcasting
#
# Another source of incompatibility that you are likely to encounter is in trying to use arrays with different shapes for arithmetic operations.
#
# For example, you have one array that larger and another array that is smaller.
# <br>You may want to use the smaller array multiple times to perform an operation (such as a sum, multiplication, etc.) on the larger array.
#
# This is achieved using the broadcasting mechanism.
#
# The arrays can be broadcast together if all dimensions of the arrays are *compatible*
#
# + [markdown] slideshow={"slide_type": "subslide"}
# ##### Dimensions are compatible when they are equal.
#
# Consider the example below. `x` and `y` are the same shape, so we can addd them.
# +
x = np.ones((3,4))
print(x.shape)
y = np.full((3,4), 4)
print(y.shape)
# Add `x` and `y`
x + y
# + [markdown] slideshow={"slide_type": "subslide"}
# ##### Dimensions are compatible when the length of at least one of them is equal to 1.
#
# <img src="img/broadcasting1x3.gif" alt="Drawing" style="width: 300px;"/>
#
# +
# 1 x 3 array
a = np.arange(1,4)
# integer
b = 2
# 1 x 3 array
result = a * b
print(a)
print()
print(b)
print()
print(result)
# + [markdown] slideshow={"slide_type": "subslide"}
# In the dimension where `b` has size 1 and `a` has a size greater than 1 (i.e. 3), `b` behaves as if it were copied along that dimension.
# +
# 4 x 1 array
x = np.array([[0],
[10],
[20],
[30]])
# 1 x 3 array
y = np.ones(3)
# 4 x 3 array
a = x * y
print(x)
print()
print(y)
print()
print(a)
# + [markdown] slideshow={"slide_type": "subslide"}
# <img src="img/broadcasting4x3.gif" alt="Drawing" style="width: 300px;"/>
# +
# a: 4 x 3 array (see cell above)
# 1 x 3 array
b = np.arange(3)
# 4 x 3 array
result = a + b
print(a)
print()
print(b)
print()
print(result)
# + [markdown] slideshow={"slide_type": "subslide"}
# The size of the output array is the maximum size along each dimension of the input arrays.
# + [markdown] slideshow={"slide_type": "subslide"}
# The 4x3 and 1x4 arrays shown in the cell below cannot be broadcast together.
# <br>The dimensions 3 and 4 are incompatible.
# -
# <img src="img/broadcasting_mismatch.gif" alt="Drawing" style="width: 300px;"/>
# + [markdown] slideshow={"slide_type": "subslide"}
# Note that if the array dimensions are incompatible, it will generate a ValueError.
# + [markdown] slideshow={"slide_type": "subslide"}
# Recall, the function `np.insert` that we used earlier.
#
# An integer (length=1) can be broadcast into an array of any size.
# + slideshow={"slide_type": "-"}
# Add items to an array
b = np.array([[1, 1],
[2, 2],
[3, 3]])
b = np.insert(b, 1, 4, axis=1)
print(b)
# + [markdown] slideshow={"slide_type": "subslide"}
# Here are some examples of practical applications of broadcasting.
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Broadcasting Example: Calorie Calculator
#
# Let's say we have a large data set; each datum is a list of parameters.
#
# Example datum: a type of food and the the amount of fat, protein and carbohydrate in a serving of that food.
#
# Our data set of food nutrients might look something like the table below:
#
# |Food (100g) |Fat(g)|Protein (g)|Carbohydrate (g)|
# |------------|----- |-----------|----------------|
# |Almonds | 49| 21| 22|
# |Peas | 0| 5| 14|
# |Avocado | 15| 2| 9|
# |Kale | 1| 3| 10|
#
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# By applying the following sclaing factors, we can calculate the number of calories in a food type due to fat, protein and carbohydrate:
# - fat: 9 cal/g
# - protein: 4 cal/g
# - carbohydrate 4 cal/g
#
# Using what we have studied so far, we could convert the table to calories using a loop:
#
# + [markdown] slideshow={"slide_type": "subslide"}
# ```python
#
# nutrients = np.array([[49, 21, 22],
# [0, 5, 14],
# [15, 2, 9],
# [ 1, 3, 10]])
#
# cal_convert = np.array([9, 4, 4])
#
# calories = np.empty((4,3))
#
# for index, value in enumerate(nutrients):
# calories[index] = value * cal_convert
#
# ```
#
# + [markdown] slideshow={"slide_type": "subslide"}
# However, it is faster and more concise to broadcast the two arrays together:
# + slideshow={"slide_type": "subslide"}
nutrients = np.array([[49, 21, 22],
[0, 5, 14],
[15, 2, 9],
[ 1, 3, 10]])
cal_convert = np.array([9, 4, 4])
calories = nutrients * cal_convert
print(calories)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Broadcasting Example: Vector Quantisation Algorithm
# This is a simple algorithm used for catagorisation.
# <br>It determines which catagory a data point should belong to from its closest proximity to a set of values representing possible catagories.
# <br>Each value represents the mean of the corresponding catagory.
#
#
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# <br>For example, colour quantisation is used in image processing reduces the number of distinct colors used in an image, while maintianing visual similarity to the original image.
#
# <table><tr><td>
# <img src="img/un_quantised_cat.png" alt="Drawing" style="width: 300px;"/> </td><td>
# <img src="img/quantised_cat.png" alt="Drawing" style="width: 300px;"/> </td><td>
# </table>
#
# CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=1477223
# + [markdown] slideshow={"slide_type": "subslide"}
# <br>In the plot below, each of the circles represents the mean height and weight of athletes grouped by type.
# <br>The square represents the height and weight of an athlete to be classified.
# <img src="img/vector_quantisation.png" alt="Drawing" style="width: 500px;"/>
# + [markdown] slideshow={"slide_type": "subslide"}
#
# To find the closet point:
# 1. Use broadcasting to find the difference between the position of the __square__ and the position of each __circle__ in the x and y directions. <br>
# 1. Find the distance, $d$ from the square, $s$ to each circle, $c$ using: <br>$d = \sqrt{(x_{c}-x_{s})^2 + (y_{c}-y_{s})^2}$ <br>
# 1. Choose the group corresponding to the minimum distance, $d_{min}$
# + slideshow={"slide_type": "subslide"}
athlete = np.array([111.0,188.0])
categories = np.array([[102.0, 203.0],
[132.0, 193.0],
[45.0, 155.0],
[57.0, 173.0]])
# 1. broadcast
diff = categories - athlete
print(diff)
# 2. distance to each point (magnitude of values along axis 1 for each datum)
# dist = np.linalg.norm(diff,axis=1)
dist = np.sqrt(np.sum(diff**2,axis=1))
print(dist)
# 3. which group?
nearest = np.argmin(dist)
print(nearest)
# + [markdown] slideshow={"slide_type": "subslide"}
# The nearest group is index 0 of the array `catagories`.
# <br>Based on mean height and weight, the athlete is most likely to be a basketball player.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Resizing and Reshaping
# We can change the size of an array in each dimension.
#
# For example, you may want to edit the length of a dimension of an array to make it compatible with another array for broadcasting.
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Resizing
# We can resize an array.
# <br>If the new array size is smaller, the original array will be trimmed to the new size.
# +
a=np.array([[0,1],
[2,3]])
b = np.resize(a,(2,1))
print(b)
print()
a.resize(2,1)
print(a)
# + [markdown] slideshow={"slide_type": "subslide"}
# If the new array size is larger, the extra space can either be filled with repeating copies of the original array.
# +
a=np.array([[0,1],
[2,3]])
b = np.resize(a,(4,4))
print(b)
# + [markdown] slideshow={"slide_type": "subslide"}
# or with zeros.
# +
a=np.array([[0,1],
[2,3]])
a.resize(4,4)
print(a)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Reshaping
# You can re-shape the array.
# The new array must have the __same number of elements__ as the original array.
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# __Example:__ Using range to create a column vector:
# +
x = np.arange(0, 31, 10)
y = x.reshape((4,1))
# which can be written in one line as:
z = np.arange(0, 31, 10).reshape((4,1))
print(x)
print()
print(y)
print()
print(z)
# + [markdown] slideshow={"slide_type": "subslide"}
# ## Review Exercises
#
# The folowing exercises are provided to practise what you have learnt in today's seminar.
#
# The extension excercises cover topics that will not be included inthe exam but may be useful to you if you are familiar with using matrices and want to practise matrix manipulation using Python.
#
# If you have not yet studied matrices, you can come back to this section when the mathematics used is more familiar to you.
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Review Exercise: 1D Arrays - Indexing and changing values.
#
# In the cell below:
#
# 1. Create an array of zeros with length 25. <br> <a href="#Zeros">Jump to Creating a Numpy Array of Zeros.</a>
#
# 2. Change the first 10 values to 5. <br> <a href="#Changing">Jump to Changing items in an array.</a>
#
# 3. Change the next 10 values to a sequence starting at 12 and increasig with steps of 2 to 30 - do this with one command.
#
# 4. Change the final 5 values to 30.
# -
# 1D array
A = np.zeros(25)
A[:10] = 5
A[10:20] = range(12,32,2)
A[-5:] = 30
print(A)
# +
# Example Solution
# 1
a = np.zeros(25)
#2
a[: 10] = 5
#3
a[10: 20] = range(12, 31, 2)
#4
a[20:] = 30
print(a)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Review Exercise: 1D Arrays - Correct the error
#
# The code below, is supposed to:
# - change the last 5 values of the array x to the values [50, 52, 54, 56, 58]
# - print the result
# There are some errors in the code.
#
# Remove the comment markers and run the code to see the error message.
#
# Then fix the code and run it again.
# -
x = np.ones(10)
x[-5:] = range(50, 60, 2)
print(x)
# Example Solution
import numpy as np
x = np.ones(10)
x[-5:] = range(50, 59, 2)
print(x)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Review Exercise: Creating 2D Arrays
#
# Print:
#
# __(A)__ An array with 3 rows and 2 columns (3 by 2), where all elements are 1.0.
#
# <a href="#CreatingArray">Jump to Creating a Numpy Array.</a>
#
# __(B)__ An array of randomly generated integers, in the range 1 to 10, with 4 rows and one column (4 by 1).
#
# <a href="#Subpackages">Jump to Subpackages.</a>
#
# __(C)__ An array with 2 rows and 2 columns (2 by 2), where all elements are 4.
#
#
#
# -
# 2D arrays
print(np.ones((3,2)))
print(np.random.randint(1,10,(4,1)))
print(np.full((2,2),4))
# +
### Example Solution
# A
print(np.ones((3,2)))
# B
print(np.random.randint(1, 10, size=(4,1)))
# C
print(np.full((2,2), 4))
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Review Exercise: 2D Arrays - Indexing and Basic Plotting
#
# __(A)__ In the cell below, for the array `x`, write code to print:
#
# * the first row of `x`
# * the first column of `x`
# * the third row of `x`
# * the four values in the upper right hand corner of `x`
# * the four values at the center of `x`
# * the last two columns (third and fourth column) of `x`
#
# <a href="#Indexing">Jump to Indexing into multi-dimensional arrays.</a>
#
# __(B)__ You have just *printed* the last two columns of `x`.
# <br>Now plot the third column of `x` against the fourth column of `x` as a line graph.
#
# <a href="#Plotting">Jump to Introduction to Plotting.</a>
# -
# 2D array
x = np.array([[4, 2, 1, 1],
[2, 4, 2, 8],
[2, 4, 3, 27],
[4, 1, 4, 64]])
print(x[0])
print(x[:,0])
print(x[2])
print(x[:2,-2:])
print(x[1:3,1:3])
print(x[:,-2:])
plt.plot(x[:,3],x[:,2])
# +
# Example Solution
x = np.array([[4, 2, 1, 1],
[2, 4, 2, 8],
[2, 4, 3, 27],
[4, 1, 4, 64]])
print(x[0])
print(x[:, 0])
print(x[2])
print(x[0:2, 2:4])
print(x[1:3, 1:3])
print(x[:, 2:4])
plt.plot(x[:, 2], x[:, 3])
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Review Exercise: Boolean array indexing
#
# Print the values of array `x` in the cell below that are...
#
# __(A)__ ...greater than 3.
#
# __(B)__ ...greater than 2 and less than 8.
#
# __(C)__ ...less than 2 or greater than 8.
#
# __(D)__ ...a multiple of `y`.
#
# <br>
# __(E)__ Change all odd numbers in x to 0
#
# <a href="#BooleanIndexing">Jump to Boolean Array Indexing.</a>
# -
x = np.arange(10)
y = 2
print(x[x>3])
print(x[(x>3) & (x<8)])
print(x[(x>8) | (x<2)])
print(x[x%y==0])
x[x%2==1]=0
print(x)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Review Exercise: Curve Fitting
#
# Using the example data set `a`,`b`:
#
# __(A)__ Plot a scatter graph of `a` against `b`, with `a` on the horizontal axis and `b` on the vertical axis.
# <br><a href="#ScatterPlot">Jump to Scatter plot.</a>
#
# __(B)__ Fit __three different__ curves to the data. You can choose from:
# - a linear relationship. <a href="#FittingLinear">Jump to Fitting a linear relationship.</a>
# - a polynomial curve. <a href="#FittingPolynomial">Jump to Fitting a polynomial curve.</a>
# - an arbitrary function <a href="#FittingArbitrary">Jump to Fitting an arbitrary curve.</a>
#
# __(C)__ Plot each curve as a line of on the graph.
# <br><a href="#LinePlot">Jump to Line plot.</a>
#
# __(D)__ Find the route mean square error (RMSE) of each curve relative to the data set.
# <br><a href="#RMSE">Jump to Route mean square error.</a>
#
# __(E)__ Display the RMSE of each curve as a figure legend.
# <br><a href="#Legend">Jump to Adding a legend.</a>
#
# __(F)__ Print the equation of the *optimal* curve i.e. the curve with the *smallest* RMSE.
# +
a = np.array([88438,45505,75127,115571,89911,87432,100083,85589,73104,86890,78580,70785,41050,57610,107537,59262,73038,87891,75368,111638,74911,71599,96774,79667,90725,93816,75859,64969,205688,71500,53098,71250,89615,94747,50400,63673,78257,72785,83015,150000,84699,67191,86298,117705,88935,89643,106678,97894,132164,59387,60684,96151,68794,74559,29430,88362,111792,57205,83651,87518,80129,86801,110761,63274,66143,110694,52590,59994,80460,103589,68298,59056,40294,161848,103100,86354,37428,43307,80792,77368,109159,71538,84783,86250,82900,74728,48597,75549,106942,102167,62708,60630,70273,84918,88693,74141,46627,119112,88260,97262,86095,110472,82734,84761,91715,103292,86339,147993,77560,100625,68094,78250,75426,86138,112344,115000,98846,90499,80029,61959,76779,68833,81026,66361,92737,76692,64974,103869,51951,108854,61038,75938,75346,40639,73156,80067,82322,52353,
62832,207262,160106,77740,72011,167094,58458,41639,79528,66583,83993,138082,77366])
b = np.array([1.7,-0.4,0.5,2.6,1.4,1.5,1.5,1.7,-0.5,1.6,0.9,1.1,-1.7,0.3,1.8,0.5,1,1.9,0.1,2,1.7,1,1.2,1.5,1,1.1,1.2,0,2.6,1.4,-0.8,1.6,1.1,1.2,-1.4,-0.5,1.9,0,1.5,2.4,1.5,0.7,1.8,2,2.4,1.6,2,2.3,2,0.1,0.3,2.3,0,0,-1.7,1.9,2,0,0.9,1.3,0.4,1.6,2.3,-0.1,1.7,2.1,-0.9,0.1,1,1.9,0.4,-0.3,-2.4,2.7,1.3,2,-1.3,-1.5,0.7,1.1,2.3,1.1,0.7,0.9,1.1,0.1,-0.9,1.4,2.1,1.2,0.1,0.8,0.3,1.4,1.5,1,-0.5,2.4,0.9,1.5,1.6,1.2,1.3,1.8,0.8,1.8,1.9,2.6,1.5,1.8,1.8,0.6,0.7,1.2,1.5,2.5,1.1,1.6,1.6,1,0,0,1,0.5,1.7,0.6,0.1,1.7,0.2,2.1,0.1,0.9,0.8,-1.3,1.3,0.5,1.5,-0.6,1.2,2.4,2.6,1.1,0.8,2.5,-0.2,-2,0.1,0.1,1.6,2.6,1.2])
#A
plt.plot(a,b,'o')
#B
fit1 = np.polyfit(a,b,1)
fit2 = np.polyfit(a,b,2)
fit3 = np.polyfit(a,b,3)
x = np.linspace(a[0],a[-1],100)
yfit1 = np.poly1d(fit1)
yfit2 = np.poly1d(fit2)
yfit3 = np.poly1d(fit3)
#D
RMSE1 = round(np.sqrt(np.sum((yfit1(a)-b)**2)/len(b)),3)
RMSE2 = round(np.sqrt(np.sum((yfit2(a)-b)**2)/len(b)),3)
RMSE3 = round(np.sqrt(np.sum((yfit3(a)-b)**2)/len(b)),3)
#C
plt.plot(a,yfit1(a),'o',label=f"RMSE={RMSE1}")
plt.plot(a,yfit2(a),'o',label=f"RMSE={RMSE2}" )
plt.plot(a,yfit3(a),'o',label=f"RMSE={RMSE3}")
plt.legend(loc='best')
print(yfit3)
# +
### Example solution
a = np.array([88438,45505,75127,115571,89911,87432,100083,85589,73104,86890,78580,70785,41050,57610,107537,59262,73038,87891,75368,111638,74911,71599,96774,79667,90725,93816,75859,64969,205688,71500,53098,71250,89615,94747,50400,63673,78257,72785,83015,150000,84699,67191,86298,117705,88935,89643,106678,97894,132164,59387,60684,96151,68794,74559,29430,88362,111792,57205,83651,87518,80129,86801,110761,63274,66143,110694,52590,59994,80460,103589,68298,59056,40294,161848,103100,86354,37428,43307,80792,77368,109159,71538,84783,86250,82900,74728,48597,75549,106942,102167,62708,60630,70273,84918,88693,74141,46627,119112,88260,97262,86095,110472,82734,84761,91715,103292,86339,147993,77560,100625,68094,78250,75426,86138,112344,115000,98846,90499,80029,61959,76779,68833,81026,66361,92737,76692,64974,103869,51951,108854,61038,75938,75346,40639,73156,80067,82322,52353,
62832,207262,160106,77740,72011,167094,58458,41639,79528,66583,83993,138082,77366])
b = np.array([1.7,-0.4,0.5,2.6,1.4,1.5,1.5,1.7,-0.5,1.6,0.9,1.1,-1.7,0.3,1.8,0.5,1,1.9,0.1,2,1.7,1,1.2,1.5,1,1.1,1.2,0,2.6,1.4,-0.8,1.6,1.1,1.2,-1.4,-0.5,1.9,0,1.5,2.4,1.5,0.7,1.8,2,2.4,1.6,2,2.3,2,0.1,0.3,2.3,0,0,-1.7,1.9,2,0,0.9,1.3,0.4,1.6,2.3,-0.1,1.7,2.1,-0.9,0.1,1,1.9,0.4,-0.3,-2.4,2.7,1.3,2,-1.3,-1.5,0.7,1.1,2.3,1.1,0.7,0.9,1.1,0.1,-0.9,1.4,2.1,1.2,0.1,0.8,0.3,1.4,1.5,1,-0.5,2.4,0.9,1.5,1.6,1.2,1.3,1.8,0.8,1.8,1.9,2.6,1.5,1.8,1.8,0.6,0.7,1.2,1.5,2.5,1.1,1.6,1.6,1,0,0,1,0.5,1.7,0.6,0.1,1.7,0.2,2.1,0.1,0.9,0.8,-1.3,1.3,0.5,1.5,-0.6,1.2,2.4,2.6,1.1,0.8,2.5,-0.2,-2,0.1,0.1,1.6,2.6,1.2])
# A
plt.plot(a, b,'o')
# B
c, d, e = np.polyfit(a, b, 2)
f, g, h, i = np.polyfit(a, b, 3)
j, k, l, m, n = np.polyfit(a, b, 4)
# C
yfit2 = np.poly1d([c, d, e])(a)
yfit3 = np.poly1d([f, g, h, i])(a)
yfit4 = np.poly1d([j, k, l, m, n])(a)
# yfit2 = c*a**2 + d*a + e
# yfit3 = f*a**3 + g*a**2 + h*a + i
# yfit4 = j*a**4 + k*a**3 + l*a**2 + m*a + n
plt.plot(a, yfit2,'o')
plt.plot(a, yfit3,'o')
plt.plot(a, yfit4,'o')
# D
# Define a function
def RMSE(ideal, real):
return round(
np.sqrt
(np.sum
((ideal - real)**2)/ len(real))
, 4)
# error
rmse2 = RMSE(yfit2, b)
rmse3 = RMSE(yfit3, b)
rmse4 = RMSE(yfit4, b)
# E
# You don't need to replot the data as shown here, you can just add the labels to your answer to part C
plt.plot(a, yfit2,'o', label = f"RMSE={rmse2}")
plt.plot(a, yfit3,'o', label = f"RMSE={rmse3}")
plt.plot(a, yfit4,'o', label = f"RMSE={rmse4}")
plt.legend(loc='best')
# F
print(np.min([rmse2, rmse3, rmse4]))
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Review Exercise: Vectorising a function
#
# Recall the function `is_positive` that we looked at in Seminar 5: Functions.
#
# A similar function is shown in the cell below.
#
# It takes an argument, `x` and returns:
# - `True` if `x` is positive.
# - `False` if `x` is negative.
#
# Write a vectorised version of the function that will accept a Numpy array as an argument.
#
# <br><a href="#Vectorising">Jump to Vectorising a function.</a>
#
# Demonstrate your function works by calling it.
# +
def is_positive(x):
"Checks if the function value f(x) is positive"
return x > 0
vec_is_positive = np.vectorize(is_positive)
x = np.array([2,-3])
print(vec_is_positive(x))
# +
# Example Solution
def is_positive(x):
"Checks if the function value f(x) is positive"
return x > 0
is_positive_vec = np.vectorize(is_positive)
z = [1, 2, 3]
is_positive_vec(z)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Review Exercise: Broadcasting
# Use a single broadcasting operation to:
# - add 2 to every element in the first column of `a`
# - add 3 to every element in the second column of `a`
# - subtract 1 from every element in the third column of `a`
# +
a = np.array([ [49, 21, 22],
[0, 5, 14],
[15, 2, 9],
[ 1, 3, 10]])
b = [2,3,-1]
print(a+b)
# -
# Example Solution
print(a + np.array([2, 3, -1]))
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Extension Exercise: Broadcasting and Mathematics with matrices - Simultaneous Equations, Polynomial Coeffcients
#
# The equation of a parabola can be fully defined using three points that lie on the curve (provided the curve is not a straight line).
#
# The equation for a parabola is $y=ax^2+bx+c$, where $a$, $b$, and $c$ are constants.
#
# __(A)__Given three points $(x_1,y_1)$, $(x_2,y_2)$, $(x_3,y_3)$,
# <br>three simultaneous equation may be written:
# $$
# \begin{split}
# x_1^2a+x_1b+c&=y_1 \\
# x_2^2a+x_2b+c&=y_2 \\
# x_3^2a+x_3b+c&=y_3 \\
# \end{split}
# $$
#
# Given that:
# <br>$(x_1,y_1)=(-2,2)$
# <br>$(x_2,y_2)=(1,-1)$
# <br>$(x_3,y_3)=(4,4)$
# <br>use matrix multiplication to find $a$,$b$ and $c$.
#
# <a href="#SimultaneousEqtns">Jump to Simultaneous Equations.</a>
# <br><a href="#Broadcasting">Jump to Broadcasting.</a>
#
# Hint:
# <br>Build a 1D array, `y`, containing values $y_1$, $y_2$ and $y_3$.
# <br>Build a 2D array, `x`, with which to multiply `y` to find a 1D array containing $a$, $b$ and $c$.
#
#
# __(B)__ Show that your solution is correct by:
# - plotting a graph of $y=ax^2+bx+c$ against $x$ for range of x.
# - plotting the three points: <br>$(x_1,y_1)=(-2,2)$ <br>$(x_2,y_2)=(1,-1)$ <br>$(x_3,y_3)=(4,4)$ <br>as points to check that they lie on the curve.
#
#
#
#
# +
# Solve the simultaneous equations to find a, b and c
# +
# Example solution
# 1D array, y
y = np.array([2, -1, 4])
# 2D array, x
x = np.array([[(-2**2), -2, 1],
[(1**2), 1, 1],
[(4**2), 4, 1]])
abc = np.linalg.solve(x, y)
print(abc)
# Another way to create matrix x without writing it out explicitly is to use:
# - broadcasting
# - the numpy function, power (raises first argument to power of second)
xs = np.array([-2, 1, 4])
xs = xs.reshape((3,1))
power = np.array([2, 1, 0])
x = np.power(xs, power)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Extension Exercise: Solving systems of first order differential equations - Predator & prey
#
# The predator-prey equations represent a simplified model of two species interacting; for example:
# - rabbits $x$(prey)
# - population $y$: foxes (predators)
#
# *The more foxes there are*, the more rabbits get eaten by foxes and the population of rabbits gets smaller...
# <br>...so there is less food for the foxes so the population of foxes gets smaller...
# <br>...so there is less danger to the rabbits, so the population fo rabbits gets bigger...
# <br>...so there is more food for the foxes, so the population of foxes gets bigger...
# <br>...*The more foxes there are*....
#
# We can expect to see the two populations rise and fall cyclically with time.
#
# The two related populations can be described by a pair of first-order non-linear ordinary differential equations.
#
# \begin{align*}
# \frac{dx}{dt}&=x(a-by)\\
# \frac{dy}{dt}&=-y(c-dx)\\
# \end{align*}
#
# Where:
# <br>$a$ represents rabbit births
# <br>$b$ represents rabbit deaths due to foxes
# <br>$c$ represents fox deaths in the absence of rabbits
# <br>$d$ represents foxes kept alive by feeding on rabbits
#
# <br>($a,b,c,d$ are assumed to be positive)
#
# __(A)__ Use `odeint` to estimate the solution to the couple differntial equations:
# - between time = 0 and time = 20 units (suggested time step = 0.1 unit)
# - where $a=b=c=d=1$
# - for initial conditions:<br>$x(0)=150$ <br>$y(0)=100$
#
# <a href="#DiffEqtns">Jump to Systems of Equations for Rates of Change.</a>
#
# __(B)__ Plot the two populations using a graph. <br>Include a legend to label the two populations.
#
# __(C)__ Try changing the values of $a,b,c,d$ and the initial number of rabbits and foxes and observe the output in your graph.
# +
# Predator-prey equations
# +
# Example solution
# A
# Between time = 0 and time = 100
ts = np.linspace(0, 100, 100)
a,b,c,d = 1,1,1,1
# Define function that returns differential
def dP_dt(P, t):
return [P[0]*(a - b*P[1]),
-P[1]*(c - d*P[0])]
# Initial conditions
P0 = [150, 100]
# Solve using odeint
Ps = odeint(dP_dt, P0, ts)
# B
# plot the two populations using a graph
foxes = Ps[:,0]
rabbits = Ps[:,1]
plt.plot(ts, rabbits, label="rabbits")
plt.plot(ts, foxes,label="foxes")
t = ts[0:50:4]
r = rabbits[0:50:4]
f = foxes[0:50:4]
plt.xlabel("Time")
plt.ylabel("Population")
# Include a legend
plt.legend();
print(t)
print(r)
print(f)
# + [markdown] slideshow={"slide_type": "slide"}
# # Summary
#
# - Numpy arrays are a type of data structure optimised for numerical computations.
# - Unlike data structure such as lists and tuples, an array can store data in multiple dimensions.
# - Numpy array are a convenient way to represent vectors and matrices.
# - Numpy funcions generally behave in an "elementwise" way.
# - We can "vectorise" other functions so that they accept data structure as arguments.
# - Broasdcasting is a useful tool for applying information in one numpy array to another without having to repeat or reshape the arrays to match one another.
# - The matplotlib library can be used to quicky produce simple plots to visualise and check your solutions to mathematical problems.
# - This includes fitting a curve or a relationship to a dataset.
# + [markdown] slideshow={"slide_type": "slide"}
# ###### Homework
#
# 1. __PULL__ the changes you made in-class today to your personal computer.
# 1. __COMPLETE__ any unfinished Review Exercises.
# 1. __PUSH__ the changes you make at home to your online repository.
# 1. Install __ffmpeg__...
#
# #### Installing FFmpeg
# FFmpeg is software for handling multimedia data.
# <br>You must have it installed to view the animatied figures we will produce in next week's seminar.
#
# ###### Installing FFmpeg on mac
# Open a terminal.
# Copy and paste the following command into the terminal to install homebrew (a linux-like package manager):
# >`ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"`
#
# Copy and paste the following command into the terminal to install FFmpeg:
# >`brew install ffmpeg`
#
# To check ffmpeg has installed copy and paste the following command into the terminal:
# >`ffmpeg -version`
#
# If FFmpeg has installed a few lines of code will appear, starting with the version number which will be something like:
# >`ffmpeg version 3.4 Copyright (c) 2000-2017 `
#
#
# -
# ###### Installing FFmpeg on linux
# Open a terminal.
# Copy and paste the following commands into the terminal (one-by-one, pressing enter after one) to install ffmpeg:
# >`sudo add-apt-repository ppa:kirillshkrogalev/ffmpeg-next
# sudo apt-get update
# sudo apt-get install ffmpeg`
#
# To check ffmpeg has installed copy and paste the following command into the terminal:
# >`ffmpeg -version`
#
# If FFmpeg has installed a few lines of code will appear, starting with the version number which will be something like:
# >`ffmpeg version 3.4 Copyright (c) 2000-2017 `
#
#
#
#
# ###### Installing FFmpeg on windows
#
# Open a terminal.
#
# To find out what version of windows you have, copy and paste the following command into the terminal to see if your computer has a 32 or 64 bit CPU:
# >`wmic os get osarchitecture`
#
# Go to ffmpeg.zeranoe.com/builds/
# - Click the appropraite __Architecture__ for your computer.
# - Click Static __Linking__
# - Leave __Version__ as the default.
# - Click __Download Build__
#
# Go to your computer's Downloads folder.
# - Right click on the newly downloaded .zip folder (it's name will start with `ffmpeg`).
# - Choose __Extract All__ from the drop-down menu.
# - If given the option to choose a location to extract the files to, choose your Program Files folder.<br>Otherwise, a non-.zip folder of the same name as the one you downloaded will appear in the Downloads folder. <br>Copy the folder to your Program Files folder.
# - Change rename of the folder you just copied into Program Files with the name:
# <br>`ffmpeg`
#
# Go back to the terminal and copy and paste the following command into the terminal to add ffmpeg to the windows path:
# >`PATH=C:\Program Files\ffmpeg\bin;%PATH%`
#
# To check ffmpeg has installed copy and paste the following command into the terminal:
# >`ffmpeg -version`
#
# If FFmpeg has installed a few lines of code will appear, starting with the version number which will be something like:
# >`ffmpeg version 3.4 Copyright (c) 2000-2017 `
#
#
# Please do this before next week's class.
| 7_Numerical_computation_with_Numpy.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Prรฉparation de la seconde table sur les caractรฉristiques dรฉmographiques
import os
import pandas as pd
# Declaration des constantes
DATA_DIR = '../data/external/'
CITIES_FILENAME = 'base-cc-filosofi-2015.xls'
PROCESSED_DIR = '../data/processed/'
COMMUNES_DIR = 'PS_communes.csv'
filo_df = pd.read_excel(os.path.join(DATA_DIR,CITIES_FILENAME), skiprows=5)
filo_df.NBPERSMENFISC15.isnull().sum()
# 10% du fichier ne porte pas d'effectif de population
filo_df.shape
filo_df.head()
filo_df.info()
# ## Importation de la table des communes
communes_df = pd.read_csv(os.path.join(PROCESSED_DIR,COMMUNES_DIR),
sep =';',
dtype = {'codecommuneetablissement' : str})
# + active=""
# # Deuxiรจme mรฉthode si le code commune n'รฉtait pas en str dรจs l'importation de dรฉpart
# communes_df['codecommuneetablissement'] = communes_df['codecommuneetablissement'].str.replace('\.0', '')
# b = '0'
# for i in range(len(communes_df)):
# if len(communes_df['codecommuneetablissement'][i]) == 4:
# communes_df['codecommuneetablissement'][i] = b + communes_df['codecommuneetablissement'][i]
# -
# ## Merge des deux tables par code commune
final_df = (communes_df.merge(filo_df, left_on = 'codecommuneetablissement', right_on = 'CODGEO', how= 'outer', indicator = True)
.fillna(value = { c: 0 for c in communes_df.columns if c != 'codecommuneetablissement'} )
)
final_df._merge.value_counts()
final_df.to_csv('../data/external/Analyse_df.csv', encoding = 'utf-8', sep = ',', index = False)
communes_df.head()
| notebooks/prep_filosofi.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Imports
import numpy as np
rng_seed = 368
np.random.seed(rng_seed)
from mongoengine import connect, Document, StringField, IntField, MapField, ListField
from tqdm import tqdm
import pymongo
# Connect to db
cursor = connect('testdb')
cursor
# +
# Define schema for db
class Article(Document):
cord_uid = StringField(required=True, primary_key=True)
title = StringField(field=str, required=False)
word_frequencies = MapField(field=IntField(), required=True)
class Word(Document):
word = StringField(required=True, primary_key=True)
# word = MapField(field=StringField(), required=True, primary_key=True)
cord_uids = ListField(field=StringField(), required=True)
# -
# Delete all articles
Article.objects().delete()
Word.objects().delete()
# +
# Saving some articles to db
for i in tqdm(range(5), unit='article'):
cord_uid = f'lalala_{i + 1}'
article = Article(cord_uid=cord_uid)
for j in range(5):
word_str = f'word_{j + 1}'
article.word_frequencies[word_str] = int(np.random.random() * 1000)
article.title = 'dick'
article.save()
for i in tqdm(range(5), unit='word'):
word_str = f'word_{i + 1}'
word = Word(word=word_str)
for j in range(3):
cord_uid = word_str+f' lalala_{j}'
word.cord_uids.append(cord_uid)
word.save()
# -
client = pymongo.MongoClient('localhost', 27017, maxPoolSize=100000)
db = client['testdb']
coll = db.word
coll.insert_one({'_id':'fefe','cord_uids':['a','b','c']})
coll.find_one('fefe')
Word.objects(word='fefe')[0].cord_uids
# +
temp = Word(word='lala')
temp.cord_uids.extend(['1','2','3'])
temp.save()
temp2 = Word.objects(word='lala')[0]
temp.cord_uids
# -
# Looking up specific cord_uid
print(Article.objects(cord_uid='lalala_1')[0].word_frequencies)
print(Article.objects(cord_uid='lalala_1')[0].title)
# Looking up specific word
word_3_cord_uids = Word.objects(word='word_1')[0].cord_uids
word_3_cord_uids
for cord_uid in word_3_cord_uids[:5]:
article = Article.objects(cord_uid=cord_uid)[0]
print(article.word_frequencies)
| code/mongodb_testing.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
from pulp import *
# ### Read the given nutrition dataset into a Pandas DataFrame object
# Note we are reading only the first 64 rows with `nrows=64` argument because we just want to read all the nutrients informtion and not the maximum/minimum bounds in the dataset. We will enter those bounds in the optimization problem separately.
df = pd.read_excel("diet.xls",nrows=64)
# ### Show first 5 rows of the dataset
df.head()
# ### Create the `PuLP` problem variable. Since it is a cost minimization problem, we need to use `LpMinimize`
# Create the 'prob' variable to contain the problem data
prob = LpProblem("Simple Diet Problem",LpMinimize)
# ### Create a list of food items from the dataset
# Creates a list of the Ingredients
food_items = list(df['Foods'])
print("So, the food items to consdier, are\n"+"-"*100)
for f in food_items:
print(f,end=', ')
# ### Create a dictinary of costs for all food items
costs = dict(zip(food_items,df['Price/ Serving']))
costs
# ### Create a dictionary of calories for all food items
calories = dict(zip(food_items,df['Calories']))
# ### Create a dictionary of cholesterol for all food items
cholesterol = dict(zip(food_items,df['Cholesterol mg']))
# ### Create a dictionary of total fat for all food items
fat = dict(zip(food_items,df['Total_Fat g']))
# ### Create a dictionary of sodium for all food items
sodium = dict(zip(food_items,df['Sodium mg']))
# ### Create a dictionary of carbohydrates for all food items
carbs = dict(zip(food_items,df['Carbohydrates g']))
# ### Create a dictionary of dietary fiber for all food items
fiber = dict(zip(food_items,df['Dietary_Fiber g']))
# ### Create a dictionary of protein for all food items
protein = dict(zip(food_items,df['Protein g']))
# ### Create a dictionary of vitamin A for all food items
vit_A = dict(zip(food_items,df['Vit_A IU']))
# ### Create a dictionary of vitamin C for all food items
vit_C = dict(zip(food_items,df['Vit_C IU']))
# ### Create a dictionary of calcium for all food items
calcium = dict(zip(food_items,df['Calcium mg']))
# ### Create a dictionary of iron for all food items
iron = dict(zip(food_items,df['Iron mg']))
# ### Create a dictionary of food items with lower bound
# A dictionary called 'food_vars' is created to contain the referenced Variables
food_vars = LpVariable.dicts("Food",food_items,0,cat='Continuous')
food_vars
# ### Adding the objective function to the problem
# The objective function is added to 'prob' first
prob += lpSum([costs[i]*food_vars[i] for i in food_items]), "Total Cost of the balanced diet"
# ### Adding the calorie constraints to the problem
prob += lpSum([calories[f] * food_vars[f] for f in food_items]) >= 1500.0, "CalorieMinimum"
prob += lpSum([calories[f] * food_vars[f] for f in food_items]) <= 2500.0, "CalorieMaximum"
# ### Adding other nutrient constraints to the problem one by one...
# +
# Cholesterol
prob += lpSum([cholesterol[f] * food_vars[f] for f in food_items]) >= 30.0, "CholesterolMinimum"
prob += lpSum([cholesterol[f] * food_vars[f] for f in food_items]) <= 240.0, "CholesterolMaximum"
# Fat
prob += lpSum([fat[f] * food_vars[f] for f in food_items]) >= 20.0, "FatMinimum"
prob += lpSum([fat[f] * food_vars[f] for f in food_items]) <= 70.0, "FatMaximum"
# Sodium
prob += lpSum([sodium[f] * food_vars[f] for f in food_items]) >= 800.0, "SodiumMinimum"
prob += lpSum([sodium[f] * food_vars[f] for f in food_items]) <= 2000.0, "SodiumMaximum"
# Carbs
prob += lpSum([carbs[f] * food_vars[f] for f in food_items]) >= 130.0, "CarbsMinimum"
prob += lpSum([carbs[f] * food_vars[f] for f in food_items]) <= 450.0, "CarbsMaximum"
# Fiber
prob += lpSum([fiber[f] * food_vars[f] for f in food_items]) >= 125.0, "FiberMinimum"
prob += lpSum([fiber[f] * food_vars[f] for f in food_items]) <= 250.0, "FiberMaximum"
# Protein
prob += lpSum([protein[f] * food_vars[f] for f in food_items]) >= 60.0, "ProteinMinimum"
prob += lpSum([protein[f] * food_vars[f] for f in food_items]) <= 100.0, "ProteinMaximum"
# Vitamin A
prob += lpSum([vit_A[f] * food_vars[f] for f in food_items]) >= 1000.0, "VitaminAMinimum"
prob += lpSum([vit_A[f] * food_vars[f] for f in food_items]) <= 10000.0, "VitaminAMaximum"
# Vitamin C
prob += lpSum([vit_C[f] * food_vars[f] for f in food_items]) >= 400.0, "VitaminCMinimum"
prob += lpSum([vit_C[f] * food_vars[f] for f in food_items]) <= 5000.0, "VitaminCMaximum"
# Calcium
prob += lpSum([calcium[f] * food_vars[f] for f in food_items]) >= 700.0, "CalciumMinimum"
prob += lpSum([calcium[f] * food_vars[f] for f in food_items]) <= 1500.0, "CalciumMaximum"
# Iron
prob += lpSum([iron[f] * food_vars[f] for f in food_items]) >= 10.0, "IronMinimum"
prob += lpSum([iron[f] * food_vars[f] for f in food_items]) <= 40.0, "IronMaximum"
# -
# ### Writing problem data to a `.lp` file
# The problem data is written to an .lp file
prob.writeLP("SimpleDietProblem.lp")
# ### Run the solver
# The problem is solved using PuLP's choice of Solver
prob.solve()
# ### Print the problem solution status `'optimal'`, `'infeasible'`, `'unbounded'` etc...
# The status of the solution is printed to the screen
print("Status:", LpStatus[prob.status])
# ### Scan through the problem variables and print out only if the variable quanity is positive i.e. it is included in the optimal solution
print("Therefore, the optimal (least cost) balanced diet consists of\n"+"-"*110)
for v in prob.variables():
if v.varValue>0:
print(v.name, "=", v.varValue)
# ### Print the optimal diet cost
print("The total cost of this balanced diet is: ${}".format(round(value(prob.objective),2)))
| Balanced_Diet_Problem_Simple.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, accuracy_score, classification_report
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
# %matplotlib inline
plt.style.use('seaborn-dark-palette')
import warnings
warnings.filterwarnings('ignore')
#Importing The Dataset
df = pd.read_csv("Social_Network_Ads.csv")
df.head()
df.tail()
df.shape
# <h3>We are avoiding the first two columns because our model will classify whether an item is purchased od not</h3>
X = df.iloc[:, [2,3]].values
Y = df.iloc[:, 4].values
print("Size of X: {}".format(X.shape))
print("Size of Y: {}".format(Y.shape))
# Splitting the dataset into the Training set and Test set
X_train, X_test, Y_train, Y_test = train_test_split(X,
Y,
test_size = 0.25,
random_state=0)
print("Size of X_train: {}".format(X_train.shape))
print("Size of X_test: {}".format(X_test.shape))
print("Size of Y_train: {}".format(Y_train.shape))
print("Size of Y_test: {}".format(Y_test.shape))
#Feature Scaling
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
#Build our Classifier
classifier = SVC(kernel = 'linear', random_state = 0)
classifier.fit(X_train, Y_train)
#Predicting The Results
y_pred = classifier.predict(X_test)
y_pred
#Comparing the results
cm = confusion_matrix(y_pred, Y_test)
cm
acc = accuracy_score(y_pred, Y_test)
print("The accuracy is: {}%".format(acc*100))
# <h3>Building a text report showing the main classification metrics</h3>
cr = classification_report(y_pred, Y_test)
print(cr)
# +
# Visualising the Training set results
x_set, y_set = X_train, Y_train
#Creating the grid of Minimum and maximun values from X_train
X1, X2 = np.meshgrid(np.arange(start = x_set[:, 0].min() - 1,
stop = x_set[:, 0].max() + 1,
step = 0.01),
np.arange(start = x_set[:, 1].min() - 1,
stop = x_set[:, 1].max() + 1,
step = 0.01))
#Plotting the line Classifier
plt.contourf(X1,
X2,
classifier.predict(np.array([X1.ravel(),
X2.ravel()]).T).reshape(X1.shape),
alpha = 0.4,
cmap = ListedColormap(('red', 'green')))
#Plotting The Datapoint in red and gree color
for i,j in enumerate(np.unique(y_set)):
plt.scatter(x_set[y_set == j, 0],
x_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i),
label = j,
s = 8,
marker = '*'
)
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
plt.title("KNN Classifier (Training Set)")
plt.xlabel("Age")
plt.ylabel("Estimated Salary")
plt.legend()
# +
# Visualising the Test set results
x_set, y_set = X_test, Y_test
#Creating the grid of Minimum and maximun values from X_train
X1, X2 = np.meshgrid(np.arange(start = x_set[:, 0].min() - 1,
stop = x_set[:, 0].max() + 1,
step = 0.01),
np.arange(start = x_set[:, 1].min() - 1,
stop = x_set[:, 1].max() + 1,
step = 0.01))
#Plotting the line Classifier
plt.contourf(X1,
X2,
classifier.predict(np.array([X1.ravel(),
X2.ravel()]).T).reshape(X1.shape),
alpha = 0.4,
cmap = ListedColormap(('red', 'green')))
#Plotting The Datapoint in red and gree color
for i,j in enumerate(np.unique(y_set)):
plt.scatter(x_set[y_set == j, 0],
x_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i),
label = j,
s = 10,
marker = '^'
)
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
plt.title("KNN Classifier (Test Set)")
plt.xlabel("Age")
plt.ylabel("Estimated Salary")
plt.legend()
# -
| Classification/Support Vector Classification.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.6.8 64-bit
# name: python3
# ---
# # Inversion method
#
# Probability integral transform is useful in statistics for checking goodness of fit of a distribution to a set of data while the inverse method is used for simulation.
#
# ## 1. **Probability integral transfrom**
#
# ๐ด For GOODNESS OF FIT ๐ด
#
# Data values that are modeled on being R.V. from any given distribution can be converted to a R.V. having uniform distribution. Let $X \sim F_X(x)$ define a transformation where $Y = F_X(X) \in [0,1]$. So, $X = F_X^{-1}(y)$, then $Y$ is uniform over $[0,1]$, i.e. $Y \sim Unif(0,1)$.
#
# This result can be summarized as:
#
# **Theorem:** if X has CDF F, then F(x) has unif(0,1) distribution.
#
# **Proof:**
#
# $$F_y(y) = P(Y<=y) = P(F_x(x) <= y) = P(x <= F_x^{-1}(y)) = F_x(F_x^{-1}(y)) = y$$
#
# So, $F_y(y) = P(Y<=y) = y$, then $Y \sim Unif(0,1)$.
#
# ## 2. **Inverse probability integral transform**
#
# ๐ด For SIMULATION OF R.V.๐ด
#
# Here, we start from $Unif(0,1)$ and going to $Y = F_X(x)$. This is helpful because it's easy to get a $Unif(0,1)$. From here, you can get a more complicated solution.
#
# *Start from the uniform distribution and do the inverse procedure*
#
# **Theorem:** suppose $X \sim U(0,1)$, i.e. $F_X(x) = x$, $\forall x \in [0,1]$. Let $Y = F^{-1}(x)$, then $X = F(y)$, where $F(\cdot)$ is a non-decreasing absolutely continuous function, then $Y$ has the CDF corresponding to $F$.
#
# **Proof:**
#
# Need to prove that $F_Y(y) = F(y)$.
#
# $$F_Y(y) = P(Y <= y) = P(F^{-1}(x) <= y) = P(x <= F(y)) = F(y)$$
#
#
# ## **Inversion method**
#
# Suppose we want to simulate $X$ whose distribution has a given CDF, $F$. If $F$ is continuous and strictly increasing, then $F^{-1}$ exists. Now, sampling $U \sim Unif(0,1)$ and setting $X = F^{-1}(u)$ does the job. This means that if $X$ has CDF $F$, then $F^{-1}(u)$ will have CDF $F$, so if you are able to calculate $F^{-1}$, and can gather uniform, then you can generate a sample from $F$.
#
# ### Example 1: Generate a random sample of a distribution with $F(x) = x / (1 + x)$.
#
# To get F^{-1}(y), specify a value for y and solve for x.
#
# $$y = x / (1 + x)$$
#
# $$x = y / (1 - y)$$
#
# So, $F^{-1}(y) = y / (1 - y)$. This means that $u / (1 - u)$ will have CDF $F$. Therefore, the algorithm is:
#
# 1. Generate uniform distribution, $ U \sim Unif(0,1)$
#
# 2. Set $x = u / (1 - u)$
#
# 3. Conduct this multiple times to sample the distribution
#
# +
import numpy as np
import matplotlib.pyplot as plt
u = np.random.uniform(0, 1, 100000)
# samples
samples = u / (1 - u)
plt.hist(samples)
plt.show()
# -
# ### Example 2: Generate random sample of exponential distribution with rate $\lambda$
#
# We know $f(x) = \lambda \exp (-\lambda x )$ where $x \geq 0$. Therefore, $F(x) = 1 - \exp(-\lambda x)$.
#
# To calculate $F^{-1}(y), specify a value for $y$ and solve for $x$.
#
# $$y = 1 - \exp(- \lambda x)$$
#
# $$x = \frac{-1}{\lambda} \log (1 - y)$$
#
# Therefore, $x = F^{-1}(y) = - \frac{1}{\lambda} \log (1 - y)$.
#
# This means that if $U \in [0,1]$, then $F^{-1}(U) = -\frac{1}{\lambda} \log (1 - U) \sim Exp(\lambda)$
#
# To generate samples,
#
# 1. Sample $U \sim Unif(0,1)$
#
# 2. Set $x = -\frac{1}{\lambda} \log(1 - u)$
#
#
# +
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import expon
u = np.random.uniform(0, 1, 1000000)
lambd = 2
# samples
samples =- (1 / lambd) * np.log(1 - u)
x = np.linspace(0,4,100)
plt.hist(samples, bins=30, density=True)
plt.plot(x, expon.pdf(x, scale=1/lambd))
plt.show()
# -
# ### Example 3: Generate random sample of the (standard) normal distribution
#
# We know $f(x) = \frac{1}{\sqrt{2\pi}} \exp( - \frac{x^2}{2} )$, where $-\infty < x < \infty$
#
# The CDF $F(x)$ does not have a closed form.
#
# $$\Phi (x) = \int_{-\int}^x \frac{1}{\sqrt{2\pi}} \exp(- \frac{x^2}{2} ) dx$$
#
# In many cases, you cannot invert the CDF (i.e. normal distribution, t-distribution)
#
# A normal R.V. can, in principle, can be generated using the inversion method. However, this requires evaluations of the standard normal inverse CDF, which is a non-trivial calculation. There [are ways](https://stats.stackexchange.com/questions/16334/how-to-sample-from-a-normal-distribution-with-known-mean-and-variance-using-a-co) of sampling this distribution.
# ## 3. Transformation Methods
#
# This is the case where distribution $F$ is linked in a simple way to another distribution easy to simulate.
#
# ### Sampling normal RVs
#
# There are a number of fast and efficient alternatives for generating normal RVs.
#
# #### **Box-Muller algorithm**
#
# Box-Muller is based on some trigonometric transformations.
from utils import disp
disp('box-muller.png')
# This method generates a pair of normal RVs $X$ and $Y$. Let $X \sim N(0,1)$ and $Y \sim N(0,1)$ be independent. Box-Muller sampling is based on representing the joint distribution of 2 independent standard normal variables in polar coordinates. The joint distribtion $p(x,y)$ which is circular-symmetric is
#
# $$p(x,y) = p(x) \times p(y) = (\frac{1}{\sqrt{2\pi}} \exp( -\frac{x^2}{2} ))(\frac{1}{\sqrt{2\pi}} \exp (-\frac{y^2}{2} ))$$
#
# $$ = \frac{1}{2\pi} \exp( - (x^2 + y^2) / 2) = \frac{1}{2\pi} \exp ( -r^2 / 2)$$
#
# where $r^2 = x^2 + y^2$. Therefore,
#
# $$p(r, \theta) = \frac{1}{2\pi} \exp ( -r^2 / 2 )$$
#
# is the joint density of $r^2 \sim \chi_2^2$ (or $\exp(1/2)$) and $\theta \sim Unif(0, 2\pi)$.
#
# This is because: $x^2 \sim \chi_1^2$, $y^2 \sim \chi_1^2$, x and y are independent. Therefore, $x^2 + y^2 \sim \chi_2^2$
#
# It follows that normal RVs can be generated from $\chi^2$ and uniform.
#
# If $X \sim N(0,1)$, $Y \sim N(0,1)$ and independent, then
#
# $$X^2 + Y^2 = -2 \log{ U_1} \sim \chi_2^2$$
#
# where $U_1 \sim Unif(0,1)$.
#
# $- \log {x}$ comes from the inverse of the exponential distribution.
#
# #### Question: Given that $x^2 + y^2 = -2 \log{U_1}$, how do we find X and Y?
#
# Define $\theta$ as a random angle between $X$ and $r$ where $r^2 = x^2 + y^2$. Then, $\theta \sim Unif(0, 2\pi)$.
#
disp('box_muller_coordinates.png')
# $$x = r \cos \theta = \sqrt{ -2 \log U_1 } \cos (2\pi U_2)$$
#
# $$y = r \sin \theta = \sqrt{ -2 \log U_1 } \sin (2\pi U_2)$$
#
# where $U_2 = \frac{\theta}{2\pi} \sim Unif(0,1)$ because as we stated above, $\theta \sim Unif(0, 2\pi)$.
#
#
# **Justification**: Let $x^2 + y^2 = -2 \log U_1$. Therefore, $u_1 = \exp ( -\frac{x^2+y^2}{2} )$.
#
# $$\tan (2\pi U_2) = Y / X $$
#
# $$U_2 = \frac{1}{2\pi} tan^{-1} (Y/X)$$
#
# The Jacobian of the polar transformation is
#
# $$| \frac{\delta (u_1, u_2)}{\delta{x,y}}| = \frac{1}{2\pi} \exp { - \frac{x^2 + y^2}{2}}$$
#
# By the formulat for the random vairable transformation, we have
#
# $$f(x,y) = f(u_1, u_2) | \frac{\delta (u_1, u_2)}{\delta{x,y}}| = \frac{1}{2\pi} \exp {-\frac{1}{2} (x^2 + y^2)}$$
#
# Hence, $X$ and $Y$ are independent N(0,1).
#
#
# **We want to generate a random normal sample. To do this, we simply **
#
# 1. Sample $U \sim Unif(0,1)$ and $V \sim Unif(0,1)$
#
# 2. Set $x = r \cos \theta = \sqrt{ -2 \log U } \cos (2\pi V)$ and $x = r \cos \theta = \sqrt{ -2 \log U } \sin (2\pi V)$
#
# 3. Take a linear function to get different mean and variance ($\mu$, $\sigma$)
#
# +
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
u = np.random.uniform(0,1,1000000)
v = np.random.uniform(0,1,1000000)
samples = np.sqrt(-2 * np.log(u)) * np.cos(2 * np.pi * v)
x = np.linspace(-4,4,100)
plt.hist(samples, bins=60, density=True)
plt.plot(x, norm.pdf(x))
plt.show()
# -
# To get a normal distribution, simply evaluate $x = \mu + z \sigma \sim N(\mu, \sigma)$.
#
# Several other useful transformation identities exist!
#
# ### Chi-squared
#
# If $x_1, x_2, ..., x_k \sim N(0,1)$ independent, then $\sum_{i=1}^k X_i^2 \sim \chi_k^2$
#
# ### Gamma
#
# If $x_1, x_2, ..., x_k \sim exp(\lambda)$ independent, then $\sum_{i=1}^k X_i \sim Gamma(k, \lambda)$
#
# **Reminder**: we can get exponential by going from uniform to exponential and can get gamma by summing exponentials
#
# ### Beta
#
# If $X_1 \sim Gamm(\alpha, \lambda)$ and $X_2 \sim Gamm(\beta, \lambda)$ independent, then $\frac{X_1}{X_1 + X_2} \sim Beta(\alpha, \beta)$
#
# ### t
#
# If $Z\sim N(0,1)$ and $Y\sim \chi_\nu^2$ independent, then $X = \frac{Z}{\sqrt{Y / \nu}} \sim t_\nu$
#
# ### F
#
# If $X\sim t_{(df)}$ then $X^2 \sim F(1, df)$
#
#
# ## Indirect Sampling techniques
#
# Sample from a different distribution to generate samples from a target distribution.
# For example, a laplace (or double exponential) distribution can be used to approximate the normal distribution.
#
# ### Majorization
#
# Suppose we want to sample from a distribution with PDF $f$.
# Suppose, further, that $f(u) \leq h(u) = M g(u), \forall u$ where $M$ is a constant > 1 and $g(u)$ is a (simple) pdf.
# By simple, we mean it's a pdf which is able to be defined easily (i.e. exponential)
#
# We say that $h(u)$ majorizes $f(u)$.
#
# The goal is to use samples from the (easy to generate) pdf $g(u)$ as "approximate samples" from $f(u)$.
# But it is clear that unless $g(u) \approx f(u), \forall u$, there will be samples from $g$ that are not representative of $f$.
# The idea is to throw away these "bad" samples using the **accept-reject algorithm (A.R. algo.)**.
# Rejection algorithm is a general algorithm to generate samples from a distribution with density $f$ (called the target denstiy) based only on the ability to generate from another distribution with density $g$ (usually referred to as the proposal density) s.t.
#
# $$sup_x \frac{f(x)}{g(x)} \leq M < \infty$$
#
# The basic algorithm is A.R. algorithm.
#
# Step 1: Generate $Y \sim g$ as proposal.
#
# Step 2: Generate $U \sim Unif(0,1)$.
#
# Step 3: If $U \leq \frac{f(Y)}{M g(Y)}$, set $X = Y$ (aka use as a sample). Otherwise, return to step 1 (aka reject sample).
#
# We are not generating anything from $X$. Everything is from $Y$. Our proposal $g$ is easier to sample than $f$.
#
# **IMPORTANT**: $g$ must have the same support as $f$.
#
# **Theorem**: (Part 1) The random variable generated by the A.R. algorithm has density $f$. (Part 2) The number of iterations in the A.R. algorithm follows a geometric distribution with mean $M$.
#
# **Proof:** (Part 2) The unconditoinal probability of acceptance is
#
# $$P(acc) = \sum_x P(acc | X=x) P(X=x)$$
#
# by the law of conditional probability
#
# $$= \sum_x P(U\leq \frac{f(x)}{M g(x)} | X = x) P(X = x)$$
#
# $$= \sum_x \frac{f(x)}{M g(x)} g(x) = \sum_x \frac{f(u)}{M} = \frac{1}{M} \sum_x f(u) = \frac{1}{M}$$
#
# Therefore, the probability to accept is $\frac{1}{M}$.
#
# Now, let $N = $ number of iterations in algorithm to set a value of $X$,
#
# $$P(N = n) = \frac{1}{M} (1 - \frac{1}{M})^{n-1}, n = 1, 2, ...$$
#
# This is the probability of $n$ iterations. This is a geometric distribution with mean $M$.
#
# i- Want to show that hte distribution of accepted ddraws is the same as the target distribution
#
# $$P(X = u | acc) = \frac{P(X=u, acc)}{P(acc)}$$
#
# $$= \frac{P(acc |X = x) \times P(X=x)}{P(acc)} = \frac{P(acc | X=u) \times g(x)}{1 / M}$$
#
# $$= \frac{f(u)}{M g(u)} \times M g(u) = f(u)$$
#
# Since the acceptance rate is $\frac{1}{M}$, you will need, on average, to generate $M \times n$ draws from the proposal distribution $g$ and from the uniform distribution to get $n$ draws from the target distribution $f$.
#
# It pays to find a sharp bound for $M$
#
# $$M = max_{u} \frac{f(u)}{g(u)}$$
#
# This can be solved by taking derivative and then solve for zero.
#
# **Example** Simulate normal RVs from double exponential RVs.
#
# Consider generating a $N(0,1)$ by using a double exponential distribution with density $g(x|\alpha) = \frac{\alpha}{2} \exp (-\alpha |x| ), \alpha > 0$, as proposal distribution.
#
# **Solution** $g$ is the double exponential. $f$ is the normal pdf.
#
# In order to use the A.R. algorithm, we need to find the value of $M$.
#
# Step 1: Let $h(x) = \frac{f(x)}{g(x)}$, then M = max_x h(x)$.
#
# $$h(x) = [ \frac{1}{\sqrt{2\pi}} \exp (- \frac{x^2}{2})] [ \frac{2}{\alpha} \exp (\alpha |x| )] $$
#
# $$= \frac{\sqrt{2}}{\alpha \sqrt{\pi}} \exp (- \frac{x^2}{2} + \alpha |x|)$$
#
# Step 2: Differentiate h, after taking $\log$ to simplify wrt x to find the maximum while ignoring the constants in front.
#
# $$\ln h(x) = - \frac{x^2}{2} + \alpha |x|$$
#
# $\frac{d}{dx} \ln h(x) = -x + \alpha$ and $\frac{d}{dx} \ln h(x) = -x - \alpha$
#
# Set equal to zero. We get $x = \pm \alpha$
#
# Step 3: To get the maximum, we plug this back into equation of $M$.
#
# $$M = \frac{2}{\alpha \sqrt{2\pi}} \exp (-\frac{\alpha^2}{2} + \alpha^2) = \frac{2}{\alpha \sqrt{2\pi}} \exp (\frac{\alpha^2}{2})$$
#
# $$ = \frac{2}{\sqrt{2\pi}} \alpha^{-1} \exp (\frac{\alpha^2}{2})$$
#
# Which depends on $\alpha$. So,
#
# Step 4: Minimize the differentiating wrt $\alpha$ to obtain the smallest $M$.
#
# $$\frac{d}{d \alpha} (\ln (\frac{1}{\alpha} \exp(\frac{\alpha^2}{2}))) = 0$$
#
# Therefore, $\alpha = \pm 1$
#
# But since $\alpha >0$, we choose $\alpha = 1$.
#
# Step 5: Insert $\alpha=1$ into the equation of $M$ given
#
# $$M = \sqrt{\frac{2}{\pi}} \exp(\frac{1}{2}) = \sqrt{\frac{2 e}{\pi}} \approx 1.32$$
#
# This is the minimum value. We can use numbers higher than this. However, the higher you go, the more values you'll have in sampling process.
#
# We know that the probability of acceptance is exactly $\frac{1}{M}$. Therefore, $P(acc) = \frac{1}{M} = \sqrt{\frac{\pi}{2 e}} \approx 0.76$
#
# ### **Algorithm: Normal from double exponential**
#
# Step 1: Generate $Y \sim double exp(1)$ (use inversion process above - start with uniform - find CDF of double exponential - inverse the x and y (=F(x)) variables - solve for x (piecewise))
#
# Step 2: Generate $U \sim Unif(0,1)$
#
# Step 3: If $U < \frac{f(y)}{M g(y)}$, accept $X = Y$. $g$ is the double exponentail and $f$ is the normal.
#
# Step 4: Otherwise return to step 1
# +
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm, laplace
M = 1.32
nsamples = 10000
alpha = 1
norm_mean = 3
norm_sigma = np.sqrt(2)
# Get a double exponential
u = np.random.uniform(0, 1, nsamples)
# double exponential is from (-inf, inf)
y = np.where(u > 0.5, -np.log(2*(1-u)), np.log(2*u))
hx = np.sqrt(2) / (alpha * np.sqrt(np.pi)) \
* np.exp(-(y**2 / 2) + alpha * np.abs(y)) \
* (1 / M)
U = np.random.uniform(0,1,nsamples)
accept_mask = U < hx
samples = norm_mean + norm_sigma*y[accept_mask]
x = np.linspace(-4,8,100)
plt.hist(samples,bins=50,density=True)
plt.plot(x,norm.pdf(x,norm_mean,norm_sigma))
plt.show()
# -
# ## Sampling a discrete distribution
#
# A discrete RV $X$ in a RV that has a probability mass function (pmf).
#
# $$p(x) = P(X=x) \forall x \in S$$
#
# where $S = \{ x_1, x_2, ..., x_k \}$ denotes the sample space and $k$ is the (possibly infinite) number of possible outcomes for the discrete variable $X$.
#
# Suppose that $S$ is ordered from smaller ot larger values. The CDF of $F$ is $F(x_j) = \sum_{i \leq j} p(x_i)$
#
# Discrete RV can be generated by slicing up the interval (0,1) into subintervals which define a partition of (0,1):
#
# $$[ (0, F(x_1)), (F(x_1), F(x_2)), (F(x_2), F(x_3)), ..., F((x_{k-1}), 1)]$$
#
# Generating $U \sim unif(0,1)$ and seeing which subintervals $U$ falls into.
#
# Set $I_j = \Iota (U \in F(x_{j-1}), F(x_j)) = \begin{cases}
# 1 & if U \in (F(x_{j-1}), F(x_j))\\
# 0 & otherwise\\
# \end{cases}$
#
# $$P(I_j = 1) P(F(x_{j-1}) \leq U \leq F(x_j)) = F(x_j) - F(x_{j-1}) = p(x_j) = P(X = x_j)$$
#
# where $F(x_0)$ is defiend to be 0. This means that the probability that $I_j = 1$ is the same as the probability that $X = x_j$. This can be used to generate from the distribution sf $x$.
#
# **Example:**
# S = \{1, 2, 3 \}$ with pmf defined by
#
# $$
# \begin{matrix}
# \mathbf{x} & 1 & 2 & 3\\
# \mathbf{p(x)} & p_1 & p_2 & p_3\\
# \end{matrix}
# $$
#
# To generate this distribution, we partition (0,1) into 3 subintervals $(0, p_1), (p_1, p_1 + p_2), (p_1 + p_2, p_1 + p_2 + p_3)$. Here, $p_1$ is $F(x_1)$ and $p_1 + p_2$ is $F(x_2)$, and $p_1 + p_2 + p_3 = 1$ at the end of the CDF.
#
# Our task: generate a $unif(0,1)$ and check which interval $U$ falls into (out of the 3 subintervals above).
#
# Assume that $p_1 = 0.4$, $p_2 = 0.25$, and $p_3 = 0.35$.
#
# Therefore, the subintervals are (0, 0.4), (0.4, 0.65), and (0.65, 1).
#
# ### Algorithm: sample a discrete distribution
#
# Step 1: Generate $U \sim Unif(0,1)$
#
# Step 2: Deliver 1 if $0 < U \leq 0.4$. Deliver 2 if $0.4 < U \leq 0.65$. Deliver 3 if $0.65 < U \leq 1$.
#
# +
import numpy as np
nsamples = 100000
u = np.random.uniform(0,1, nsamples)
ones = sum((u > 0) & (u <= 0.4))
twos = sum((u > 0.4) & (u <= 0.65))
threes = sum((u > 0.65) & (u <= 1))
np.array([ones, twos, threes]) / nsamples
| HopML/Inversion methods.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/100rab-S/TensorFlow-Advanced-Techniques/blob/main/C1W3_L2_CustomDenseLayer.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="4TUw0gRnF3uS"
# # Ungraded Lab: Building a Custom Dense Layer
#
# In this lab, we'll walk through how to create a custom layer that inherits the [Layer](https://keras.io/api/layers/base_layer/#layer-class) class. Unlike simple Lambda layers you did previously, the custom layer here will contain weights that can be updated during training.
# + [markdown] id="k10QkEUzF3ut"
# ## Imports
# + id="DpioxwFXD9Is"
try:
# # %tensorflow_version only exists in Colab.
# %tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
import numpy as np
# + [markdown] id="K9ibc1EQF3u0"
# ## Custom Layer with weights
#
# To make custom layer that is trainable, we need to define a class that inherits the [Layer](https://keras.io/api/layers/base_layer/#layer-class) base class from Keras. The Python syntax is shown below in the class declaration. This class requires three functions: `__init__()`, `build()` and `call()`. These ensure that our custom layer has a *state* and *computation* that can be accessed during training or inference.
# + id="jnVrzRT6BPWl"
# inherit from this base class
from tensorflow.keras.layers import Layer
class SimpleDense(Layer):
def __init__(self, units=32): #the default value for units is being set to 32 in this layer
'''Initializes the instance attributes'''
super(SimpleDense, self).__init__()
self.units = units
def build(self, input_shape):
'''Create the state of the layer (weights). It initializes both weight and bias for each unit in the layer.'''
# initialize the weights
w_init = tf.random_normal_initializer()
self.w = tf.Variable(name="kernel", initial_value=w_init(shape=(input_shape[-1], self.units), dtype='float32'),
trainable=True)
# initialize the biases
b_init = tf.zeros_initializer()
self.b = tf.Variable(name="bias", initial_value=b_init(shape=(self.units,), dtype='float32'), trainable=True)
def call(self, inputs):
'''Defines the computation from inputs to outputs.'''
return tf.matmul(inputs, self.w) + self.b
# + [markdown] id="bELAiWKOF3u7"
# Now we can use our custom layer like below:
# + id="mtQc91hwF3vD" colab={"base_uri": "https://localhost:8080/"} outputId="07f92a3e-f271-4a78-f1d6-0772a6c43d79"
# declare an instance of the class
my_dense = SimpleDense(units=1)
# define an input and feed into the layer
x = tf.ones((1, 1))
y = my_dense(x)
# parameters of the base Layer class like `variables` can be used
print(my_dense.variables)
# + [markdown] id="mZiBRINuF3vH"
# Let's then try using it in simple network:
# + id="WwTPJT4DkTyW" colab={"base_uri": "https://localhost:8080/"} outputId="7801a9b2-2894-4c40-c846-1bd2fba4b2ea"
# define the dataset
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)
# use the Sequential API to build a model with our custom layer
my_layer = SimpleDense(units=1)
model = tf.keras.Sequential([my_layer])
# configure and train the model
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(xs, ys, epochs=500,verbose=0)
# perform inference
print(model.predict([10.0]))
# see the updated state of the variables
print(my_layer.variables)
| C1W3_L2_CustomDenseLayer.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ###### Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2014 <NAME>, <NAME>, <NAME>. Based on [CFD Python](https://github.com/barbagroup/CFDPython), (c)2013 <NAME>, also under CC-BY.
# # Space & Time
# ## Introduction to numerical solution of PDEs
# Welcome to *Space and Time: Introduction to finite-difference solutions of PDEs*, the second module of ["Practical Numerical Methods with Python"](https://openedx.seas.gwu.edu/courses/course-v1:MAE+MAE6286+2017/about).
#
# In the first module, we looked into numerical integration methods for the solution of ordinary differential equations (ODEs), using the phugoid model of glider flight as a motivation. In this module, we will study the numerical solution of *partial differential equations (PDEs)*, where the unknown is a multi-variate function. The problem could depend on time, $t$, and one spatial dimension $x$ (or more), which means we need to build a discretization grid with each independent variable.
#
# We will start our discussion of numerical PDEs with 1-D linear and non-linear convection equations, the 1-D diffusion equation, and 1-D Burgers' equation. We hope you will enjoy them!
# ## 1D linear convection
# The *one-dimensional linear convection equation* is the simplest, most basic model that can be used to learn something about numerical solution of PDEs. It's surprising that this little equation can teach us so much! Here it is:
#
# $$
# \begin{equation}
# \frac{\partial u}{\partial t} + c \frac{\partial u}{\partial x} = 0
# \end{equation}
# $$
#
# The equation represents a *wave* propagating with speed $c$ in the $x$ direction, without change of shape. For that reason, it's sometimes called the *one-way wave equation* (sometimes also the *advection equation*).
#
# With an initial condition $u(x,0)=u_0(x)$, the equation has an exact solution given by:
#
# $$
# \begin{equation}
# u(x,t)=u_0(x-ct)
# \end{equation}
# $$
#
# Go on: check it. Take the time and space derivative and stick them into the equation to see that it holds!
#
# Look at the exact solution for a moment ... we know two things about it:
#
# 1. its shape does not change, being always the same as the initial wave, $u_0$, only shifted in the $x$-direction; and
# 2. it's constant along so-called **characteristic curves**, $x-ct=$constant. This means that for any point in space and time, you can move back along the characteristic curve to $t=0$ to know the value of the solution.
# 
# #### Characteristic curves for positive wave speed.
# Why do we call the equations *linear*? PDEs can be either linear or non-linear. In a linear equation, the unknown function $u$ and its derivatives appear only in linear terms, in other words, there are no products, powers, or transcendental functions applied on them.
#
# What is the most important feature of linear equations? Do you remember? In case you forgot: solutions can be superposed to generate new solutions that still satisfy the original equation. This is super useful!
# ## Finite-differences
# In the previous lessons, we discretized time derivatives; now we have derivatives in both space *and* time, so we need to discretize with respect to *both* these variables.
#
# Imagine a *space-time* plot, where the coordinates in the vertical direction represent advancing in timeโfor example, from $t^n$ to $t^{n+1}$โand the coordinates in the horizontal direction move in space: consecutive points are $x_{i-1}$, $x_i$, and $x_{i+1}$. This creates a grid where a point has both a temporal and spatial index. Here is a graphical representation of the space-time grid:
#
# $$
# \begin{matrix}
# t^{n+1} & \rightarrow & \bullet && \bullet && \bullet \\
# t^n & \rightarrow & \bullet && \bullet && \bullet \\
# & & x_{i-1} && x_i && x_{i+1}
# \end{matrix}
# $$
#
# For the numerical solution of $u(x,t)$, we'll use subscripts to denote the spatial position, like $u_i$, and superscripts to denote the temporal instant, like $u^n$. We would then label the solution at the top-middle point in the grid above as follows:
# $u^{n+1}_{i}$.
#
# Each grid point below has an index $i$, corresponding to the spatial position and increasing to the right, and an index $n$, corresponding to the time instant and increasing upwards. A small grid segment would have the following values of the numerical solution at each point:
#
# $$
# \begin{matrix}
# & &\bullet & & \bullet & & \bullet \\
# & &u^{n+1}_{i-1} & & u^{n+1}_i & & u^{n+1}_{i+1} \\
# & &\bullet & & \bullet & & \bullet \\
# & &u^n_{i-1} & & u^n_i & & u^n_{i+1} \\
# & &\bullet & & \bullet & & \bullet \\
# & &u^{n-1}_{i-1} & & u^{n-1}_i & & u^{n-1}_{i+1} \\
# \end{matrix}
# $$
#
# Another way to explain our discretization grid is to say that it is built with constant steps in time and space, $\Delta t$ and $\Delta x$, as follows:
#
# $$
# \begin{eqnarray}
# x_i &=& i\, \Delta x \quad \text{and} \quad t^n= n\, \Delta t \nonumber \\
# u_i^n &=& u(i\, \Delta x, n\, \Delta t)
# \end{eqnarray}
# $$
# ### Discretizing our model equation
# Let's see how to discretize the 1-D linear convection equation in both space and time. By definition, the partial derivative with respect to time changes only with time and not with space; its discretized form changes only the $n$ indices. Similarly, the partial derivative with respect to $x$ changes with space not time, and only the $i$ indices are affected.
#
# We'll discretize the spatial coordinate $x$ into points indexed from $i=0$ to $N$, and then step in discrete time intervals of size $\Delta t$.
#
# From the definition of a derivative (and simply removing the limit), we know that for $\Delta x$ sufficiently small:
#
# $$
# \begin{equation}
# \frac{\partial u}{\partial x}\approx \frac{u(x+\Delta x)-u(x)}{\Delta x}
# \end{equation}
# $$
#
# This formula could be applied at any point $x_i$. But note that it's not the only way that we can estimate the derivative. The geometrical interpretation of the first derivative $\partial u/ \partial x$ at any point is that it represents the slope of the tangent to the curve $u(x)$. In the sketch below, we show a slope line at $x_i$ and mark it as "exact." If the formula written above is applied at $x_i$, it approximates the derivative using the next spatial grid point: it is then called a _forward difference_ formula.
#
# But as shown in the sketch below, we could also estimate the spatial derivative using the point behind $x_i$, in which case it is called a _backward difference_. We could even use the two points on each side of $x_i$, and obtain what's called a _central difference_ (but in that case the denominator would be $2\Delta x$).
# 
# #### Three finite-difference approximations at $x_i$.
# We have three possible ways to represent a discrete form of $\partial u/ \partial x$:
#
# * Forward difference: uses $x_i$ and $x_i + \Delta x$,
# * Backward difference: uses $x_i$ and $x_i- \Delta x$,
# * Central difference: uses two points on either side of $x_i$.
#
# The sketch above also suggests that some finite-difference formulas might be better than others: it looks like the *central difference* approximation is closer to the slope of the "exact" derivative. Curious if this is just an effect of our exaggerated picture? We'll show you later how to make this observation rigorous!
#
# The three formulas are:
#
# $$
# \begin{eqnarray}
# \frac{\partial u}{\partial x} & \approx & \frac{u(x_{i+1})-u(x_i)}{\Delta x} \quad\text{Forward}\\
# \frac{\partial u}{\partial x} & \approx & \frac{u(x_i)-u(x_{i-1})}{\Delta x} \quad\text{Backward}\\
# \frac{\partial u}{\partial x} & \approx & \frac{u(x_{i+1})-u(x_{i-1})}{2\Delta x} \quad\text{Central}
# \end{eqnarray}
# $$
#
# Euler's method is equivalent to using a forward-difference scheme for the time derivative. Let's stick with that, and choose the backward-difference scheme for the space derivative. Our discrete equation is then:
#
# $$
# \begin{equation}
# \frac{u_i^{n+1}-u_i^n}{\Delta t} + c \frac{u_i^n - u_{i-1}^n}{\Delta x} = 0
# \end{equation}
# $$
#
# where $n$ and $n+1$ are two consecutive steps in time, while $i-1$ and $i$ are two neighboring points of the discretized $x$ coordinate. With given initial conditions, the only unknown in this discretization is $u_i^{n+1}$. We solve for this unknown to get an equation that lets us step in time, as follows:
#
# $$
# \begin{equation}
# u_i^{n+1} = u_i^n - c \frac{\Delta t}{\Delta x}(u_i^n-u_{i-1}^n)
# \end{equation}
# $$
#
# We like to make drawings of a grid segment, showing the grid points that influence our numerical solution. This is called a **stencil**. Below is the stencil for solving our model equation with the finite-difference formula we wrote above.
# 
# #### Stencil for the "forward-time/backward-space" scheme.
# ## And compute!
# Alright. Let's get a little Python on the road. First: we need to load our array and plotting libraries, as usual.
import numpy
from matplotlib import pyplot
# %matplotlib inline
# We also set notebook-wide plotting parameters for the font family and the font size by modifying entries of the `rcParams` dictionary.
# Set the font family and size to use for Matplotlib figures.
pyplot.rcParams['font.family'] = 'serif'
pyplot.rcParams['font.size'] = 16
# As a first exercise, we'll solve the 1D linear convection equation with a *square wave* initial condition, defined as follows:
#
# $$
# \begin{equation}
# u(x,0)=\begin{cases}2 & \text{where } 0.5\leq x \leq 1,\\
# 1 & \text{everywhere else in } (0, 2)
# \end{cases}
# \end{equation}
# $$
#
# We also need a boundary condition on $x$: let $u=1$ at $x=0$. Our spatial domain for the numerical solution will only cover the range $x\in (0, 2)$.
# 
# #### Square wave initial condition.
# Now let's define a few variables; we want to make an evenly spaced grid of points within our spatial domain. In the code below, we define a variable called `nx` that will be the number of spatial grid points, and a variable `dx` that will be the distance between any pair of adjacent grid points. We also can define a step in time, `dt`, a number of steps, `nt`, and a value for the wave speed: we like to keep things simple and make $c=1$.
# +
# Set parameters.
nx = 41 # number of spatial discrete points
L = 2.0 # length of the 1D domain
dx = L / (nx - 1) # spatial grid size
nt = 25 # number of time steps
dt = 0.02 # time-step size
c = 1.0 # convection speed
# Define the grid point coordinates.
x = numpy.linspace(0.0, L, num=nx)
# -
# We also need to set up our initial conditions. Here, we use the NumPy function `numpy.ones()` defining an array which is `nx`-element long with every value equal to $1$. How useful! We then *change a slice* of that array to the value $u=2$, to get the square wave, and we print out the initial array just to admire it. But which values should we change? The problem states that we need to change the indices of `u` such that the square wave begins at $x = 0.5$ and ends at $x = 1$.
#
# We can use the [`numpy.where()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) function to return a list of indices where the vector $x$ meets some conditions.
# The function [`numpy.logical_and()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html) computes the truth value of `x >= 0.5` **and** `x <= 1.0`, element-wise.
# Set initial conditions with 1.0 everywhere (for now).
u0 = numpy.ones(nx)
# Get a list of indices where 0.5 <= x <= 1.0.
mask = numpy.where(numpy.logical_and(x >= 0.5, x <= 1.0))
print(mask)
# With the list of indices, we can now update our initial conditions to get a square-wave shape.
# Set initial condition u = 2.0 where 0.5 <= x <= 1.0.
u0[mask] = 2.0
print(u0)
# Now let's take a look at those initial conditions we've built with a handy plot.
# Plot the initial conditions.
pyplot.figure(figsize=(4.0, 4.0))
pyplot.title('Initial conditions')
pyplot.xlabel('x')
pyplot.ylabel('u')
pyplot.grid()
pyplot.plot(x, u0, color='C0', linestyle='--', linewidth=2)
pyplot.xlim(0.0, L)
pyplot.ylim(0.0, 2.5);
# It does look pretty close to what we expected. But it looks like the sides of the square wave are not perfectly vertical. Is that right? Think for a bit.
# Now it's time to write some code for the discrete form of the convection equation using our chosen finite-difference scheme.
#
# For every element of our array `u`, we need to perform the operation:
#
# $$
# u_i^{n+1} = u_i^n - c \frac{\Delta t}{\Delta x}(u_i^n-u_{i-1}^n)
# $$
#
# We'll store the result in a new (temporary) array `un`, which will be the solution $u$ for the next time-step. We will repeat this operation for as many time-steps as we specify and then we can see how far the wave has traveled.
#
# We first initialize the placeholder array `un` to hold the values we calculate for the $n+1$ time step, using once again the NumPy function `ones()`.
#
# Then, we may think we have two iterative operations: one in space and one in time (we'll learn differently later), so we may start by nesting a spatial loop inside the time loop, as shown below. You see that the code for the finite-difference scheme is a direct expression of the discrete equation:
u = u0.copy()
for n in range(1, nt):
un = u.copy()
for i in range(1, nx):
u[i] = un[i] - c * dt / dx * (un[i] - un[i - 1])
# **Note 1**โWe stressed above that our physical problem needs a boundary condition at $x=0$. Here we do not need to impose it at every iteration because our discretization does not change the value of u[0]: it remains equal to one and our boundary condition is therefore satisfied during the whole computation!
#
# **Note 2**โWe will learn later that the code as written above is quite inefficient, and there are better ways to write this, Python-style. But let's carry on.
#
# Now let's inspect our solution array after advancing in time with a line plot.
# Plot the solution after nt time steps
# along with the initial conditions.
pyplot.figure(figsize=(4.0, 4.0))
pyplot.xlabel('x')
pyplot.ylabel('u')
pyplot.grid()
pyplot.plot(x, u0, label='Initial',
color='C0', linestyle='--', linewidth=2)
pyplot.plot(x, u, label='nt = {}'.format(nt),
color='C1', linestyle='-', linewidth=2)
pyplot.legend()
pyplot.xlim(0.0, L)
pyplot.ylim(0.0, 2.5);
# That's funny. Our square wave has definitely moved to the right, but it's no longer in the shape of a top-hat. **What's going on?**
# ##### Dig deeper
# The solution differs from the expected square wave because the discretized equation is an approximation of the continuous differential equation that we want to solve. There are errors: we knew that. But the modified shape of the initial wave is something curious. Maybe it can be improved by making the grid spacing finer. Why don't you try it? Does it help?
# ## Spatial truncation error
# Recall the finite-difference approximation we are using for the spatial derivative:
#
# $$
# \begin{equation}
# \frac{\partial u}{\partial x}\approx \frac{u(x+\Delta x)-u(x)}{\Delta x}
# \end{equation}
# $$
#
# We obtain it by using the definition of the derivative at a point, and simply removing the limit, in the assumption that $\Delta x$ is very small. But we already learned with Euler's method that this introduces an error, called the *truncation error*.
#
# Using a Taylor series expansion for the spatial terms now, we see that the backward-difference scheme produces a first-order method, in space.
# $$
# \begin{equation}
# \frac{\partial u}{\partial x}(x_i) = \frac{u(x_i)-u(x_{i-1})}{\Delta x} + \frac{\Delta x}{2} \frac{\partial^2 u}{\partial x^2}(x_i) - \frac{\Delta x^2}{6} \frac{\partial^3 u}{\partial x^3}(x_i)+ \cdots
# \end{equation}
# $$
#
# The dominant term that is neglected in the finite-difference approximation is of $\mathcal{O}(\Delta x)$. We also see that the approximation *converges* to the exact derivative as $\Delta x \rightarrow 0$. That's good news!
#
# In summary, the chosen "forward-time/backward space" difference scheme is first-order in both space and time: the truncation errors are $\mathcal{O}(\Delta t, \Delta x)$. We'll come back to this!
# ## Non-linear convection
# Let's move on to the non-linear convection equation, using the same methods as before. The 1-D convection equation is:
#
# $$
# \begin{equation}
# \frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} = 0
# \end{equation}
# $$
#
# The only difference with the linear case is that we've replaced the constant wave speed $c$ by the variable speed $u$. The equation is non-linear because now we have a product of the solution and one of its derivatives: the product $u\,\partial u/\partial x$. This changes everything!
#
# We're going to use the same discretization as for linear convection: forward difference in time and backward difference in space. Here is the discretized equation:
#
# $$
# \begin{equation}
# \frac{u_i^{n+1}-u_i^n}{\Delta t} + u_i^n \frac{u_i^n-u_{i-1}^n}{\Delta x} = 0
# \end{equation}
# $$
#
# Solving for the only unknown term, $u_i^{n+1}$, gives an equation that can be used to advance in time:
#
# $$
# \begin{equation}
# u_i^{n+1} = u_i^n - u_i^n \frac{\Delta t}{\Delta x} (u_i^n - u_{i-1}^n)
# \end{equation}
# $$
#
# There is very little that needs to change from the code written so far. In fact, we'll even use the same square-wave initial condition. But let's re-initialize the variable `u` with the initial values, and re-enter the numerical parameters here, for convenience (we no longer need $c$, though).
# +
# Set parameters.
nx = 41 # number of spatial discrete points
L = 2.0 # length of the 1D domain
dx = L / (nx - 1) # spatial grid size
nt = 10 # number of time steps
dt = 0.02 # time-step size
x = numpy.linspace(0.0, L, num=nx)
u0 = numpy.ones(nx)
mask = numpy.where(numpy.logical_and(x >= 0.5, x <= 1.0))
u0[mask] = 2.0
# -
# How does it look?
# Plot the initial conditions.
pyplot.figure(figsize=(4.0, 4.0))
pyplot.title('Initial conditions')
pyplot.xlabel('x')
pyplot.ylabel('u')
pyplot.grid()
pyplot.plot(x, u0, color='C0', linestyle='--', linewidth=2)
pyplot.xlim(0.0, L)
pyplot.ylim(0.0, 2.5);
# Changing just one line of code in the solution of linear convection, we are able to now get the non-linear solution: the line that corresponds to the discrete equation now has `un[i]` in the place where before we just had `c`. So you could write something like:
#
# ```Python
# for n in range(1, nt):
# un = u.copy()
# for i in range(1, nx):
# u[i] = un[i] - un[i]*dt/dx*(un[i]-un[i-1])
# ```
#
# We're going to be more clever than that and use NumPy to update all values of the spatial grid in one fell swoop. We don't really need to write a line of code that gets executed *for each* value of $u$ on the spatial grid. Python can update them all at once! Study the code below, and compare it with the one above. Here is a helpful sketch, to illustrate the array operationโalso called a "vectorized" operationโfor $u_i-u_{i-1}$.
# 
#
# <br>
# #### Sketch to explain vectorized stencil operation. Adapted from ["Indices point between elements"](https://blog.nelhage.com/2015/08/indices-point-between-elements/) by <NAME>.
# Compute the solution using Euler's method and array slicing.
u = u0.copy()
for n in range(1, nt):
u[1:] = u[1:] - dt / dx * u[1:] * (u[1:] - u[:-1])
# Plot the solution after nt time steps
# along with the initial conditions.
pyplot.figure(figsize=(4.0, 4.0))
pyplot.xlabel('x')
pyplot.ylabel('u')
pyplot.grid()
pyplot.plot(x, u0, label='Initial',
color='C0', linestyle='--', linewidth=2)
pyplot.plot(x, u, label='nt = {}'.format(nt),
color='C1', linestyle='-', linewidth=2)
pyplot.legend()
pyplot.xlim(0.0, L)
pyplot.ylim(0.0, 2.5);
# Hmm. That's quite interesting: like in the linear case, we see that we have lost the sharp sides of our initial square wave, but there's more. Now, the wave has also lost symmetry! It seems to be lagging on the rear side, while the front of the wave is steepening. Is this another form of numerical error, do you ask? No! It's physics!
# ##### Dig deeper
# Think about the effect of having replaced the constant wave speed $c$ by the variable speed given by the solution $u$. It means that different parts of the wave move at different speeds. Make a sketch of an initial wave and think about where the speed is higher and where it is lower ...
# ## References
#
# * <NAME> (2015), ["Indices point between elements"](https://blog.nelhage.com/2015/08/indices-point-between-elements/)
# ---
#
# ###### 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())
| lessons/02_spacetime/02_01_1DConvection.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: brandon_env
# language: python
# name: brandon_env
# ---
# ### GitHub README Extraction
#
# During this summer, the DSGP OSS 2021 team willbe classifying GitHub repositores into different software types. To do this, we will be extracting README files from all of the OSS repos (i.e. those with OSS licenses) and then developing NLP techniques to classify those repos.
#
# In this file, we document the extraction process for GitHub README files.
# +
# load packages
import os
import pandas as pd
import string
import requests as r
import json
import base64
import urllib.request
import itertools
from bs4 import BeautifulSoup
from dotenv import load_dotenv
# +
logins = ["brandonleekramer", "uva-bi-sdad", "facebook"]
repos = [ "diversity", "oss-2020", "react"]
for login, repo in zip(logins, repos):
url = f'https://github.com/{login}/{repo}/'
urllib.request.urlretrieve(url, f'readme_{login}_{repo}.txt')
print(f'Finished scraping: {login}/{repo}')
| src/10_scrape-repos/.ipynb_checkpoints/scrape_readmes-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ###### Star Type Classification
# For comparing all models of ML
# It can be used for prediction
#
# Temperature -- K
# L -- L/Lo
# R -- R/Ro
# AM -- Mv
# Color -- General Color of Spectrum
# Spectral_Class -- O,B,A,F,G,K,M / SMASS - https://en.wikipedia.org/wiki/Asteroid_spectral_types
# Type -- Red Dwarf, Brown Dwarf, White Dwarf, Main Sequence , Super Giants, Hyper Giants
#
# TARGET:
# Type
#
# from 0 to 5
#
# Red Dwarf - 0
# Brown Dwarf - 1
# White Dwarf - 2
# Main Sequence - 3
# Super Giants - 4
# Hyper Giants - 5
# MATH:
#
# Lo = 3.828 x 10^26 Watts
# (Avg Luminosity of Sun)
# Ro = 6.9551 x 10^8 m
# (Avg Radius of Sun)
# +
import numpy as np
import pandas as pd
import seaborn as sb
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix, precision_score, recall_score, f1_score
# -
df = pd.read_csv(r'F:\dataset\Stars.csv')
df.head(n=10)
df.isnull().sum()
# There is no missing values in the dataset.
print(df.shape)
df.describe()
# Let's find the correlation between the features and how they are related and also plot the heatmap.
corr = df.corr()
plt.figure(figsize=(10,8))
sb.heatmap(corr, annot=True)
plt.title("Pearson's correlation heatmap", fontsize=20)
corr.Type
# We can notice that except A_M all other features are positively correlated. Let plot the graph for visualization.
df.corr()['Type'][['Temperature', 'L', 'R', 'A_M']].plot.bar()
sb.pairplot(data=df,hue='Type')
df_col = df.loc[:, ['Temperature', 'L', 'R', 'A_M']]
for col_nm in df_col:
plt.figure(figsize=(12,6))
sb.barplot(x=df['Type'], y=df_col[col_nm])
plt.title(col_nm+' barplot',fontsize=20)
plt.xlabel('Type', fontsize=14)
plt.ylabel(col_nm, fontsize=14)
plt.show()
# From graph Type vs temperature it is clear that type 2, 3, 4, 5 has higher surface temperature than type 1 and 2 star.
# From graph Type vs L shows that the luminousity of type 4, 5 star is far greater than rest.
# In graph Type vs R, the type 5 star is far larger in size than the rest of the star.
# Graph Type vs A_M, we can see the type 0, 1, 2 star have positive absolute magnitude ie they are less brighter as compared to type 4, 5 stars which have negative absolute magnitude.
# Now let's plot boxplot to see how the stars are distributed according to their features.
for col_nm in df_col:
plt.figure(figsize=(12,1.5))
sb.boxplot(x=df_col[col_nm])
plt.title(col_nm+' boxplot',fontsize=20)
plt.xlabel(col_nm, fontsize=14)
plt.show()
# Also boxplotting Temperature, L, R, A_M vs. Type to get some idea regarding the distribution of stars according to their Type.
# +
# Boxplots per target variable values
for col_nm in df_col:
plt.figure(figsize=(12,6))
sb.boxplot(data = df, x = df_col[col_nm], y ='Type', orient = 'h')
plt.title(col_nm +' distribution per value of Type', fontsize = 20)
plt.xlabel(col_nm, fontsize=14)
plt.ylabel('Type')
plt.show()
# -
for col_nm in df_col:
plt.figure(figsize=(12,6))
sb.distplot(df_col[col_nm], hist=True, kde=True, bins=int(180/15), color='darkblue',
hist_kws=dict(edgecolor='black', linewidth=2))
plt.title(col_nm +' Histogram', fontsize = 20)
plt.xlabel(col_nm, fontsize=14)
plt.show()
# Getting the count of all the type of colors present in the dataset.
df['Color'].value_counts()
# We see there are different types of similar colors. We can group them together to a color to which they are strongly related. This will help to simplify our data. Let's do it.
x=['Blue-white','yellow-white','Blue White', 'Blue white', 'Yellowish White', 'white', 'Whitish', 'Blue-White', 'White-Yellow']
for i in x:
df.loc[df['Color']==i, 'Color']='White'
x=['yellowish','Yellowish']
for i in x:
df.loc[df['Color']==i, 'Color']='Yellow'
x=['Pale yellow orange','Orange-Red']
for i in x:
df.loc[df['Color']==i, 'Color']='Orange'
df['Color'].value_counts()
# We grouped all the stars to five colors namely, 'Red', 'White', 'Blue', 'Orange', and 'Yellow'.
# Now let's encode all the Color column and Spectral class name categorical data to numeric values.
# +
from sklearn.preprocessing import LabelEncoder
df['Color'] = LabelEncoder().fit_transform(df['Color'])
df['Spectral_Class'] = LabelEncoder().fit_transform(df['Spectral_Class'])
print(df['Color'].unique())
print(df['Spectral_Class'].unique())
# -
df.head()
# For training our model, we will be using Random Forest classifier and K Nearest Neighbor Classifier and compare the results.
X=df.drop('Type', axis=1)
Y=df['Type']
print(X.shape, Y.shape)
# +
# Using MinMaxScaler to scale the input data.
x_scaled = MinMaxScaler().fit_transform(X)
x_scaled
# -
# We will be splitting the data into 70% train set and 30% test set.
X_train, X_test, y_train, y_test = train_test_split(x_scaled, Y, test_size=0.4, random_state=47)
print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
# +
# Creating a function for training the model and calculating metrics.
def model_training(X_train, X_test, y_train, y_test, model):
model.fit(X_train, y_train)
y_hat = model.predict(X_test)
accuracy = accuracy_score(y_test, y_hat)
cm = confusion_matrix(y_test, y_hat)
c_report = classification_report(y_test, y_hat)
precision = precision_score(y_test, y_hat, average='micro')
recall = recall_score(y_test, y_hat, average='micro')
f1 = f1_score(y_test, y_hat, average='micro')
return accuracy, cm, precision, recall, f1, c_report
# +
# Using RandomForestClassifier.
rfc = RandomForestClassifier(random_state=42,
n_estimators= 250,
criterion= 'gini',
max_depth= 5,
max_features= 'log2',
min_samples_leaf= 4,
min_samples_split= 3,)
accuracy, cm, precision, recall, f1, c_report = model_training(X_train, X_test, y_train, y_test, rfc)
print('Accuracy :', accuracy)
print('--------------------------------------------')
print('Confusion Matrix :\n', cm)
print('--------------------------------------------')
print('Classification Report :\n', c_report)
print('--------------------------------------------')
print('Precision: %.3f ' % precision)
print('Recall: %.3f ' % recall)
print('F1 score: %.3f' % f1)
# +
# Plotting the feature importance.
features = X.columns
imp = rfc.feature_importances_
plt.figure(figsize=(12,6))
plt.bar(features, imp)
plt.show()
# -
# From the above graph, it is visible that features R and A_M are most useful in predicting the target value.
# +
knn = KNeighborsClassifier(n_neighbors=6, leaf_size=1, p=2)
accuracy, cm, precision, recall, f1, c_report = model_training(X_train, X_test, y_train, y_test, knn)
print('Accuracy :', accuracy)
print('--------------------------------------------')
print('Confusion Matrix :\n', cm)
print('--------------------------------------------')
print('Classification Report :\n', c_report)
print('--------------------------------------------')
print('Precision: %.3f ' % precision)
print('Recall: %.3f ' % recall)
print('F1 score: %.3f' % f1)
# +
neighbors = np.arange(1, 7)
train_accuracy = np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
for i, k in enumerate(neighbors):
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
# Compute training and test data accuracy
train_accuracy[i] = knn.score(X_train, y_train)
test_accuracy[i] = knn.score(X_test, y_test)
# Generate plot
plt.plot(neighbors, test_accuracy, label = 'Testing dataset Accuracy')
plt.plot(neighbors, train_accuracy, label = 'Training dataset Accuracy')
plt.legend()
plt.xlabel('n_neighbors')
plt.ylabel('Accuracy')
plt.show()
# -
# Comparing the above two models, we got 100% accuracy for Random Forest Classifier and 97.9% for K Nearest Neighbors classifier. Thus, Random Forest Classifier is better in predicting the type of star than KNN Classifier.
| stars_classification.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] hide_input=true
# # Discretising differential equations
# -
# ## The problem
#
# Consider the first-order lowpass RC circuit below:
#
# 
#
# The input signal $x(t)$ is the source voltage and the output $y(t)$ is the voltage across the capacitor.
#
# Using standard techniques the governing differential equation is found to be
# $$y(t) + RC \frac{dy(t)}{dt} = x(t).$$
# (You should check this result.) For known $x(t)$ we can use this equation to solve for the corresponding output $y(t)$. This is a first-order differential equation in $y(t)$, so one auxiliary condition will be required to specify $y(t)$ fully (think of homogeneous and particular solutions).
#
# We want to find an approximate numerical solution for $y(t)$ when the input is the unit step $x(t) = u(t)$. The auxiliary condition will be that the output is zero for nonpositive values of time: $y(t) = 0$ for $t \leq 0$. For the circuit this means that the capacitor is initially discharged before the arrival of the step at $t=0$, or an *initial rest* condition.
# ## Approach
#
# The signals $x(t)$ and $y(t)$ are functions of a real-valued time variable. This makes them difficult to represent in a computer: we need to store the value of each signal at an uncountably infinite set of time instants. Symbolic computation might work for the problem described (try it?), but only because the input is simple.
#
# In the physical world nothing changes infinitely fast, so you have the sense that if you sample $x(t)$ and $y(t)$ sufficiently finely you'll capture most of the detail. We almost always sample regularly, or periodically. For example the signal $x(t)$ can be approximated by the set of sample values $x(nT)$ for some small fixed $T$, where $n$ runs over the integers. This is still admittedly an infinite set, but at least now it's countable: if we're only considering signals over a finite interval we can store the values on a computer. We will formalise the sense in which this approximation is valid during this course.
#
# Once we've discretised the signals, we can also make a discrete appoximation to the differential equation. This can be done in many ways. The approximate output can then be found from the approximate input and the approximate differential equation.
# ### Discretise the signals
#
# Set up a discrete coordinate system with spacing $T$ such that $t = nT$ for integer $n$. We need to specify $T$ in advance: its value should be small enough to give the required accuracy. It's possible to formulate this precisely, but for our numerical approximation we just make it as small as we can.
#
# The sampled (discrete) signals are
# $$x[n] = x(nT) \qquad \text{and} \qquad y[n] = y(nT).$$
# Applying the initial conditions for the problem we get $y[n]=0$ for $n \leq 0$, and more specifically $y[0] = 0$.
# ### Discretise the system
#
# When solving first order differential equations it is common to write them in the standard form $y'(t) = f(t, y(t))$, where $y'(t)$ is the time derivative of $y(t)$. Thus for the RC circuit we have
# $$\frac{dy(t)}{dt} = \frac{1}{RC} (x(t) - y(t)).$$
# If we discretise the system differential equation by sampling at $t=nT$ we get
# $$\frac{dy(nT)}{dt} = \frac{1}{RC} (x(nT) - y(nT)).$$
# The time derivative of $y(t)$ is the complicated part of this expression.
#
# Using what you know about derivatives,
# $$\frac{dy(t)}{dt} = \lim_{h \to 0} \frac{y(t+h) - y(t)}{h}
# \approx \frac{y(t+T) - y(t)}{T} \quad \text{for small $T$}.$$
# This involves the limit "from the right", and is called the "forward difference" approximation to the derivative.
#
# Substituting into the discretised system differential equation gives
# $$\frac{y(nT+T) - y(nT)}{T} \approx \frac{1}{RC} (x(nT) - y(nT)).$$
# This involves values of the signals $x(t)$ and $y(t)$ at $t=nT$, which are available from the discrete representations $x[n]$ and $y[n]$. Noting that $x[n] = x(nT)$ and $y[n] = y(nT)$ we find
# $$y[n+1] \approx y[n] + \frac{T}{RC} (x[n] - y[n]).$$
# Note that as written the output $y[n+1]$ is expressed in terms of the previous output $y[n]$ and the previous input $x[n]$. With proper initialisation this makes it possible to calculate the values $y[n]$ recursively.
# + [markdown] hide_input=true
# ### Recurse from initial conditions
#
# For any value of $n$, if we know $x[n]$ and $y[n]$ then we can calculate $y[n+1]$ in the forward direction from the equation above. We know $x[n]$ for all $n$, since the input is specified. However, we can't calculate say $y[5]$ without knowing $y[4]$, so we don't know how to start the recursion. In this case the initial conditions provide a starting point. This is called an *initial value problem* (IVP).
#
# Specifically, we know that for the situation described we require that $y[n]=0$ for $n \leq 0$. In particular we must have $y[-1] = 0$. With this auxiliary condition we can calculate $y[0]$ by evaluating the discrete system equation for $n=-1$:
# $$y[0] \approx y[-1] + \frac{T}{RC} (x[-1] - y[-1]) = 0 + \frac{T}{RC} (0 - 0) = 0.$$
# Then $y[1]$ can be calculated by using the expression for $n=1$:
# $$y[1] \approx y[0] + \frac{T}{RC} (x[0] - y[0]) = 0 + \frac{T}{RC} (1 - 0) = \frac{T}{RC}.$$
# Subsequently we can recursively calculate $y[2]$, $y[3]$, and so on.
#
# This is an instance of the forward or standard Euler method for numerically solving ordinary differential equations.
# -
# ### Frequency representation
#
# In this course we will see (or might have seen) that the RC circuit has a transfer function
# $$H(\omega) = \frac{1/RC}{1/RC + j \omega}$$
# and an impulse response
# $$h(t) = \frac{1}{RC} e^{-\frac{1}{RC}t} u(t).$$
# The exact analytical form for the step response, which is the true signal we are trying to estimate with our numerical approximation, is
# $$g(t) = (1 - e^{-\frac{1}{RC}t}) u(t).$$
# This will be used to evaluate the accuracy of the discrete approximation.
# ## Implementation
#
# The next section demonstrates the basic code functionality for calculating the output samples $y[n]$. After that a full script is provided for interrogating the effect of $T$ in the approximation.
# ### Basic code functionality
#
# We assume $R = C = 1$, just for simplicity. We also for now consider the case of $T=1/2$. The code below sets up the Python kernel and calculates some initial variables.
# +
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# %matplotlib notebook
# Assume R=C=1 and T=1/2
R = 1.0; C = 1.0; T = 0.5;
# -
# To keep track of everything and for use in later plots, we generate a vector containing the discrete sample points for $t$. We don't need to consider negative values of $t$ since both $x(t)$ and $y(t)$ are zero over that part of the domain. Note that in the code below `tv[0]=0`, but in general the first element of the vector may not correspond to $t=0$.
# Discrete time points to calculate (we want to plot from t=0 to t=tmax)
tmax = 5.001;
tv = np.arange(0, tmax, T);
N = len(tv); # number of points
# Now we create a vector `yv` to hold the values of the signal $y$. The elements of `tv` and `yv` are assumed to be in correspondence, so for example `yv[2]` holds the value of the signal $y(t)$ at time `tv[2]`.
# +
# Create a vector yv = (y[0], y[1], ..., y[N-1]) to hold the values of y(nT)
# for nonnegative values of n. We know that for n<0 the output is zero
yv = np.zeros(tv.shape);
# Initialise with the value for y[0] obtained from auxiliary condition
yv[0] = 0;
# Iterate the recursion in the forward direction for the required number of values
for n in range(0,N-1):
yv[n+1] = yv[n] + T/(R*C)*(1 - yv[n]); # since x[n] = 1 over this range
yv
# -
# Plot the approximate solution just calculated, together with the exact solution.
# +
# Plot the result
ph = plt.plot(tv, yv, c='g');
# Plot the exact solution for comparison
tcv = np.arange(0, tmax, T/100); # dense set of time points
ycv = 1 - np.exp(-tcv/(R*C)); # corresponding response values
ph0 = plt.plot(tcv, ycv, c='k');
plt.xlabel('t'); plt.ylabel('g(t)');
# -
# ### Investigation
#
# The script below investigates the standard Euler method for the problem, assuming different values of $T$. As $T$ approaches zero the numerical approximation becomes more accurate.
# %run src/labX_preamble.py # For internal notebook functions
# +
# %%writefileexec src/lab_discdiffeq-1.py -s # dump cell to file before execute
# Standard Euler metod for voltage across capacitor in series RC circuit versus
# input voltage for unit step input. Initial rest conditions are assumed
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# %matplotlib notebook
# Assume R=C=1
R = 1.0; C = 1.0;
# Show results for different values of T. The solution becomes exact as T
# tends to zero
fh1 = plt.figure(1);
for T in [1.0, 0.5, 0.2, 0.1]:
# Discrete time points to calculate (we want to plot from t=0 to t=tmax)
tmax = 5.001;
tv = np.arange(0, tmax, T);
N = len(tv); # number of points
# Create a vector yv = (y[0], y[1], ..., y[N-1]) to hold the values of y[n]
# for nonnegative values of n. We know that for n<0 the output is zero
yv = np.zeros(tv.shape);
# Calculate the value for y[0] and put it in vector yv
yv[0] = 0;
# Iterate the recursion for the required number of values
for n in range(1,N):
yv[n] = yv[n-1] + T/(R*C) - T/(R*C)*yv[n-1];
# Plot the resulting points
ph = plt.plot(tv, yv, c='g');
#end for
# Also plot the exact solution for comparison
tcv = np.arange(0, tmax, T/100);
ycv = 1 - np.exp(-tcv/(R*C));
ph = plt.plot(tcv, ycv, c='k');
plt.xlabel('t'); plt.ylabel('g(t)');
# -
# # Tasks
#
# These tasks involve writing code, or modifying existing code, to meet the objectives described.
#
# 1. If you use the backward difference approximation to the derivative
# $$\frac{dy(t)}{dt} \approx \frac{y(t) - y(t-T)}{T} \quad \text{for small $T$}$$
# instead of the forward difference, then you will arrive at the backward (or implicit) Euler numerical solution to the differential equation:
# $$y[n+1] = \frac{1}{1+T/(RC)} y[n] + \frac{T/(RC)}{1+T/(RC)} x[n+1] = a y[n] + b x[n+1],$$
# with
# $$a=\frac{1}{1+T/(RC)} \qquad \text{and} \qquad b=\frac{T/(RC)}{1+T/(RC)}.$$
# Use this to estimate the step response of the circuit given, and investigate the approximation for the same values of $T$ used before.<br>
# <br>
# In terms of stability of approximation the backward Euler method is better than the forward Euler, but the order of their approximation errors is the same. More advanced methods include the RungeโKutta family.<br><br>
#
# 2. Find the output when input is right-sided sinusoid $x(t) = \cos(\omega_0 t) u(t)$, again for $RC=1$ and under initial rest conditions $y(0) = 0$. Make a plot of the response for frequencies $\omega_0 = 1$, $\omega_0 = 2$, and $\omega_0 = 5$ radians per second for the case of $T=0.01$ seconds.<br>
# <br>
# Observe that after the initial transient dies out the output is a sinusoid of the same frequency, but with a change in amplitude and a shift along the time axis. For a fixed amplitude input the output amplitude decreases as the frequency goes up, which is why we call this a lowpass filter.<br><br>
#
# 3. Formulate and investigate the forward Euler method to find the step response of a highpass filter, where $R$ and $C$ are swapped in the circuit. You can again assume initial rest conditions.<br><br>
#
# 4. Consider the output when input is right-sided sinusoid $x(t) = \cos(\omega_0 t) u(t)$ with $\omega_0 = 2$ radians per second and for $RC=1$. Investigate the initial condition $y(0) = c$ for different values of $c$. Make a plot of the response for $c = 0, 0.5, 1$ for the case of $T=0.01$. You should observe that after enough time has passed (i.e. after the transients have settled), the response becomes independent of the initial condition.<br><br>
#
# 5. (Optional) Find the approximate output when the input is a two-sided sinusoid $x(t) = \sin(\omega_0 t)$, by formulating and applying recursion in both directions. Note that the backward difference approximation to the derivative can be used to find an equation for the reverse iteration:
# $$y[n-1] \approx y[n] - \frac{T}{RC} (x[n] - y[n]).$$
# Investigate the initial condition $y(0) = c$ for different values of $c$.<br><br>
#
# 6. (Optional) Try to find the exact step response of the RC lowpass filter using Sympy.
# The wikipedia page https://en.wikipedia.org/wiki/Euler_method is a good place for details. The description for the backward method https://en.wikipedia.org/wiki/Backward_Euler_method is also useful.
| lab_discdiffeq.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Question 1
# +
import numpy as np
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
#########################################################
# Description: Simulate a channel using a digital Butterworth LPF with specified cutoff. This function
# computes the output of the channel for the given input signal, and also adds AWGN of
# specified noise variance
#
# Usage: y = channel(x,T,dt,fcut,nvar,figvar)
# Inputs: x - Input signal
# T - Symbol duration
# dt - Sampling interval
# fcut - For the digital Butterworth LPF, the 3-db cutoff is set to fcut*R/(.5 * fs), where R is the
# symbol rate
# nvar - noise variance
# figvar - If '1', the function will plot the frequency response of the filter, and the
# input and ouput signals
# Output: y - Output signal y = h*x + n.
#########################################################
def channel(x,T,dt,fcut,nvar,figvar):
fs = 1/dt
R = 1/T
Wn = fcut*R/(fs/2)
if Wn == 0 :
y = x + np.sqrt(nvar)*np.random.normal(0,1,x.size)
else :
b, a = signal.butter(5, Wn)
y = signal.lfilter(b, a, x) + np.sqrt(nvar)*np.random.normal(0,1,x.size)
if figvar == 1 :
f = np.arange(0,fs/2,dt)
w, Hf = signal.freqz(b,a,f.size)
plt.figure()
plt.plot(f,np.abs(Hf))
plt.title('Frequency Response')
plt.grid()
plt.figure()
plt.title('Sampled Original and Noisy Signal')
plt.plot(x,'-')
plt.plot(y,'--')
plt.grid()
return y
# -
x = np.array([-1,-1,1,1,1,-1,-1,1,-1,1])
#x = np.random.randint(2, size=10) - 1
samples = 10
p = np.kron(x,np.ones(samples))
T = 1
dt = 0.1
fcut=1
nvar = 0
figvar=1
y = channel(p,T,dt,fcut,nvar,figvar)
x = np.array([-1,-1,1,1,1,-1,-1,1,-1,1])
#x = np.random.randint(2, size=10) - 1
samples = 10
p = np.kron(x,np.ones(samples))
T = 1
dt = 0.1
fcut=2
nvar = 0
figvar=1
y = channel(p,T,dt,fcut,nvar,figvar)
x = np.array([-1,-1,1,1,1,-1,-1,1,-1,1])
#x = np.random.randint(2, size=10) - 1
samples = 10
p = np.kron(x,np.ones(samples))
T = 1
dt = 0.1
fcut=3
nvar = 0
figvar=1
y = channel(p,T,dt,fcut,nvar,figvar)
x = np.array([-1,-1,1,1,1,-1,-1,1,-1,1])
#x = np.random.randint(2, size=10) - 1
samples = 10
p = np.kron(x,np.ones(samples))
T = 1
dt = 0.1
fcut=4
nvar = 0
figvar=1
y = channel(p,T,dt,fcut,nvar,figvar)
# # Question 2 and 3
def _2n3(A,n,T,samples,dt,fcut,nvar,figvar):
count=0
x = (2*np.random.randint(2, size=n) -1) * A
p = np.kron(x,np.ones(samples))
x_axis = np.arange(0,n,dt/T)
y = channel(p,T,dt,fcut,nvar,figvar)
#Matched Filter
h = np.full((int(T/dt)), 2*A)
#Recovered Signal
received_signal = np.convolve(h,y)
th = 0
count=0
recovered_sig = np.empty([n, int(T/dt)])
for i in range(n):
if(received_signal[int((i*samples) + (n/2))]>th):
curr = A
else:
curr = -A
if(abs(curr - x[i]) > 0.00001):
count=count+1;
row = np.full((1, int(T/dt)), curr)
recovered_sig[i] = row;
recovered_sig = np.reshape(recovered_sig,(n*int(T/dt)))
if figvar == 1:
plt.figure()
plt.grid()
plt.plot(x_axis,recovered_sig)
plt.title('Reconstructed')
plt.show()
count=0
experiments = 100
for i in range(experiments):
x = (2*np.random.randint(2, size=n) -1) * A
p = np.kron(x,np.ones(samples))
x_axis = np.arange(0,n,dt/T)
figvar=0
y = channel(p,T,dt,fcut,nvar,0)
#Matched Filter
h = np.full((int(T/dt)), 2*A)
#Recovered Signal
received_signal = np.convolve(h,y)
th = 0
recovered_sig = np.empty([n, int(T/dt)])
for i in range(n):
if(received_signal[int((i*samples) + (n/2))]>th):
curr = A
else:
curr = -A
if(abs(curr - x[i]) > 0.00001):
count=count+1;
row = np.full((1, int(T/dt)), curr)
recovered_sig[i] = row;
recovered_sig = np.reshape(recovered_sig,(n*int(T/dt)))
error = count/(n*experiments)
if figvar == 1:
print('bits interpreted incorrectly in 100 experiments:',error)
return error
def _3(A,n,T,samples,dt,fcut,nvar,figvar):
#Cutoff frequency v/s bit error probability graph
nvar = 1;
freqcut = np.arange(0.5,4.5,0.1)
val = np.empty([freqcut.shape[0]])
for j in range(freqcut.shape[0]):
val[j] = _2n3(A,n,T,samples,dt,freqcut[j],nvar,figvar)
plt.figure()
plt.grid()
plt.plot(freqcut,val)
plt.title('Cutoff frequency v/s bit error probability')
plt.show()
#Variance v/s bit error probability graph
fcut = 1.5
variance = np.arange(0,10,0.1)
val = np.empty([variance.shape[0]])
for j in range(variance.shape[0]):
val[j] = _2n3(A,n,T,samples,dt,fcut,variance[j],figvar)
plt.figure()
plt.grid()
plt.plot(variance,val)
plt.title('Variance v/s bit error probability')
plt.show()
#Amplitude v/s bit error probability graph
amplitude = np.arange(0.1,10,0.1)
val = np.empty([amplitude.shape[0]])
for j in range(amplitude.shape[0]):
val[j] = _2n3(amplitude[j],n,T,samples,dt,fcut,nvar,figvar)
plt.figure()
plt.grid()
plt.plot(amplitude,val)
plt.title('Amplitude v/s bit error probability')
plt.show()
A = 1
n = 16
T = 1
dt = 1/samples
fcut=0.5
nvar = 2
samples = 10
figvar=1
_2n3(A,n,T,samples,dt,fcut,nvar,figvar)
figvar=0
_3(A,n,T,samples,dt,fcut,nvar,figvar)
# PLOTS FOR QUESTION THREE ARE IN THIS CELL
A = 1
n = 16
T = 1
samples = 10
dt = 1/samples
fcut=1
nvar = 0
figvar=1
_2n3(A,n,T,samples,dt,fcut,nvar,figvar)
A = 1
n = 16
T = 1
dt = 1/samples
fcut=2
nvar = 0
samples = 10
figvar=1
_2n3(A,n,T,samples,dt,fcut,nvar,figvar)
A = 1
n = 16
T = 1
dt = 1/samples
fcut=2
nvar = 2
samples = 10
figvar=1
_2n3(A,n,T,samples,dt,fcut,nvar,figvar)
A = 1
n = 16
T = 1
dt = 1/samples
fcut=4
nvar = 2
samples = 10
figvar=1
_2n3(A,n,T,samples,dt,fcut,nvar,figvar)
| lab7/E1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import os
import sys
import numpy as np
import pandas as pd
import matplotlib as mlp
from matplotlib import pyplot as plt
import seaborn as sns
# %matplotlib inline
mlp.style.use("seaborn")
import statsmodels
import statsmodels.api as sm
import warnings
warnings.filterwarnings("ignore")
# -
ie_data = pd.read_excel("../data/ie_data.xls", sheet_name="Data", skiprows=7)
ie_data = ie_data[["Date", "CAPE", "Yield", "Real Return", "Real Return.1", "Returns.2"]].copy()
ie_data.rename(columns={"Yield": "Excess_CAPE_Yield", "Real Return": "Real_Returns_Equity", "Real Return.1": "Real_Returns_Bond", "Returns.2": "Excess_Real_Returns_Equity"}, inplace=True)
ie_data = ie_data.dropna()
ie_data.head()
ie_data = pd.read_excel("../data/ie_data.xls", sheet_name="Data", skiprows=7)
ie_data.drop(ie_data.tail(1).index, inplace=True)
ie_data.head()
ie_data["Real Return"].min()
# +
x = 1/(np.array(ie_data[(ie_data["Date"]<=2006)]["CAPE"]).astype(float))
x = sm.add_constant(x)
y = np.array(ie_data[(ie_data["Date"]<=2006)]["Real_Returns_Equity"]).astype(float)
model = sm.OLS(y, x, missing="drop")
summary = model.fit()
summary.summary()
# -
def cape_regression(cape_values, time_period, data=ie_data):
x = np.array(cape_values)
x = sm.add_constant(x)
model = sm.OLS(np.array(data["Real_Total_Return_Price"]), x, missing="drop")
summary = model.fit()
# ## Taxes
ie_data = pd.read_csv("../data/ie_data_tax.csv", index_col=False)
ie_data = ie_data[ie_data["Date"]<2011.09]
print(ie_data.columns)
ie_data.head()
preprocess = lambda x: float(x.replace(" ", "").replace(",", "")) if not isinstance(x, float) else x
ie_data["CAPE"] = ie_data["CAPE"].apply(preprocess)
ie_data["Real_Total_Return_Price"] = ie_data["Real_Total_Return_Price"].apply(preprocess)
# ## Interest Rates
ie_data.head()
# +
# Calculate 2 and 5 Years Annualized Expected Real Equity Return
n, p = ie_data.shape
return_2 = []
return_5 = []
for i, row in ie_data.iterrows():
if i+24 < n:
return_2.append((ie_data.loc[i+24, "Price.1"]/ie_data.loc[i, "Price.1"])**(1/2)-1)
else:
return_2.append(np.nan)
if i+60 < n:
return_5.append((ie_data.loc[i+60, "Price.1"]/ie_data.loc[i, "Price.1"])**(1/5)-1)
else:
return_5.append(np.nan)
ie_data["Real_Return_2"] = return_2
ie_data["Real_Return_5"] = return_5
# Calculate 2 and 5 Years Annualized Real Yield of Long-term Bond
yield_2 = []
yield_5 = []
for i, row in ie_data.iterrows():
if i-24 >= 0:
yield_2.append(ie_data.loc[i, "Rate GS10"]/100-((ie_data.loc[i, "CPI"]/ie_data.loc[i-24, "CPI"])**(1/2)-1))
else:
yield_2.append(np.nan)
if i-60 >= 0:
yield_5.append(ie_data.loc[i, "Rate GS10"]/100-((ie_data.loc[i, "CPI"]/ie_data.loc[i-60, "CPI"])**(1/5)-1))
else:
yield_5.append(np.nan)
ie_data["Real_Yield_2"] = yield_2
ie_data["Real_Yield_5"] = yield_5
# -
# Select varialbles of interest and sample period
df = ie_data[["Date", "Rate GS10", "CAPE", "Yield", "Real Return", "Real Return.1",
"Returns.2", "Real_Return_2", "Real_Return_5", "Real_Yield_2",
"Real_Yield_5"]].copy()
df.rename(columns={"Rate GS10": "10Y_Nominal_Yield", "Yield": "Excess_CAPE_Yield", "Real Return": "Real_Returns_Equity_10Y",
"Real Return.1": "Real_Returns_Bond_10Y", "Returns.2": "Excess_Real_Returns_Equity_10Y",
"Real_Return_2": "Real_Returns_Equity_2Y", "Real_Return_5": "Real_Returns_Equity_5Y",
"Real_Yield_2": "Real_Yield_2Y", "Real_Yield_5": "Real_Yield_5Y"}, inplace=True)
# Drop NAs, sample period: 1881.01-2011.08
df_clean = df.dropna()
df_clean.head()
df["Log_CAPE"] = np.log(df["CAPE"])
df["CAPE_Inverse"] = 1/df["CAPE"]
df["Real_Yield_10Y"] = df.CAPE_Inverse - df.Excess_CAPE_Yield
# Descriptive statistics
df.describe()
# Regression given by Shiller(1996):
# $$
# Real Returns Equity_{t+k}=\alpha+\beta_k \log{CAPE_{t}}+\varepsilon_{t+k,k}
# $$
# The intuition behind the regression is that under low-interest rate regimes, CAPE is unusually high. Currently SP500 CAPE sits at 39.6, 2nd highest of all time. A high CAPE ratio suggests that equities are overvalued, resulting in low subsequent returns while a low CAPE is suggestive of higher future returns.
# +
# Regression of different sample period
split = 2007.01
reg_data = df[df.Date < split][["Log_CAPE", "Real_Returns_Equity_10Y"]].dropna()
reg1_before = sm.OLS(reg_data.Real_Returns_Equity_10Y, sm.add_constant(reg_data[["Log_CAPE"]]))
result1_before = reg1_before.fit()
reg_data = df[df.Date >= split][["Log_CAPE", "Real_Returns_Equity_10Y"]].dropna()
reg1_after = sm.OLS(reg_data.Real_Returns_Equity_10Y, sm.add_constant(reg_data[["Log_CAPE"]]))
result1_after = reg1_after.fit()
# Entire period
reg_data = df[["Log_CAPE", "Real_Returns_Equity_10Y"]].dropna()
reg1_all = sm.OLS(reg_data.Real_Returns_Equity_10Y, sm.add_constant(reg_data[["Log_CAPE"]]))
result1_all = reg1_all.fit()
print(result1_after.summary())
# -
# ## Accounting
# ## Market Composition
| notebooks/CAPE Ratio Regression.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] heading_collapsed=true
# # Load Data
# + code_folding=[] hidden=true
# import
import autodisc as ad
import ipywidgets
import plotly
import numpy as np
plotly.offline.init_notebook_mode(connected=True)
# + code_folding=[] hidden=true
# Define and load data
org_experiment_definitions = [
# two dimensions
dict(id = '1',
directory = '../experiments/experiment_000001',
name = 'Test 1',
is_default = True),
dict(id = '2',
directory = '../experiments/experiment_000002',
name = 'Test 2',
is_default = True),
]
repetition_ids = list(range(10))
# define names and load the data
experiment_name_format = '<id> - <name>' # <id>, <name>
experiment_definitions = []
for org_exp_def in org_experiment_definitions:
new_exp_def = dict()
new_exp_def['directory'] = org_exp_def['directory']
if 'is_default' in org_exp_def:
new_exp_def['is_default'] = org_exp_def['is_default']
if 'name' in org_exp_def:
new_exp_def['id'] = ad.gui.jupyter.misc.replace_str_from_dict(experiment_name_format, {'id': org_exp_def['id'], 'name': org_exp_def['name']})
else:
new_exp_def['id'] = ad.gui.jupyter.misc.replace_str_from_dict(experiment_name_format, {'id': org_exp_def['id']})
experiment_definitions.append(new_exp_def)
experiment_statistics = dict()
for experiment_definition in experiment_definitions:
experiment_statistics[experiment_definition['id']] = ad.gui.jupyter.misc.load_statistics(experiment_definition['directory'])
# -
# # Error Curves
# + [markdown] heading_collapsed=true
# ## Generate Data
# + hidden=true
def compute_running_average(data=None, data_sources=None, nsteps=50):
averaged_data = dict()
if not isinstance(data_sources, list):
data_sources = [data_sources]
# compute for each experiment
for experiment_id, experiment_data in data.items():
cur_average_experiment_data = dict()
# compute for each given datasource
for datasource in data_sources:
# go through the sub elements of the current datasource to get to the final data
cur_data = experiment_data
if not isinstance(datasource, tuple):
datasource = (datasource, )
# go though sub datasources to reach final data
for sub_ds in datasource:
cur_data = cur_data[sub_ds]
cur_average_data = np.zeros(cur_data.shape) * np.nan
for end_idx in range(cur_data.shape[1]):
start_idx = max(0, end_idx - nsteps)
cur_average_data[:, end_idx] = np.nansum(cur_data[:, start_idx:end_idx+1], axis=1) / (end_idx-start_idx+1)
for sub_ds in reversed(datasource[1:]):
cur_average_data = {sub_ds: cur_average_data}
cur_average_experiment_data[datasource[0]] = cur_average_data
averaged_data[experiment_id] = cur_average_experiment_data
return averaged_data
# compute the running average for some statistics
experiment_running_average_statisitics = compute_running_average(data=experiment_statistics,
data_sources=[('error_in_goalspace_between_goal_bestpolicy', 'data'),('error_in_goalspace_between_goal_usedpolicy', 'data')],
nsteps=100)
# -
# ## Error between Goal and Optimal Policy
# + code_folding=[0]
# PLOTTING
config = dict(
layout = dict(
title = 'Error between Goal and Optimal Policy',
xaxis = dict(
title = 'explorations'
),
yaxis = dict(
title = 'error'
)
)
)
elems = ad.gui.jupyter.interact_selection_multiple_experiments_repetitions(func=ad.gui.jupyter.plot_scatter_per_datasource,
experiment_definitions=experiment_definitions,
repetition_ids=repetition_ids,
data=experiment_running_average_statisitics,
data_source=('error_in_goalspace_between_goal_bestpolicy', 'data'),
config=config)
# -
# ## Error between Goal and Used Policy
# + code_folding=[0]
# PLOTTING
config = dict(
layout = dict(
title = 'Error between Goal and Used Policy',
xaxis = dict(
title = 'explorations'
),
yaxis = dict(
title = 'error'
)
)
)
elems = ad.gui.jupyter.interact_selection_multiple_experiments_repetitions(func=ad.gui.jupyter.plot_scatter_per_datasource,
experiment_definitions=experiment_definitions,
repetition_ids=repetition_ids,
data=experiment_running_average_statisitics,
data_source=('error_in_goalspace_between_goal_usedpolicy', 'data'),
config=config)
# -
# # Classification
# + [markdown] heading_collapsed=true
# ## Generate Data
# + code_folding=[] hidden=true
## Collect Data for categories
# function to calcuate ratios
def calc_binary_ratio(array):
return np.sum(array) / np.sum(~np.isnan(array))
classifier_data = dict()
for experiment_definition in experiment_definitions:
experiment_id = experiment_definition['id']
dead_data = experiment_statistics[experiment_id]['classifier_dead']['data']
dead_ratio = experiment_statistics[experiment_id]['classifier_dead']['ratio']
animal_data = experiment_statistics[experiment_id]['classifier_animal']['data']
animal_ratio = experiment_statistics[experiment_id]['classifier_animal']['ratio']
non_animal_data = np.full(dead_data.shape, True)
non_animal_data[dead_data] = False
non_animal_data[animal_data] = False
non_animal_ratio = np.apply_along_axis(calc_binary_ratio, 1, non_animal_data)
diverging_data = np.full(experiment_statistics[experiment_id]['classifier_diverging']['data'].shape, True)
diverging_data[experiment_statistics[experiment_id]['classifier_diverging']['data'] == 0] = False
diverging_ratio = np.apply_along_axis(calc_binary_ratio, 1, diverging_data)
diverging_animal_data = animal_data & diverging_data
diverging_animal_ratio = np.apply_along_axis(calc_binary_ratio, 1, diverging_animal_data)
non_diverging_animal_data = animal_data & ~diverging_data
non_diverging_animal_ratio = np.apply_along_axis(calc_binary_ratio, 1, non_diverging_animal_data)
diverging_non_animal_data = non_animal_data & diverging_data
diverging_non_animal_ratio = np.apply_along_axis(calc_binary_ratio, 1, diverging_non_animal_data)
non_diverging_non_animal_data = non_animal_data & ~diverging_data
non_diverging_non_animal_ratio = np.apply_along_axis(calc_binary_ratio, 1, non_diverging_non_animal_data)
non_diverging_animal_stable_fixpoint_data = non_diverging_animal_data & experiment_statistics[experiment_id]['classifier_stable_fixpoint_solution']['data']
non_diverging_animal_stable_fixpoint_ratio = np.apply_along_axis(calc_binary_ratio, 1, non_diverging_animal_stable_fixpoint_data) / non_diverging_animal_ratio
non_diverging_animal_stable_fixpoint_ratio[np.isnan(non_diverging_animal_stable_fixpoint_ratio)] = 0
# animal & moving & not fixpoint
non_diverging_animal_moving_data = non_diverging_animal_data & experiment_statistics[experiment_id]['classifier_moving']['data'] & ~non_diverging_animal_stable_fixpoint_data
non_diverging_animal_moving_ratio = np.apply_along_axis(calc_binary_ratio, 1, non_diverging_animal_moving_data) / non_diverging_animal_ratio
non_diverging_animal_moving_ratio[np.isnan(non_diverging_animal_moving_ratio)] = 0
# animal & not moving & not fixpoint
non_diverging_animal_non_moving_data = non_diverging_animal_data & ~experiment_statistics[experiment_id]['classifier_moving']['data'] & ~non_diverging_animal_stable_fixpoint_data
non_diverging_animal_non_moving_ratio = np.apply_along_axis(calc_binary_ratio, 1, non_diverging_animal_non_moving_data) / non_diverging_animal_ratio
non_diverging_animal_non_moving_ratio[np.isnan(non_diverging_animal_non_moving_ratio)] = 0
non_diverging_non_animal_stable_fixpoint_data = non_diverging_non_animal_data & experiment_statistics[experiment_id]['classifier_stable_fixpoint_solution']['data']
non_diverging_non_animal_stable_fixpoint_ratio = np.apply_along_axis(calc_binary_ratio, 1, non_diverging_non_animal_stable_fixpoint_data) / non_diverging_non_animal_ratio
non_diverging_non_animal_stable_fixpoint_ratio[np.isnan(non_diverging_non_animal_stable_fixpoint_ratio)] = 0
non_diverging_non_animal_non_stable_fixpoint_data = non_diverging_non_animal_data & ~experiment_statistics[experiment_id]['classifier_stable_fixpoint_solution']['data']
non_diverging_non_animal_non_stable_fixpoint_ratio = np.apply_along_axis(calc_binary_ratio, 1, non_diverging_non_animal_non_stable_fixpoint_data) / non_diverging_non_animal_ratio
non_diverging_non_animal_non_stable_fixpoint_ratio[np.isnan(non_diverging_non_animal_non_stable_fixpoint_ratio)] = 0
classifier_data[experiment_id] = dict(
dead_data = dead_data,
dead_ratio = dead_ratio,
animal_data = animal_data,
animal_ratio = animal_ratio,
non_animal_data = non_animal_data,
non_animal_ratio = non_animal_ratio,
diverging_data = diverging_data,
diverging_ratio = diverging_ratio,
diverging_animal_data = diverging_animal_data,
diverging_animal_ratio = diverging_animal_ratio,
non_diverging_animal_data = non_diverging_animal_data,
non_diverging_animal_ratio = non_diverging_animal_ratio,
diverging_non_animal_data = diverging_non_animal_data,
diverging_non_animal_ratio = diverging_non_animal_ratio,
non_diverging_non_animal_data = non_diverging_non_animal_data,
non_diverging_non_animal_ratio = non_diverging_non_animal_ratio,
non_diverging_animal_stable_fixpoint_data = non_diverging_animal_stable_fixpoint_data,
non_diverging_animal_stable_fixpoint_ratio = non_diverging_animal_stable_fixpoint_ratio,
non_diverging_animal_moving_data = non_diverging_animal_moving_data,
non_diverging_animal_moving_ratio = non_diverging_animal_moving_ratio,
non_diverging_animal_non_moving_data = non_diverging_animal_non_moving_data,
non_diverging_animal_non_moving_ratio = non_diverging_animal_non_moving_ratio,
non_diverging_non_animal_stable_fixpoint_data = non_diverging_non_animal_stable_fixpoint_data,
non_diverging_non_animal_stable_fixpoint_ratio = non_diverging_non_animal_stable_fixpoint_ratio,
non_diverging_non_animal_non_stable_fixpoint_data = non_diverging_non_animal_non_stable_fixpoint_data,
non_diverging_non_animal_non_stable_fixpoint_ratio = non_diverging_non_animal_non_stable_fixpoint_ratio
)
# -
# ## Major Classification
# + code_folding=[0]
# Plotting
config = dict(
plot_type = 'plotly_box',
layout = dict(
title = 'Major Classification'
),
trace_labels = ['dead', 'div non animal', 'div animal', 'non animal', 'animal'],
)
elems = ad.gui.jupyter.interact_selection_multiple_experiments_repetitions(func=ad.gui.jupyter.plot_barbox_per_datasource,
experiment_definitions=experiment_definitions,
repetition_ids=repetition_ids,
data=classifier_data,
data_source=['dead_ratio', 'diverging_non_animal_ratio', 'diverging_animal_ratio', 'non_diverging_non_animal_ratio', 'non_diverging_animal_ratio'],
config=config)
# -
# ## Animal Classification
# + code_folding=[0]
# Plotting
config = dict(
plot_type = 'plotly_box',
layout = dict(
title = 'Animal Classification'
),
trace_labels = ['stable fixpoint', 'moving', 'non moving'],
)
elems = ad.gui.jupyter.interact_selection_multiple_experiments_repetitions(func=ad.gui.jupyter.plot_barbox_per_datasource,
experiment_definitions=experiment_definitions,
repetition_ids=repetition_ids,
data=classifier_data,
data_source=['non_diverging_animal_stable_fixpoint_ratio', 'non_diverging_animal_moving_ratio', 'non_diverging_animal_non_moving_ratio'],
config=config)
# -
# ## Non-Animal Classification
# + code_folding=[0]
# Plotting
config = dict(
plot_type = 'plotly_box',
layout = dict(
title = 'Non-Animal Classification'
),
trace_labels = ['stable fixpoint', 'non stable'],
)
elems = ad.gui.jupyter.interact_selection_multiple_experiments_repetitions(func=ad.gui.jupyter.plot_barbox_per_datasource,
experiment_definitions=experiment_definitions,
repetition_ids=repetition_ids,
data=classifier_data,
data_source=['non_diverging_non_animal_stable_fixpoint_ratio', 'non_diverging_non_animal_non_stable_fixpoint_ratio'],
config=config)
# -
# # Run Parameters
# + code_folding=[0]
# Plotting
def plot_run_parameters_for_experiment(experiment_id):
config = dict(
subplots = dict(subplot_titles = ['R', 'T', 'm', 's', 'b:1', 'b:2', 'b:3', 'b:4'],
rows=4,
cols=2),
init_mode = 'elements',
layout = dict(
height = 1000,
default_xaxis = dict(
title = 'explorations'
),
default_yaxis = dict(
title = 'error'
),
),
default_element_label = '<mean_label> - <subelem_idx>',
default_trace = dict(
mode = 'markers'
),
default_mean_trace = dict(
legendgroup = '<data_idx>', # subplot_idx, data_idx
showlegend = False,
),
default_subplot_mean_traces = [dict(
showlegend = True,
)],
default_element_trace = dict(
visible='legendonly',
legendgroup = 'elem <data_idx>-<subelem_idx>',
showlegend = False,
),
default_subplot_element_traces = [dict(
showlegend = True
)],
default_data_element_traces = [dict(
visible = True
)]
)
ad.gui.jupyter.plot_scatter_per_datasource(experiment_ids=[experiment_id],
repetition_ids=['all'],
data=experiment_statistics,
data_source=[('run_parameters','R'),
('run_parameters','T'),
('run_parameters','m'),
('run_parameters','s'),
('run_parameters','b', 0),
('run_parameters','b', 1),
('run_parameters','b', 2),
('run_parameters','b', 3)],
config=config)
experiment_ids = [exp_def['id'] for exp_def in experiment_definitions]
retval = ipywidgets.interact(plot_run_parameters_for_experiment, experiment_id = experiment_ids)
| autodisc/autodisc/demos/lenia/goalspace_exploration/analyse/Experiment Overview.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] colab_type="text" id="nCc3XZEyG3XV"
# Lambda School Data Science
#
# *Unit 2, Sprint 3, Module 2*
#
# ---
#
#
# # Permutation & Boosting
#
# You will use your portfolio project dataset for all assignments this sprint.
#
# ## Assignment
#
# Complete these tasks for your project, and document your work.
#
# - [ ] If you haven't completed assignment #1, please do so first.
# - [ ] Continue to clean and explore your data. Make exploratory visualizations.
# - [ ] Fit a model. Does it beat your baseline?
# - [ ] Try xgboost.
# - [ ] Get your model's permutation importances.
#
# You should try to complete an initial model today, because the rest of the week, we're making model interpretation visualizations.
#
# But, if you aren't ready to try xgboost and permutation importances with your dataset today, that's okay. You can practice with another dataset instead. You may choose any dataset you've worked with previously.
#
# The data subdirectory includes the Titanic dataset for classification and the NYC apartments dataset for regression. You may want to choose one of these datasets, because example solutions will be available for each.
#
#
# ## Reading
#
# Top recommendations in _**bold italic:**_
#
# #### Permutation Importances
# - _**[Kaggle / <NAME>: Machine Learning Explainability](https://www.kaggle.com/dansbecker/permutation-importance)**_
# - [<NAME>: Interpretable Machine Learning](https://christophm.github.io/interpretable-ml-book/feature-importance.html)
#
# #### (Default) Feature Importances
# - [<NAME>: Selecting good features, Part 3, Random Forests](https://blog.datadive.net/selecting-good-features-part-iii-random-forests/)
# - [<NAME>, et al: Beware Default Random Forest Importances](https://explained.ai/rf-importance/index.html)
#
# #### Gradient Boosting
# - [A Gentle Introduction to the Gradient Boosting Algorithm for Machine Learning](https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/)
# - _**[A Kaggle Master Explains Gradient Boosting](http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/)**_
# - [_An Introduction to Statistical Learning_](http://www-bcf.usc.edu/~gareth/ISL/ISLR%20Seventh%20Printing.pdf) Chapter 8
# - [Gradient Boosting Explained](http://arogozhnikov.github.io/2016/06/24/gradient_boosting_explained.html)
# - _**[Boosting](https://www.youtube.com/watch?v=GM3CDQfQ4sw) (2.5 minute video)**_
# -
import pandas as pd
import seaborn as sns
import numpy as np
from sklearn.model_selection import train_test_split
train, test = train_test_split(sns.load_dataset('titanic').drop(columns=['alive']), random_state=0)
target = 'survived'
train.shape, test.shape
train, val = train_test_split(train, train_size=0.75, test_size=0.25, random_state=42)
# arrange data into X features matrix and y target vector:
X_train = train.drop(columns=target)
y_train = train[target]
X_val = val.drop(columns=target)
y_val = val[target]
X_test = test.drop(columns=target)
y_test = test[target]
pip install --upgrade category_encoders
# +
# regular random forest classifier:
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
import category_encoders as ce
pipeline = make_pipeline(
ce.OrdinalEncoder(),
SimpleImputer(strategy='median'),
RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
)
# Fit on train, score on val
pipeline.fit(X_train, y_train)
print('Validation Accuracy', pipeline.score(X_val, y_val))
# +
# with permutation importances:
transformers = make_pipeline(
ce.OrdinalEncoder(),
SimpleImputer(strategy='median')
)
X_train_transformed = transformers.fit_transform(X_train)
X_val_transformed = transformers.transform(X_val)
model = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train_transformed, y_train)
# +
import eli5
from eli5.sklearn import PermutationImportance
permuter = PermutationImportance(
model,
scoring='accuracy',
n_iter=5,
random_state=42
)
permuter.fit(X_val_transformed, y_val)
# -
feature_names = X_val.columns.tolist()
pd.Series(permuter.feature_importances_, feature_names).sort_values(ascending=False)
# +
feature_names = X_val.columns.tolist()
eli5.show_weights(
permuter,
top=None, # show permutation importances for all features
feature_names=feature_names
)
# -
print('Shape before removing features:', X_train.shape)
minimum_importance = 0
mask = permuter.feature_importances_ > minimum_importance
features = X_train.columns[mask]
X_train = X_train[features]
print('Shape after removing features:', X_train.shape)
# +
X_val = X_val[features]
pipeline = make_pipeline(
ce.OrdinalEncoder(),
SimpleImputer(strategy='median'),
RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
)
# Fit on train, score on val
pipeline.fit(X_train, y_train)
print('Validation Accuracy', pipeline.score(X_val, y_val))
# -
| module2/assignment_applied_modeling_2 (1).ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# #### Sample client usage
#
# This shows an example of how to setup a client to get output from the server.
# The client is pre configured to connect to the hostname pre set in docker-compose.
# Docker compose sets host names of containers to be the same host name as the service name (hence pipeline)
#
# +
from konduitserving.client import Client
import numpy as np
input_names = ['default']
output_names = ['default']
port = 65535
client = Client(input_names=input_names,
timeout=300,
output_names=output_names,
input_type='JSON',
endpoint_output_type='RAW',
return_output_type='JSON',
url='http://pipeline:' + str(port))
data_input = {'img_path': '/usr/share/input-data/download.jpg'}
result = client.predict(data_input)
print(str(result))
# -
| docker/notes/client-notebook.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <img align="right" src="images/tf.png" width="128"/>
# <img align="right" src="images/logo.png" width="128"/>
# <img align="right" src="images/etcbc.png" width="128"/>
# <img align="right" src="images/dans.png" width="128"/>
#
# ---
#
# To get started: consult [start](start.ipynb)
#
# ---
#
# # Similar lines
#
# We spot the many similarities between lines in the corpus.
#
# There are ca 50,000 lines in the corpus of which ca 35,000 with real content.
# To compare these requires more than half a billion comparisons.
# That is a costly operation.
# [On this laptop it took 21 whole minutes](https://nbviewer.jupyter.org/github/etcbc/dss/blob/master/programs/parallels.ipynb).
#
# The good news it that we have stored the outcome in an extra feature.
#
# This feature is packaged in a TF data module,
# that we will automatically loaded with the DSS.
# %load_ext autoreload
# %autoreload 2
# +
import collections
from tf.app import use
# -
# A = use('dss', hoist=globals())
A = use("dss:clone", checkout="clone", hoist=globals())
# The new feature is **sim** and it it an edge feature.
# It annotates pairs of lines $(l, m)$ where $l$ and $m$ have similar content.
# The degree of similarity is a percentage (between 60 and 100), and this value
# is annotated onto the edges.
#
# Here is an example:
allLines = F.otype.s("line")
nLines = len(allLines)
exampleLine = allLines[0]
sisters = E.sim.b(exampleLine)
print(f"{len(sisters)} similar lines")
print("\n".join(f"{s[0]} with similarity {s[1]}" for s in sisters[0:10]))
A.table(tuple((s[0],) for s in ((exampleLine,), *sisters)), end=10)
# # All similarities
#
# Let's first find out the range of similarities:
# +
minSim = None
maxSim = None
similarity = dict()
for ln in F.otype.s("line"):
sisters = E.sim.f(ln)
if not sisters:
continue
for (m, s) in sisters:
similarity[(ln, m)] = s
thisMin = min(s[1] for s in sisters)
thisMax = max(s[1] for s in sisters)
if minSim is None or thisMin < minSim:
minSim = thisMin
if maxSim is None or thisMax > maxSim:
maxSim = thisMax
print(f"minimum similarity is {minSim:>3}")
print(f"maximum similarity is {maxSim:>3}")
# -
# # The bottom lines
#
# We give a few examples of the least similar lines.
#
# We can use a search template to get the 90% lines.
query = """
line
-sim=60> line
"""
# In words: find a line connected via a sim-edge with value 60 to an other line.
results = A.search(query)
A.table(results, start=1, end=10, withPassage="1 2")
# Or in full layout:
A.table(results, start=1, end=10, fmt="layout-orig-full", withPassage="1 2")
# # More research
#
# Let's find out which lines have the most correspondences.
# +
parallels = {}
for (ln, m) in similarity:
parallels.setdefault(ln, set()).add(m)
parallels.setdefault(m, set()).add(ln)
print(f"{len(parallels)} out of {nLines} lines have at least one similar line")
# -
rankedParallels = sorted(
parallels.items(),
key=lambda x: (-len(x[1]), x[0]),
)
for (ln, paras) in rankedParallels[0:10]:
print(
f'{len(paras):>4} siblings of {ln} = {T.text(ln)} = {T.text(ln, fmt="text-source-full", descend=True)}'
)
for (ln, paras) in rankedParallels[100:110]:
print(
f'{len(paras):>4} siblings of {T.text(ln)} = {T.text(ln, fmt="text-source-full", descend=True)}'
)
for (ln, paras) in rankedParallels[500:510]:
print(
f'{len(paras):>4} siblings of {T.text(ln)} = {T.text(ln, fmt="text-source-full", descend=True)}'
)
# And how many lines have just one correspondence?
#
# We look at the tail of rankedParallels.
pairs = [(x, list(paras)[0]) for (x, paras) in rankedParallels if len(paras) == 1]
print(f"There are {len(pairs)} exclusively parallel pairs of lines")
for (x, y) in pairs[0:10]:
A.dm("---\n")
print(f"similarity {similarity[(x,y)]}")
A.plain(x, fmt="layout-orig-full")
A.plain(y, fmt="layout-orig-full")
# Why not make an overview of exactly how wide-spread parallel lines are?
#
# We count how many lines have how many parallels.
# +
parallelCount = collections.Counter()
buckets = (2, 10, 20, 50, 100)
bucketRep = {}
prevBucket = None
for bucket in buckets:
if prevBucket is None:
bucketRep[bucket] = f" n <= {bucket:>3}"
elif bucket == buckets[-1]:
bucketRep[bucket] = f" n > {bucket:>3}"
else:
bucketRep[bucket] = f"{prevBucket:>3} < n <= {bucket:>3}"
prevBucket = bucket
for (ln, paras) in rankedParallels:
clusterSize = len(paras) + 1
if clusterSize > buckets[-1]:
theBucket = buckets[-1]
else:
for bucket in buckets:
if clusterSize <= bucket:
theBucket = bucket
break
parallelCount[theBucket] += 1
for (bucket, amount) in sorted(
parallelCount.items(),
key=lambda x: (-x[0], x[1]),
):
print(f"{amount:>4} lines have {bucketRep[bucket]} sisters")
# -
# # Cluster the lines
#
# Before we try to find them, let's see if we can cluster the similar lines in similar clusters.
# From now on we forget about the level of similarity, and focus on whether two lines are just "similar", meaning that they have
# a high degree of similarity.
# +
SIMILARITY_THRESHOLD = 0.8
CLUSTER_THRESHOLD = 0.4
def makeClusters():
# determine the domain
domain = set()
for ln in allLines:
ms = E.sim.f(ln)
for (m, s) in ms:
if s > SIMILARITY_THRESHOLD:
domain.add(s)
added = True
if added:
domain.add(m)
A.indent(reset=True)
chunkSize = 1000
b = 0
j = 0
clusters = []
for ln in domain:
j += 1
b += 1
if b == chunkSize:
b = 0
A.info(f"{j:>5} lines and {len(clusters):>5} clusters")
lSisters = {x[0] for x in E.sim.b(ln) if x[1] > SIMILARITY_THRESHOLD}
lAdded = False
for cl in clusters:
if len(cl & lSisters) > CLUSTER_THRESHOLD * len(cl):
cl.add(ln)
lAdded = True
break
if not lAdded:
clusters.append({ln})
A.info(f"{j:>5} lines and {len(clusters)} clusters")
return clusters
# -
clusters = makeClusters()
# What is the distribution of the clusters, in terms of how many similar lines they contain?
# We count them.
# +
clusterSizes = collections.Counter()
for cl in clusters:
clusterSizes[len(cl)] += 1
for (size, amount) in sorted(
clusterSizes.items(),
key=lambda x: (-x[0], x[1]),
):
print(f"clusters of size {size:>4}: {amount:>5}")
# -
# # Interesting groups
#
# Exercise: investigate some interesting groups, that lie in some sweet spots.
#
# * the biggest clusters: more than 13 members
# * the medium clusters: between 4 and 13 members
# * the small clusters: between 2 and 4 members
# ---
#
# All chapters:
#
# * **[start](start.ipynb)** become an expert in creating pretty displays of your text structures
# * **[display](display.ipynb)** become an expert in creating pretty displays of your text structures
# * **[search](search.ipynb)** turbo charge your hand-coding with search templates
# * **[exportExcel](exportExcel.ipynb)** make tailor-made spreadsheets out of your results
# * **[share](share.ipynb)** draw in other people's data and let them use yours
# * **similarLines** spot the similarities between lines
#
# ---
#
# See the [cookbook](cookbook) for recipes for small, concrete tasks.
#
# CC-BY <NAME>
| dss/similarLines.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Deep CORAL Implementation
# ## Introduction
# Machine learning practitioners are frequently hindered and set back in their efforts by an inadequate amount of labeled data in their chosen domains. In these situations gathering additional relevant, labeled data is often prohibitively expensive or time consuming. As a result ML professionals frequently seek methods of incorporating additional readily available data that comes from another domain and/or is unlabelled. Deep CORAL is a cutting edge algorithm for improving model accuracy through the incorporation of such additional data sources. It can be used for both incorporating out-of-domain data (i.e. images taken with a different camera type or setting as in the Amazon vs. webcam images of the Office 31 dataset) or for semi-supervised learning with a small number of labeled images and a larger body of in-domain, unlabeled images. Deep CORAL is able to accomplish this goal by using a nonlinear transformation that aligns the correlations of layer activations in deep neural networks.
# ### Initialize the workspace with necessary packages
import boto3
import tarfile
import json
from PIL import Image
import requests
from io import BytesIO
# ### Initialize AWS services
# +
# This step requires that you have AWS configured on the computer with an access key and secret
# access key for your account
invoke_url = 'https://sqs.us-west-2.amazonaws.com/758621242503/DA_API_Q2'
listen_url = 'https://sqs.us-west-2.amazonaws.com/758621242503/DA_API_Response'
s3client = boto3.client('s3')
sqs = boto3.client('sqs')
client = boto3.client('sagemaker-runtime')
# -
# ### Prepare data and upload to S3 storage for use in training
# The data must be present in the local directory in the folder structure below:
# - Data
# - labeled
# - folder for each class with images
# - unlabeled
# - "imagesโ folder with all images
# - test
# - folder for each class with images
# - trainingparameters.txt file
#
def make_tarfile(output_filename, source_dir):
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir)
# Make your own tar-file name here
your_filename = "API_test_data.tar.gz"
make_tarfile(your_filename,'data')
# Upload the data package to your S3 bucket. Read/write permission for this bucket must be
# provided to the kittmiller25 AWS account so that the data can be accessed and the trained
# model and files may be uploaded after training
your_bucket = "domaintestkitt"
with open(your_filename, "rb") as f:
s3client.upload_fileobj(f, your_bucket, your_filename)
# ### Send training request
# +
# Send request with data location and naming information to the SQS queue for initiating training
send_response = sqs.send_message(
QueueUrl=invoke_url,
MessageAttributes={
'bucket': {
'DataType': 'String',
'StringValue': your_bucket
},
'fname' :{
'DataType': 'String',
'StringValue': your_filename
}
},
MessageBody=('Training request')
)
print(send_response['MessageId'])
# -
# ### Check for response from the training algorithm
# Typically any error responses will come back within 1-2 minutes of sending the training request. If no error has been received within 2 minutes, training is likely proceeding smoothly. Training times vary based on the hyperparameters and the size of datasets, but with 1-3 thousand images each in the labeled and unlabeled datasets training with 25 epochs typically takes approximately 20-25 minutes, with an additional ~10 minutes for endpoint creation.
# Receive training result message from the SQS listener queue
listen_response = sqs.receive_message(
QueueUrl=listen_url,
MaxNumberOfMessages=1,
WaitTimeSeconds=20,
MessageAttributeNames=[
'Title'],
)
print(listen_response['Messages'][0]['Body'])
# Delete message after receiving to prevent from clogging the queue or causing confusion
# with any other users
sqs.delete_message(
QueueUrl=listen_url,
ReceiptHandle=listen_response['Messages'][0]['ReceiptHandle']
);
# ### Test the model at the endpoint
# Select an image for model testing
input = {'url':'https://richmedia.ca-richimage.com/ImageDelivery/imageService?profileId=12026540&id=1390281&recipeId=728'}
response = requests.get(input['url'])
img = Image.open(BytesIO(response.content))
img
# Submit the image to the endpoint and receive the inference
response = client.invoke_endpoint(
EndpointName='pytorch-inference-2020-03-28-19-22-01-460',
Body=json.dumps(input),
ContentType='application/json'
)
print(str(response['Body'].read(),'utf-8'))
| Deployment.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] toc=true
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Objectives" data-toc-modified-id="Objectives-1"><span class="toc-item-num">1 </span>Objectives</a></span></li><li><span><a href="#Motivation-for-Hypothesis-Testing" data-toc-modified-id="Motivation-for-Hypothesis-Testing-2"><span class="toc-item-num">2 </span>Motivation for Hypothesis Testing</a></span></li><li><span><a href="#Experiment-Design" data-toc-modified-id="Experiment-Design-3"><span class="toc-item-num">3 </span>Experiment Design</a></span><ul class="toc-item"><li><span><a href="#The-Scientific-Method" data-toc-modified-id="The-Scientific-Method-3.1"><span class="toc-item-num">3.1 </span>The Scientific Method</a></span></li><li><span><a href="#Making-a-Good-Experiment" data-toc-modified-id="Making-a-Good-Experiment-3.2"><span class="toc-item-num">3.2 </span>Making a Good Experiment</a></span><ul class="toc-item"><li><span><a href="#Control-Groups" data-toc-modified-id="Control-Groups-3.2.1"><span class="toc-item-num">3.2.1 </span>Control Groups</a></span></li><li><span><a href="#Random-Trials" data-toc-modified-id="Random-Trials-3.2.2"><span class="toc-item-num">3.2.2 </span>Random Trials</a></span></li><li><span><a href="#Sample-Size" data-toc-modified-id="Sample-Size-3.2.3"><span class="toc-item-num">3.2.3 </span>Sample Size</a></span></li><li><span><a href="#Reproducible" data-toc-modified-id="Reproducible-3.2.4"><span class="toc-item-num">3.2.4 </span>Reproducible</a></span></li></ul></li><li><span><a href="#Scenarios" data-toc-modified-id="Scenarios-3.3"><span class="toc-item-num">3.3 </span>Scenarios</a></span></li></ul></li><li><span><a href="#Introducing-Hypothesis-Testing" data-toc-modified-id="Introducing-Hypothesis-Testing-4"><span class="toc-item-num">4 </span>Introducing Hypothesis Testing</a></span><ul class="toc-item"><li><span><a href="#Intuition" data-toc-modified-id="Intuition-4.1"><span class="toc-item-num">4.1 </span>Intuition</a></span></li><li><span><a href="#Scenario" data-toc-modified-id="Scenario-4.2"><span class="toc-item-num">4.2 </span>Scenario</a></span></li><li><span><a href="#High-Level-Hypothesis-Testing" data-toc-modified-id="High-Level-Hypothesis-Testing-4.3"><span class="toc-item-num">4.3 </span>High-Level Hypothesis Testing</a></span></li></ul></li><li><span><a href="#Steps-of-a-Hypothesis-Test" data-toc-modified-id="Steps-of-a-Hypothesis-Test-5"><span class="toc-item-num">5 </span>Steps of a Hypothesis Test</a></span><ul class="toc-item"><li><span><a href="#STEP-1:-State-the-Null-and-Alternative-Hypotheses" data-toc-modified-id="STEP-1:-State-the-Null-and-Alternative-Hypotheses-5.1"><span class="toc-item-num">5.1 </span>STEP 1: State the Null and Alternative Hypotheses</a></span><ul class="toc-item"><li><span><a href="#The-Null-Hypothesis" data-toc-modified-id="The-Null-Hypothesis-5.1.1"><span class="toc-item-num">5.1.1 </span>The Null Hypothesis</a></span></li><li><span><a href="#The-Alternative-Hypothesis" data-toc-modified-id="The-Alternative-Hypothesis-5.1.2"><span class="toc-item-num">5.1.2 </span>The Alternative Hypothesis</a></span></li><li><span><a href="#๐ง -Knowledge-Check" data-toc-modified-id="๐ง -Knowledge-Check-5.1.3"><span class="toc-item-num">5.1.3 </span>๐ง Knowledge Check</a></span></li></ul></li><li><span><a href="#STEP-2:-Specify-Significance-Level" data-toc-modified-id="STEP-2:-Specify-Significance-Level-5.2"><span class="toc-item-num">5.2 </span>STEP 2: Specify Significance Level</a></span><ul class="toc-item"><li><span><a href="#A-Caution" data-toc-modified-id="A-Caution-5.2.1"><span class="toc-item-num">5.2.1 </span>A Caution</a></span></li></ul></li><li><span><a href="#STEP-3:-Calculate-the-Test-Statistic" data-toc-modified-id="STEP-3:-Calculate-the-Test-Statistic-5.3"><span class="toc-item-num">5.3 </span>STEP 3: Calculate the Test Statistic</a></span><ul class="toc-item"><li><span><a href="#Calculating-the-$z$-statistic" data-toc-modified-id="Calculating-the-$z$-statistic-5.3.1"><span class="toc-item-num">5.3.1 </span>Calculating the $z$-statistic</a></span></li></ul></li><li><span><a href="#STEP-4:-Calculate-p-value" data-toc-modified-id="STEP-4:-Calculate-p-value-5.4"><span class="toc-item-num">5.4 </span>STEP 4: Calculate p-value</a></span></li><li><span><a href="#STEP-5:-Interpret-p-value" data-toc-modified-id="STEP-5:-Interpret-p-value-5.5"><span class="toc-item-num">5.5 </span>STEP 5: Interpret p-value</a></span><ul class="toc-item"><li><span><a href="#Another-Warning" data-toc-modified-id="Another-Warning-5.5.1"><span class="toc-item-num">5.5.1 </span>Another Warning</a></span></li></ul></li><li><span><a href="#Summary" data-toc-modified-id="Summary-5.6"><span class="toc-item-num">5.6 </span>Summary</a></span></li></ul></li><li><span><a href="#Performing-a-$z$-test" data-toc-modified-id="Performing-a-$z$-test-6"><span class="toc-item-num">6 </span>Performing a $z$-test</a></span><ul class="toc-item"><li><span><a href="#$z$-Tests" data-toc-modified-id="$z$-Tests-6.1"><span class="toc-item-num">6.1 </span>$z$-Tests</a></span><ul class="toc-item"><li><span><a href="#Working-with-Just-the-Sample" data-toc-modified-id="Working-with-Just-the-Sample-6.1.1"><span class="toc-item-num">6.1.1 </span>Working with Just the Sample</a></span></li><li><span><a href="#Example" data-toc-modified-id="Example-6.1.2"><span class="toc-item-num">6.1.2 </span>Example</a></span></li></ul></li></ul></li><li><span><a href="#Summary" data-toc-modified-id="Summary-7"><span class="toc-item-num">7 </span>Summary</a></span></li></ul></div>
# -
from scipy import stats
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# + [markdown] heading_collapsed=true
# # Objectives
# + [markdown] hidden=true
# - Describe the basic framework and vocabulary for hypothesis testing
# - Define Null and Alternative Hypotheses
# - Define p-value, $\alpha$
# - Perform z-tests
# + [markdown] heading_collapsed=true
# # Motivation for Hypothesis Testing
# + [markdown] hidden=true
# When we want to be able to determine something about the world, we typically turn to science. And science is really built upon the idea testing ideas through **experiments**. If we have an idea, but our experiment(s) shows that it's unlikely to be true then we learned something about our world!
# + [markdown] hidden=true
# <img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Beaker_-_The_Noun_Project.svg" width=50%/>
# + [markdown] hidden=true
# Data _science_ can use this same process and it can be formalized through a statistical process called a **hypothesis test**. But before we can talk about performing these tests, we need to talk about how we design our experiments.
# + [markdown] heading_collapsed=true
# # Experiment Design
# + [markdown] hidden=true
# Experiments are how we get the data we need to determine if our observations are worthwhile! But if you have a poorly designed experiment, you can't trust the observations/data to say anything useful.
# + [markdown] hidden=true
# > **NOTE**
# >
# > We typically use the term "experiment" when doing a hypothesis test. This can be a little confusing when the data has been collected _before_ any other step. This is fine but we should consider if this experiment follows the general criteria of a "good" design.
# + [markdown] heading_collapsed=true hidden=true
# ## The Scientific Method
# + [markdown] hidden=true
# You should consider if the question you're looking to answer can be investigated with the **scientific method**. If it is, we can feel better that we're asking a _scientific question_ (compared to a question that is _unverifiable_).
# + [markdown] hidden=true
# There is no completely agreed upon "scientific method" but the following should help us know if we're on the right track:
# + [markdown] hidden=true
# - Question/Observation
# - Background Knowledge
# - Hypothesis
# - Experiment
# - Analysis
# - Conclusions
# + [markdown] heading_collapsed=true hidden=true
# ## Making a Good Experiment
# + [markdown] hidden=true
# We strive to make the best we can which is a perfectly designed experiment that would test every possible answer to a question. Of course this is unrealistic, though we strive towards the best experiment we can to answer questions.
# + [markdown] hidden=true
# Below are a few items to consider for a good experiment. An experiment doesn't have to fulfill everything to still be useful, though the more items off the checkoff list the more certain we'll feel about our results.
# + [markdown] heading_collapsed=true hidden=true
# ### Control Groups
# + [markdown] hidden=true
# > Your experiment should consider other factors that could affect the outcome and try to account for (or *control*) those factors
# + [markdown] heading_collapsed=true hidden=true
# ### Random Trials
# + [markdown] hidden=true
# > By having random trials/samples, you're less likely to have bias in your observations/data
# + [markdown] heading_collapsed=true hidden=true
# ### Sample Size
# + [markdown] hidden=true
# > A large enough sample size that we can reasonably extrapolate to the population of interest
# + [markdown] heading_collapsed=true hidden=true
# ### Reproducible
# + [markdown] hidden=true
# > Being able to reproduce the experiment means we can test again and ensure are results are valid.
# + [markdown] heading_collapsed=true hidden=true
# ## Scenarios
# + [markdown] hidden=true
# - Chemistry - do inputs from two different barley fields produce different
# # yields?
# - Astrophysics - do star systems with near-orbiting gas giants have hotter
# # stars?
# - Medicine - BMI vs. Hypertension, etc.
# - Business - which ad is more effective given engagement?
# + [markdown] hidden=true
# 
# + [markdown] hidden=true
# 
# + [markdown] heading_collapsed=true
# # Introducing Hypothesis Testing
# + [markdown] heading_collapsed=true hidden=true
# ## Intuition
# + [markdown] hidden=true
# Suppose we gather a sample from a population. We want to know if the sample is a good representation of the population. Essentially, is it right to say the sample is _representative_ of that population.
# + [markdown] heading_collapsed=true hidden=true
# ## Scenario
# + [markdown] hidden=true
# Imagine we're driving down the road of our hometown and see a local high school's school bus broken down at the side of the road. All of the students are safely waiting outside of the bus and you notice that they seem a bit on the taller side.
#
#
# 
# + [markdown] hidden=true
# You wonder if these students are representative of the full student body or are particularly special in terms of height (maybe they could all be on the basketball team ๐).
#
# We can quantify how _"weird"_ this group is compared to the student body knowing/measuring the means and standard deviations of the population and sample.
# + [markdown] hidden=true
# > This is at heart what hypothesis testing is: ***"Does our sample come from the population or is it a special set?"***
# + [markdown] hidden=true
# Suppose we already know that high school students are on average $65$ inches with a standard deviation of $3$ inches.
#
# If we measured everyone on that bus, we would have found that their average height was $73$ inches. Through standardization, we know then the $z$-score for these particular students is $\frac{73-65}{3}=\frac{8}{3}\approx 2.7$.
# + [markdown] hidden=true
# According to the empirical (68โ95โ99.7) rule for normal distributions there is only roughly a $0.003\%$ chance that the sample came from the same population, because it is roughly 3 standard deviations above the mean.
#
#
# Seems unlikely that these students aren't a special subset of the student population.
#
# <img src="img/normal_sd_new.png" width="500">
#
# + [markdown] hidden=true
# > **NOTE**
# >
# > We will later formalize this by defining a _threshold value_ $\alpha$ (called the **significance level**) to decide whether we believe that the sample is from the same underlying population or not.
# + [markdown] heading_collapsed=true hidden=true
# ## High-Level Hypothesis Testing
# + [markdown] hidden=true
# We will go deeper into in the parts & steps of hypothesis tests, but here is a high-level understanding of what a hypothesis test will look like:
# + [markdown] hidden=true
# 1. Start with a Scientific Question (yes/no)
# 2. Take the skeptical stance (**null hypothesis**)
# 3. State the complement (**alternative hypothesis**)
# 4. Set a threshold for errors (**$\alpha$ significance level**)
# 5. Create a model (*test statistic*) of the situation *assuming the null hypothesis is true*
# 6. Decide whether or not to *reject the null hypothesis* by comparing the *threshold* and *test statistic*
# + [markdown] heading_collapsed=true
# # Steps of a Hypothesis Test
# + [markdown] hidden=true
# Let's go through the steps of the hypothesis test one-by-one and define what we need as we go.
#
# Below are the general steps of the hypothesis test (we'll focus on the one-sample $z$-test)
# + [markdown] hidden=true
# 1. State the null hypothesis and the alternative hypothesis
# 2. Specify significance level ($\alpha$)
# 3. Calculate test statistic (z-statistic)
# 4. Calculate p-value
# 5. Interpret p-value (reject or fail to reject the null hypothesis)
#
# + [markdown] heading_collapsed=true hidden=true
# ## STEP 1: State the Null and Alternative Hypotheses
# + [markdown] hidden=true
# It's important to state both the **null hypothesis** $H_0$ and **alternative hypothesis** $H_a$ (or $H_1$) so we can be clear in what we can learn from our hypothesis test.
# + [markdown] heading_collapsed=true hidden=true
# ### The Null Hypothesis
# + [markdown] hidden=true
# > There is NOTHING, **no** difference.
# 
# + [markdown] hidden=true
# > The **null hypothesis** $H_0$ is what we would expect if there is no difference from our sample to our comparison group (population in many cases).
# + [markdown] hidden=true
# If we're testing the function of a new drug, then the null hypothesis will say something like:
#
# > The drug has _no effect_ on patients (does not speed up recovery)
# + [markdown] hidden=true
# If we're testing whether Peeps cause dementia, then the null hypothesis will say:
# > There is _no correlation_ between Peeps consumption and the rate of dementia development
# + [markdown] heading_collapsed=true hidden=true
# ### The Alternative Hypothesis
# + [markdown] hidden=true
# > The **alternative hypothesis** $H_a$ or $H_1$ says the sample is _different_ from the comparison group. It is essentially the opposite of the null hypothesis (there is an _effect_).
# + [markdown] hidden=true
# Going back to our drug example, our alternative hypothesis could be:
# > The drug _decreases_ the time of recovery (versus not using the drug)
# + [markdown] hidden=true
# Going back to our Peeps & dementia example, our alternative hypothesis could be:
# > There is a _positive correlation_ between Peeps consumption and the rate of dementia development (as Peep consumption increases, the rate of dementia increases
# + [markdown] heading_collapsed=true hidden=true
# ### ๐ง Knowledge Check
# + [markdown] hidden=true
# 1. A drug manufacturer claims that a drug increases memory. It designs an experiment where both control and experimental groups are shown a series of images, and records the number of correct recollections until an error is made for each group.
# + [markdown] hidden=true
# Answer:
#
# Null: People who took the drug don't have more correct recollections than people who didn't take the drug.
#
# Alternative: People who took the drug do have more correct recollections than people who didn't take the drug.
# + [markdown] hidden=true
# 2. An online toystore claims that putting a 5 minute timer on the checkout page of its website decreases conversion rate. It sets up two versions of its site, one with a timer and one with no timer.
# + [markdown] hidden=true
# Answer:
#
# Null: Putting a timer on the checkout page does not decrease conversion rate.
# Alternative: Putting a timer on the checkout page does decrease conversion rate.
# + [markdown] hidden=true
# 3. The Kansas City public school system wants to test whether the scores of students who take standardized tests under the supervision of teachers differ from the scores of students who take them in rooms with school administrators.
# + [markdown] hidden=true
# Answer:
# + [markdown] hidden=true
# 4. A pest control company believes that the length of cockroach legs in colonies which have persisted after two or more insecticide treatements are longer than those in which have not been treated with insecticide.
# + [markdown] hidden=true
# Answer:
# + [markdown] hidden=true
# 5. A healthcare company believes patients between the ages of 18 and 25 participate in annual checkups less than all other age groups.
# + [markdown] hidden=true
# Answer:
# + [markdown] heading_collapsed=true hidden=true
# ## STEP 2: Specify Significance Level
# + [markdown] hidden=true
# Now that we have our hypotheses define, we have to determine when do we say an observation is **statistically significant**. Basically, how "weird" do things have to be until we reject $H_0$.
# + [markdown] hidden=true
# We choose a threshold called the **significance level** $\alpha$. The smaller the value, the more "weirdness" we're willing to accept before reject the null hypothesis.
#
# If the probability of observing a weird value (our sample) is smaller than $\alpha$, then we will reject the null-hypothesis.
# + [markdown] hidden=true
# Typically we choose $\alpha$ to be $0.05$ which means that we have to observe a sample that would occur less than $5\%$ of the time if the null hypothesis is true.
# + [markdown] heading_collapsed=true hidden=true
# ## STEP 3: Calculate the Test Statistic
# + [markdown] hidden=true
# With the setup from the prior steps, we can now look at our sample. We'll want to find a **test statistic** that can be compared to our distribution (usually something like the normal distribution).
# + [markdown] hidden=true
# Today we will focus on performing a **$z$-test** which is a hypothesis test that uses the normal curve. So we will find the $z$-score of our sample's mean also know as our **$z$-statistic** in the context of hypothesis testing.
#
# > **NOTE**
# >
# > Just know that we'll see there are other hypothesis tests that follow the same steps but differ in how we calculate their test statistics. We'll see more types of tests later on.
# + [markdown] heading_collapsed=true hidden=true
# ### Calculating the $z$-statistic
# + [markdown] hidden=true
# We first need to find the mean value of the sample $\bar{x}$
#
# > **NOTE**
# >
# > We use $\bar{x}$ for a sample over $\mu$ which is reserved for a population mean. This is to remind us not to confuse the two.
# + [markdown] hidden=true
# After finding the mean, we need the standard deviation of the population $\sigma$ to get our $z$-statistic.
# + [markdown] hidden=true
# -----------
# + [markdown] hidden=true
# If we already know it, great! But what if we don't?
#
# Well, we can _estimate_ the standard deviation from our sample. We call this the **standard error** $s_\bar{x}$ (or $\hat{\sigma_x}$) and is defined like below:
#
# $$ \large \sigma \approx s_\bar{x} = \frac{s}{\sqrt{n}} $$
#
# where $n$ is the number of data points in the sample and $s$ is the standard deviation of the sample or **sample standard deviation** (sometimes denoted as $\sigma_x$)
# + [markdown] hidden=true
# We won't dig too deep into this, but notice that the square-root in the denominator. This is because we're saying that the sample standard deviation $s$ is an estimate of the population standard deviation $\sigma$, but as we get more data points in our sample our estimate gets narrower/smaller.
# + [markdown] hidden=true
# -----------
# + [markdown] hidden=true
# And finally, we can calculate our $z$-statistic:
#
# $$ \large z = \frac{\bar{x} - \mu}{\sigma} $$
#
# > Remember that our $\mu$ comes from the null hypothesis; we expect our sample to have about the same mean as the population if the null hypothesis is true.
# + [markdown] heading_collapsed=true hidden=true
# ## STEP 4: Calculate p-value
# + [markdown] hidden=true
# The basic idea of a $p$-value is to quantify the probability that the results seen are in fact the result of mere random chance.
#
# This is connected with the null hypothesis: If the null hypothesis is true and there is _**no** significant_ correlation between the population variables and our samples observed variable and would have to be the result of mere random chance.
# + [markdown] hidden=true
# The p-value is _probability_ that we would observe the sample measurement ($\bar{x}$) assuming the null hypothesis (the standard normal curve). This tells us how _likely or unlikely_ our sample measurement is
# + [markdown] hidden=true
# ----------------------------
# + [markdown] hidden=true
# For the $z$-test, we can use the PDF of the normal distribution to find this probability (`p = 1 - scipy.stats.norm.cdf(z_score)`)
# + [markdown] heading_collapsed=true hidden=true
# ## STEP 5: Interpret p-value
# + [markdown] hidden=true
# Suppose we calculate a $p$-value for some statistic we've measured and we get a $p$-value of 20%. This would mean that there is a 20% chance that the results we observed were the result of mere random chance. Probably this is high enough that we ought _not_ to reject the null hypothesis that our variables are uncorrelated.
# + [markdown] hidden=true
# If $p \lt \alpha$, we reject the null hypothesis.:
#
# If $p \geq \alpha$, we fail to reject the null hypothesis.
# + [markdown] hidden=true
# > **NOTE**
# >
# > This only tells us if there is a statistically significant difference not to what _degree_
# > 
# > โ๏ธ _Be careful how you interpret your p-value_
# + [markdown] hidden=true
# > **We never _accept_ the null hypothesis, because future experiments may yield significant results.**
#
# * We do not throw out "failed" experiments!
# * We say "this methodology, with this data, does not produce significant results"
# * Maybe we need more data!
#
# + [markdown] hidden=true
# In practice, a $p$-value _threshold_ ($\alpha$) of $5\%$ is very often the default value for these tests of statistical significance. Thus, if it is calculated that the chance that the results we observed were actually the result of randomness is less than 1 in 20, then we would _reject_ the null hypothesis.
# + [markdown] heading_collapsed=true hidden=true
# ### Another Warning
# + [markdown] hidden=true
# The choice of $\alpha = 0.05$ is arbitrary and has survived as a pseudo-standard largely because of traditions in teaching.
#
# The [American Statistical Association](https://www.amstat.org) has [recently been questioning this standard](https://www.tandfonline.com/toc/utas20/73/sup1?nav=tocList&) and in fact there are movements to reject hypothesis testing in a more wholesale way.
#
# The chief thing to keep in mind is that binary test results are often misleading. And as for an appropriate $p$-level: This really depends on the case. In some scenarios, false positives are more costly than in others. We must also determine our $\alpha$ level *before* we conduct our tests. Otherwise, we will be accused of $p$-hacking.
# + [markdown] hidden=true
# ---------------
# + [markdown] hidden=true
# A cautionary study, the weight-loss chocolate study conducted by <NAME>: https://www.scribd.com/doc/266969860/Chocolate-causes-weight-loss
#
# > Article on explaining the whole ordeal https://io9.gizmodo.com/i-fooled-millions-into-thinking-chocolate-helps-weight-1707251800
# + [markdown] heading_collapsed=true hidden=true
# ## Summary
# + [markdown] hidden=true
# Steps in doing hypothesis test (one-sample z-test):
#
# 1. State alternative hypothesis (and null)
# * example: sample mean is greater than population mean (mu)
# 2. Specify significance level (alpha)
# * alpha is the probability of rejecting null even though its true (!)
# 3. Calculate test statistic (z-statistic)
# * $z = \frac{\bar{x}-\mu}{\sigma}$
# 4. Calculate p-value
# * p = 1 - CDF(z-stat)
# * Probability we'd find this value given null is true
# * `1 - scipy.stats.norm.cdf(z_score)`
# 5. Interpret p-value
#
#
#
# + [markdown] heading_collapsed=true
# # Performing a $z$-test
# + [markdown] heading_collapsed=true hidden=true
# ## $z$-Tests
# + [markdown] hidden=true
# A $z$-test is used when you know the population mean and standard deviation.
# + [markdown] hidden=true
# Our test statistic is the $z$-statistic.
# + [markdown] hidden=true
# For a single point in relation to a distribution of points:
#
# $z = \dfrac{{x} - \mu}{\sigma}$
#
#
# + [markdown] hidden=true
# <br>Our $z$-score tells us how many standard deviations away from the mean our point is.
# <br>We assume that the sample population is normally destributed, and we are familiar with the empirical rule: <br>66:95:99.7
#
# 
#
# + [markdown] hidden=true
# Because of this, we can say, with a $z$-score of approximately 2, our data point is 2 standard deviations from the mean, and therefore has a probability of appearing of 1-.95, or .05.
# + [markdown] hidden=true
# Recall the following example: Assume the mean height for women is normally distributed with a mean of 65 inches and a standard deviation of 4 inches. What is the $z$-score of a woman who is 75 inches tall?
# + hidden=true
z_score = (75 - 65)/4
print(z_score)
# + [markdown] heading_collapsed=true hidden=true
# ### Working with Just the Sample
# + [markdown] hidden=true
# When we are working with a sampling distribution, the z score is equal to <br><br> $\Large z = \dfrac{{\bar{x}} - \mu_{0}}{\dfrac{\sigma}{\sqrt{n}}}$
# + [markdown] hidden=true
# $\bar{x}$ equals the sample mean.
# <br>$\mu_{0}$ is the mean associated with the null hypothesis.
# <br>$\sigma$ is the population standard deviation
# <br>$\sqrt{n}$ is the sample size, which reflects that we are dealing with a sample of the population, not the entire population.
# + [markdown] hidden=true
# The denominator $\frac{\sigma}{\sqrt{n}}$, is the standard error
#
# Standard error is the standard deviation of the sampling mean. We will go into that further below.
# + hidden=true
sample_female_heights = [68, 65, 69, 70, 70,
61, 59, 65, 64, 66,
72, 71, 68, 66, 64,
65, 65, 70, 71, 63,
72, 66, 65, 65, 72]
x_bar = np.mean(sample_female_heights)
mu = 65
n = len(sample_female_heights)
std = 4
z = (x_bar - mu)/(4/np.sqrt(n))
z
# + hidden=true
# we can use stats to calculate the percentile
print(stats.norm.cdf(z))
# We can also use the survival function to calculate the probability. It's '1 - cdf'
print(stats.norm.sf(z))
# + [markdown] heading_collapsed=true hidden=true
# ### Example
# + [markdown] hidden=true
# Let's work with the normal distribution, since it's so useful. Suppose we are told that African elephants have weights distributed normally around a mean of 9000 lbs., with a standard deviation of 900 lbs. Pachyderm Adventures has recently measured the weights of 40 African elephants in Gabon and has calculated their average weight at 8637 lbs. They claim that these statistics on the Gabonese elephants are significant. Let's find out!
# + [markdown] hidden=true
# What is our null hypothesis?
# + hidden=true
# The Gabonese elephants are not different in weight from the other elephants.
# + [markdown] hidden=true
# What is our alternative hypothesis?
# + hidden=true
# The Gabonese elephants are different in weight.
# + [markdown] hidden=true
# What is our alpha?
# + hidden=true
alpha = 0.5
# + [markdown] hidden=true
# Remember we gave the formula for standard error before as $\frac{\sigma}{\sqrt{n}}$
# <br> Let's calculate that with our elephant numbers.
# + hidden=true
se = 900 / np.sqrt(40)
se
# + [markdown] hidden=true
# Now let's calculate the z-score analytically.
# Remember the formula for z-score:
# $z = \dfrac{{\bar{x}} - \mu_{0}}{\dfrac{\sigma}{\sqrt{n}}}$
# + hidden=true
x_bar = 8637
mu = 9000
se = 142.3
z = (x_bar - mu) / se
z
# + hidden=true
# Now we get our p-value from the test statistic:
stats.norm.cdf(z)
# So this saying that the chance of seeing this is half a percent. So we would discard our null hypothesis.
| Phase_2/ds-z_tests-nbz32-main/hypothesis_testing.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:mypy36]
# language: python
# name: conda-env-mypy36-py
# ---
# # Exploring and undertanding documental databases with topic models
#
# Version 1.0
#
# Date: Nov 23, 2017
#
# Authors:
#
# * <NAME> (<EMAIL>)
# * <NAME> (<EMAIL>)
# +
# Common imports
# %matplotlib inline
import matplotlib.pyplot as plt
import pylab
import numpy as np
# import pandas as pd
# import os
from os.path import isfile, join
# import scipy.io as sio
# import scipy
import zipfile as zp
# import shutil
# import difflib
import gensim
# -
# ## 1. Corpus acquisition
#
# In this block we will work with collections of text documents. The objectives will be:
#
# * Find the most important topics in the collection and assign documents to topics
# * Analyze the structure of the collection by means of graph analysis
#
# We will work with a collection of research projects funded by the US National Science Foundation, that you can find under the `./data` directory. These files are publicly available from the NSF website.
# ### 1.1. Exploring file structure
#
# NSF project information is provided in XML files. Projects are yearly grouped in `.zip` files, and each project is saved in a different XML file. To explore the structure of such files, we will use the file `160057.xml`. Parsing XML files in python is rather easy using the `ElementTree` module.
# ####ย 1.1.1. File format
#
# To start with, you can have a look at the contents of the example file. We are interested on the following information of each project:
#
# * Project identifier
# * Project Title
# * Project Abstract
# * Budget
# * Starting Year (we will ignore project duration)
# * Institution (name, zipcode, and state)
# +
xmlfile = '../data/1600057.xml'
with open(xmlfile,'r') as fin:
print(fin.read())
# -
# #### 1.1.2. Parsing XML
#
# XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree. The `ElementTree` module has two classes for this purpose:
#
# * `ElementTree` represents the whole XML document as a tree
# * `Element` represents a single node in this tree
#
# We can import XML data by reading an XML file:
import xml.etree.ElementTree as ET
root = ET.fromstring(open(xmlfile,'r').read())
# The code below implements a function that parses the XML files and provides as its output a dictionary with fields:
#
# project_code (string)
# title (string)
# abstract (string)
# budget (float)
# year (string)
# institution (tuple with elements: name, zipcode, and statecode)
#
# +
def parse_xmlproject(xml_string):
"""This function processess the specified XML field,
and outputs a dictionary with the desired project information
:xml_string: String with XML content
:Returns: Dictionary with indicated files
"""
root = ET.fromstring(xml_string)
dictio = {}
for child in root[0]:
if child.tag.lower() == 'awardtitle':
dictio['title'] = child.text
elif child.tag.lower() == 'awardeffectivedate':
dictio['year'] = str(child.text[-4:])
elif child.tag.lower() == 'awardamount':
dictio['budget'] = float(child.text)
elif child.tag.lower() == 'abstractnarration':
dictio['abstract'] = child.text
elif child.tag.lower() == 'awardid':
dictio['project_code'] = child.text
elif child.tag.lower() == 'institution':
#For the institution we have to access the children elements
#and search for the name, zipcode, and statecode only
name = ''
zipcode = ''
statecode = ''
for child2 in child:
if child2.tag.lower() == 'name':
name = child2.text
elif child2.tag.lower() == 'zipcode':
zipcode = child2.text
elif child2.tag.lower() == 'statecode':
statecode = child2.text
dictio['institution'] = (name, zipcode, statecode)
return dictio
parse_xmlproject(open(xmlfile,'r').read())
# -
# ### 1.2. Building the dataset
#
# Now, we will use the function you just implemented, to create a database that we will use throughout this module.
#
# For simplicity, and given that the dataset is not too large, we will keep all projects in the RAM. The dataset will consist of a list containing the dictionaries associated to each of the considered projects in a time interval.
# +
# Construct an iterator (or a list) for the years you want to work with
years = [2015, 2016]
datafiles_path = '../data/'
NSF_data = []
for year in years:
zpobj = zp.ZipFile(join(datafiles_path, str(year)+'.zip'))
for fileinzip in zpobj.namelist():
if fileinzip.endswith('xml'):
#Some files seem to be incorrectly parsed
try:
project_dictio = parse_xmlproject(zpobj.read(fileinzip))
if project_dictio['abstract']:
NSF_data.append(project_dictio)
except:
pass
# -
# We will extract some characteristics of the constructed dataset:
# +
print('Number of projects in dataset:', len(NSF_data))
# Budget
budget_data = list(map(lambda x: x['budget'], NSF_data))
print('Average budget of projects in dataset:', np.mean(budget_data))
# Institutions
insti_data = list(map(lambda x: x['institution'], NSF_data))
print('Number of unique institutions in dataset:', len(set(insti_data)))
# Counts per year
counts = dict()
for project in NSF_data:
counts[project['year']] = counts.get(project['year'],0) + 1
print('Breakdown of projects by starting year:')
for el in counts:
print(el, ':', counts[el])
# -
# For the rest of this notebook, we will work with the abstracts only. The list of all abstract will be the corpus we will work with.
# +
corpus_raw = list(map(lambda x: x['abstract'], NSF_data))
abstractlen_data = list(map(lambda x: len(x), corpus_raw))
print('Average length of projects abstracts (in characters):', np.mean(abstractlen_data))
# -
# ## 2. Corpus Processing
#
# Topic modelling algorithms process vectorized data. In order to apply them, we need to transform the raw text input data into a vector representation. To do so, we will remove irrelevant information from the text data and preserve as much relevant information as possible to capture the semantic content in the document collection.
#
# Thus, we will proceed with the following steps:
#
# 1. Tokenization
# 2. Homogeneization, which includes:
# 1. Removing capitalization.
# 2. Removing non alphanumeric tokens (e.g. punktuation signs)
# 3. Stemming/Lemmatization.
# 3. Cleaning
# 4. Vectorization
# For the first steps, we will use some of the powerful methods available from the [Natural Language Toolkit](http://www.nltk.org). In order to use the `word_tokenize` method from nltk, you might need to get the appropriate libraries using `nltk.download()`. You must select option "d) Download", and identifier "punkt"
from nltk import download
# You should comment this code fragment if the package is already available.
# download('punkt')
# download('stopwords')
# ### 2.1. Corpus Processing
# We will create a list that contains just the abstracts in the dataset. As the order of the elements in a list is fixed, it will be later straightforward to match the processed abstracts to metadata associated to their corresponding projects.
# **Exercise 1**: Generate a corpus of processed documents. For each document in `corpus_raw` complete the following steps:
# 1. Tokenize.
# 2. Remove capitalization and non-alphanumeric tokens.
# 3. Lemmatize
# 4. Remove the stopwords using the NLTK stopwords list.
#
# +
from nltk.tokenize import word_tokenize
from nltk.stem import SnowballStemmer, WordNetLemmatizer
from nltk.corpus import stopwords
# Maybe you can try the stemmer too.
# stemmer = SnowballStemmer('english')
wnl = WordNetLemmatizer()
stopwords_en = stopwords.words('english')
# Initialize ouput corpus
corpus_clean = []
ndocs = len(corpus_raw)
for n, text in enumerate(corpus_raw):
if not n%100:
print('\rTokenizing document', n, 'out of', ndocs, end='', flush=True)
# Tokenize each text entry.
# tokens = <FILL IN>
tokens = word_tokenize(text)
# tokens_filtered = <FILL IN>
tokens_filtered = [el.lower() for el in tokens if el.isalnum()]
# tokens_lemmatized = <FILL IN>
tokens_lemmatized = [wnl.lemmatize(el) for el in tokens_filtered]
# tokens_clean = <FILL IN>
tokens_clean = [token for token in tokens_lemmatized if token not in stopwords_en]
# Add the new token list as a new element to corpus_clean (that will be a list of lists)
# corpus_clean.<FILL IN>
corpus_clean.append(tokens_clean)
print('\n\n The corpus has been tokenized. Check the result for the first abstract:')
print(corpus_raw[0])
print(corpus_clean[0])
# -
# ### 2.4. Vectorization
#
# Up to this point, we have transformed the raw text collection in a list of documents, where each documen is a collection of the words that are most relevant for semantic analysis. Now, we need to convert these data (a list of token lists) into a numerical representation (a list of vectors, or a matrix). To do so, we will start using the tools provided by the `gensim` library.
#
# As a first step, we create a dictionary containing all tokens in our text corpus, and assigning an integer identifier to each one of them.
# +
# Create dictionary of tokens
D = gensim.corpora.Dictionary(corpus_clean)
n_tokens = len(D)
print('The dictionary contains', n_tokens, 'terms')
print('First terms in the dictionary:')
for n in range(10):
print(str(n), ':', D[n])
# -
# We can also filter out terms that appear in too few or too many of the documents in the dataset:
# +
no_below = 5 #Minimum number of documents to keep a term in the dictionary
no_above = .75 #Maximum proportion of documents in which a term can appear to be kept in the dictionary
D.filter_extremes(no_below=no_below, no_above=no_above, keep_n=25000)
n_tokens = len(D)
print('The dictionary contains', n_tokens, 'terms')
print('First terms in the dictionary:')
for n in range(10):
print(str(n), ':', D[n])
# -
# In the second step, let us create a numerical version of our corpus using the `doc2bow` method. In general, `D.doc2bow(token_list)` transforms any list of tokens into a list of tuples `(token_id, n)`, one per each token in `token_list`, where `token_id` is the token identifier (according to dictionary `D`) and `n` is the number of occurrences of such token in `token_list`.
#
# **Exercise 2**: Apply the `doc2bow` method from gensim dictionary `D`, to all tokens in every document in `clean_abstracts`. The result must be a new list named `corpus_bow` where each element is a list of tuples `(token_id, number_of_occurrences)`.
# corpus_bow = <FILL IN>
corpus_bow = [D.doc2bow(doc) for doc in corpus_clean]
# At this point, it is good to make sure to understand what has happened. In `clean_abstracts` we had a list of token lists. With it, we have constructed a Dictionary, `D`, which assigns an integer identifier to each token in the corpus.
# After that, we have transformed each article (in `clean_abstracts`) in a list tuples `(id, n)`.
print('Original document (after cleaning):')
print(corpus_clean[0])
print('Sparse vector representation (first 10 components):')
print(corpus_bow[0][:10])
print('Word counts for the first project (first 10 components):')
print(list(map(lambda x: (D[x[0]], x[1]), corpus_bow[0][:10])))
# Note that we can interpret each element of corpus_bow as a `sparse_vector`. For example, a list of tuples
#
# [(0, 1), (3, 3), (5,2)]
#
# for a dictionary of 10 elements can be represented as a vector, where any tuple `(id, n)` states that position `id` must take value `n`. The rest of positions must be zero.
#
# [1, 0, 0, 3, 0, 2, 0, 0, 0, 0]
#
# These sparse vectors will be the inputs to the topic modeling algorithms.
#
# As a summary, the following variables will be relevant for the next chapters:
# * `D`: A gensim dictionary. Term strings can be accessed using the numeric identifiers. For instance, `D[0]` contains the string corresponding to the first position in the BoW representation.
# * `corpus_bow`: BoW corpus. A list containing an entry per project in the dataset, and consisting of the (sparse) BoW representation for the abstract of that project.
# * `NSF_data`: A list containing an entry per project in the dataset, and consisting of metadata for the projects in the dataset
#
# The way we have constructed the `corpus_bow` variable guarantees that the order is preserved, so that the projects are listed in the same order in the lists `corpus_bow` and `NSF_data`.
# Before starting with the semantic analyisis, it is interesting to observe the token distribution for the given corpus.
# +
# SORTED TOKEN FREQUENCIES (I):
# Create a "flat" corpus with all tuples in a single list
corpus_bow_flat = [item for sublist in corpus_bow for item in sublist]
# Initialize a numpy array that we will use to count tokens.
# token_count[n] should store the number of ocurrences of the n-th token, D[n]
token_count = np.zeros(n_tokens)
# Count the number of occurrences of each token.
for x in corpus_bow_flat:
# Update the proper element in token_count
# scode: <FILL IN>
token_count[x[0]] += x[1]
# Sort by decreasing number of occurences
ids_sorted = np.argsort(- token_count)
tf_sorted = token_count[ids_sorted]
# -
# `ids_sorted` is a list of all token ids, sorted by decreasing number of occurrences in the whole corpus. For instance, the most frequent term is
print(D[ids_sorted[0]])
# which appears
print("{0} times in the whole corpus".format(tf_sorted[0]))
# In the following we plot the most frequent terms in the corpus.
# +
# SORTED TOKEN FREQUENCIES (II):
plt.rcdefaults()
# Example data
n_art = len(NSF_data)
n_bins = 25
hot_tokens = [D[i] for i in ids_sorted[n_bins-1::-1]]
y_pos = np.arange(len(hot_tokens))
z = tf_sorted[n_bins-1::-1]/n_art
plt.figure()
plt.barh(y_pos, z, align='center', alpha=0.4)
plt.yticks(y_pos, hot_tokens)
plt.xlabel('Average number of occurrences per article')
plt.title('Token distribution')
plt.show()
# +
# SORTED TOKEN FREQUENCIES:
# Example data
plt.figure()
plt.semilogy(tf_sorted)
plt.ylabel('Total number of occurrences')
plt.xlabel('Token rank')
plt.title('Token occurrences')
plt.show()
# +
# cold_tokens = <FILL IN>
cold_tokens = [D[i] for i in ids_sorted if tf_sorted[i]==1]
print("There are {0} cold tokens, which represent {1}% of the total number of tokens in the dictionary".format(
len(cold_tokens), float(len(cold_tokens))/n_tokens*100))
# -
# ### 2.5. Dictionary properties
#
# As a final comment, note that gensim dictionaries contain a method `dfs` to compute the word counts automatically. In the code below we build a list `all_counts` that contains tuples (terms, document_counts).
all_counts = [(D[el], D.dfs[el]) for el in D.dfs]
all_counts = sorted(all_counts, key=lambda x: x[1])
# ## 3. Topic Modeling
#
# There are several implementations of the LDA topic model in python:
#
# * Python library `lda`.
# * Gensim module: `gensim.models.ldamodel.LdaModel`
# * Sci-kit Learn module: `sklearn.decomposition`
#
# In the following sections we explore the use of `gensim`
#
# ### 3.1. Training a topic model using Gensim LDA
#
# Since we already have computed the dictionary and documents BoW representation using Gensim, computing the topic model is straightforward using the `LdaModel()` function. Please, refer to Gensim API documentation for more information on the different parameters accepted by the function:
# ** Exercise 3**: Create an LDA model with the 50 topics using `corpus_bow` and the dictionary, `D`.
# +
num_topics = 50
# This might take some time...
# ldag = gensim.models.ldamodel.LdaModel(<FILL IN>)
ldag = gensim.models.ldamodel.LdaModel(corpus=corpus_bow, id2word=D, num_topics=num_topics)
# -
# ### 3.2. LDA model visualization
#
# Gensim provides a basic visualization of the obtained topics:
ldag.print_topics(num_topics=-1, num_words=10)
# A more useful visualization is provided by the python LDA visualization library, pyLDAvis.
#
# Before executing the next code fragment you need to install pyLDAvis:
#
# >> pip install (--user) pyLDAvis
# +
import pyLDAvis.gensim as gensimvis
import pyLDAvis
vis_data = gensimvis.prepare(ldag, corpus_bow, D)
pyLDAvis.display(vis_data)
# -
# ### 3.3. Gensim utility functions
#
# In addition to visualization purposes, topic models are useful to obtain a semantic representation of documents that can later be used with some other purpose:
#
# * In document classification problems
# * In content-based recommendations systems
#
# Essentially, the idea is that the topic model provides a (semantic) vector representation of documents, and use probability divergences to measure document similarity. The following functions of the `LdaModel` class will be useful in this context:
#
# * `get_topic_terms(topic_id)`: Gets vector of the probability distribution among words for the indicated topic
# * `get_document_topics(bow_vector)`: Gets (sparse) vector with the probability distribution among topics for the provided document
#
# **Exercise 4**: Show the probability distribution over words for topic 0.
# <SOL>
print(ldag.get_topic_terms(topicid=0))
# </SOL>
# **Exercise 5**: Show the probability distribution over topics for document 0.
print(ldag.get_document_topics(corpus_bow[0]))
# An alternative to the use of the `get_document_topics()` function is to directly transform a dataset using the `ldag` object as follows. You can apply this transformation to several documents at once, but then the result is an iterator from which you can build the corresponding list if necessary
# +
print(ldag[corpus_bow[0]])
print('When applied to a dataset it will provide an iterator')
print(ldag[corpus_bow[:3]])
print('We can rebuild the list from the iterator with a one liner')
print([el for el in ldag[corpus_bow[:3]]])
# -
# Finally, Gensim provides some useful functions to convert between formats, and to simplify interaction with numpy and scipy. The following code fragment converts a corpus in sparse format to a full numpy matrix
reduced_corpus = [el for el in ldag[corpus_bow[:3]]]
reduced_corpus = gensim.matutils.corpus2dense(reduced_corpus, num_topics).T
print(reduced_corpus)
# **Exercise 6**: Build a function that returns the most relevant projects for a given topic
# +
def most_relevant_projects(ldag, topicid, corpus_bow, nprojects=10):
"""This function returns the most relevant projects in corpus_bow
: ldag: The trained topic model object provided by gensim
: topicid: The topic for which we want to find the most relevant documents
: corpus_bow: The BoW representation of documents in Gensim format
: nprojects: Number of most relevant projects to identify
: Returns: A list with the identifiers of the most relevant projects
"""
print('Computing most relevant projects for Topic', topicid)
print('Topic composition is:')
print(ldag.show_topic(topicid))
#<SOL>
document_topic = [el for el in ldag[corpus_bow]]
document_topic = gensim.matutils.corpus2dense(document_topic, ldag.num_topics).T
return np.argsort(document_topic[:,topicid])[::-1][:nprojects].tolist()
#</SOL>
#To test the function we will find the most relevant projects for a subset of the NSF dataset
project_id = most_relevant_projects(ldag, 17, corpus_bow[:10000])
#Print titles of selected projects
for idproject in project_id:
print(NSF_data[idproject]['title'])
# -
# **Exercise 7**: Build a function that computes the semantic distance between two documents. For this, you can use the functions (or code fragments) provided in the library `dist_utils.py`.
def pairwase_dist(doc1, doc2):
"""This function returns the Jensen-Shannon
distance between the corresponding vectors of the documents
: doc1: Semantic representation for the doc1 (a vector of length ntopics)
: doc2: Semantic representation for the doc2 (a vector of length ntopics)
: Returns: The JS distance between doc1 and doc2 (a number)
"""
#<SOL>
#</SOL>
# **Exercise 8**: Explore the influence of the concentration parameters, $alpha$ and $eta$. In particular observe how do topic and document distributions change as these parameters increase.
# ** Exercise 9**: Note that we have not used the terms in the article titles, though the can be expected to contain relevant words for the topic modeling. Include the title words in the analyisis. In order to give them a special relevante, insert them in the corpus several times, so as to make their words more significant.
#
#
# ##ย 4. Saving data.
#
# The following function creates the Node CSV file that could be usefult for further processing. In particular, the output files could be used to visualize the document corpus as a graph using a visualization software like Gephi.
# +
#print(NSF_data[0].keys())
#print(NSF_data[0]['institution'])
def strNone(str_to_convert):
if str_to_convert is None:
return ''
else:
return str_to_convert
with open('NSF_nodes.csv','w') as fout:
fout.write('Id;Title;Year;Budget;UnivName;UnivZIP;State\n')
for project in NSF_data:
fout.write(project['project_code']+';'+project['title']+';')
fout.write(project['year']+';'+str(project['budget'])+';')
fout.write(project['institution'][0]+';')
fout.write(strNone(project['institution'][1])+';')
fout.write(strNone(project['institution'][2])+'\n')
# -
| TM2.Topic_Models/TM_py3_NSF/notebook/TM2_TopicModels_professor.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.9.0 64-bit
# language: python
# name: python3
# ---
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
i=0
j=0
total_length=len(nums1)+len(nums2)
l=[]
while (len(l)<=total_length/2 and not (total_length==0)):
if (i<len(nums1) and j<len(nums2) and nums1[i]<=nums2[j]) or (i<len(nums1) and j>=len(nums2)):
l.append(nums1[i])
i=i+1
elif (i<len(nums1) and j<len(nums2) and nums2[j]<=nums1[i]) or (j<len(nums2) and i>=len(nums1)):
l.append(nums2[j])
j=j+1
l_length=len(l)
if total_length%2==0 and l_length>=2:
return (l[l_length-2]+l[l_length-1])/2
elif l_length>=1:
return l[l_length-1]
else:
return 0
sol = Solution()
nums1 = [1,2]
nums2 = [3,4]
sol.findMedianSortedArrays(nums1,nums2)
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
total = len(nums1) + len(nums2)
result = []
# step 1
loc = total//2 + 1
# step 2
for i in range(loc):
try:
if(nums1[0]<=nums2[0]):
result.append(nums1.pop(0))
else:
result.append(nums2.pop(0))
except:
if(nums1==[]):
result.append(nums2.pop(0))
elif(nums2==[]):
result.append(nums1.pop(0))
# step 3
if(total%2==1):
return result[-1]
elif(total%2==0):
return (result[-1] + result[-2])/float(2)
| Problems/4-medianOfTwoSortedArrays.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] slideshow={"slide_type": "slide"}
# # Routing, Arbitrage
#
# Chapter 8 of [Real World Algorithms](https://mitpress.mit.edu/books/real-world-algorithms).
#
# ---
#
# > <NAME><br />
# > Athens University of Economics and Business
# + [markdown] slideshow={"slide_type": "slide"}
# ## The Bellman-Ford(-Moore) Algorithm
#
# The Bellman-Ford(-Moore) algorithm is an alternative to Dijkstra's algorithm for finding shortest paths in graphs.
#
# The basic idea is that we find the shortest paths from a start node to other nodes by using 1, 2, $n-1$ links, where $n$ is the number of nodes in the graph.
#
# So we start with shortest paths that have only one link, then with two links, and so on.
# + [markdown] slideshow={"slide_type": "slide"}
# We will use the following function to read weighted graphs from files containing one line per edge.
#
# This is familiar, it is the same that we used with Dijkstra's algorithm.
# + slideshow={"slide_type": "slide"}
def read_graph(filename, directed=False):
graph = {}
with open(filename) as input_file:
for line in input_file:
parts = line.split()
if len(parts) != 3:
continue # not a valid line, ignore
[n1, n2, w] = [ int (x) for x in parts ]
if n1 not in graph:
graph[n1] = []
if n2 not in graph:
graph[n2] = []
graph[n1].append((n2, w))
if not directed:
graph[n2].append((n1, w))
return graph
# + [markdown] slideshow={"slide_type": "slide"}
# As a first example we will use the traffic grid graph again.
#
# <img width="400" src="traffic_grid_graph.png"/>
# + [markdown] slideshow={"slide_type": "slide"}
# We go ahead and read it.
# + slideshow={"slide_type": "fragment"}
import pprint
g = read_graph('traffic_grid_graph.txt')
pprint.pprint(g)
# + [markdown] slideshow={"slide_type": "slide"}
# We need a substitute for $\infty$ in the algorithm.
#
# We will use `sys.maxsize` as a substitute for $\infty$ .
#
# In Python there is no predefined maximum integer; `sys.maxsize` gives the maximum 32 bit or 64 bit integer, depending on the machine.
#
# If that is not enough, we could simply assign a larger value.
# + slideshow={"slide_type": "fragment"}
import sys
MAX_INT = sys.maxsize
# + [markdown] slideshow={"slide_type": "slide"}
# The Bellman-Ford(-Moore) algorithm in Python is as follows; note that we just call it `bellman_ford(g, s)`.
# + slideshow={"slide_type": "fragment"}
def bellman_ford(g, s):
nodes = g.keys()
num_nodes = len(nodes)
# Initialize array holding path lengths.
dist = [ MAX_INT ] * num_nodes
dist[s] = 0
# Initialize array holding node predecessors.
pred = [ -1 ] * num_nodes
# Try using paths of length up to num_nodes
for i in range(num_nodes - 1):
# Try all edges: get all nodes...
for u in nodes:
# ...then for each node get all edges.
for v, w in g[u]:
# If the path to node v is bigger than the path to
# node u and then the edge to v, update it.
# If the distance to u is MAX_INT, it means we
# have not reached it yet, so we should ignore it.
if dist[u] != MAX_INT and dist[v] > dist[u] + w:
dist[v] = dist[u] + w
pred[v] = u
return (pred, dist)
# + [markdown] slideshow={"slide_type": "slide"}
# We can apply it directly on our traffic grid graph:
# -
pred, dist = bellman_ford(g, 0)
print('pred', pred)
print('dist', dist)
# + [markdown] slideshow={"slide_type": "slide"}
# We can improve on our implementation by noting that at each iteration we do not need to check all edges.
#
# In particular, at each iteration of the algorithm, instead of checking all edges, we need to check only the edges of the nodes whose estimates we updated at the previous iteration.
#
# To do that, we will use a First-In First-Out (FIFO) queue, which we'll get from Python's [`deque`](https://docs.python.org/3/library/collections.html#collections.deque).
#
# + [markdown] slideshow={"slide_type": "slide"}
# Each time we update an edge we will add the target node in the queue.
#
# We will get the edges to check in each iteration by getting the edges of the first node in the queue each time.
#
# We will kick-off the process by adding the source node into the queue.
#
# We'll call the implementation `bellman_ford_qb(g, s)`, where `qb` stands for "queue-based".
#
# + slideshow={"slide_type": "slide"}
import collections
def bellman_ford_qb(g, s):
nodes = g.keys()
num_nodes = len(nodes)
# Initialize array holding path lengths.
dist = [ MAX_INT ] * num_nodes
dist[s] = 0
# Initialize array holding node predecessors.
pred = [ -1 ] * num_nodes
# Initialize queue.
q = collections.deque()
# We'll use a list to check whether something
# is already in the queue, so that we won't
# add it twice.
in_queue = [ False ] * num_nodes
# We start by putting the starting node in the queue.
in_queue[s] = True
q.append(s)
# While the queue is not empty:
while len(q) != 0:
u = q.popleft()
in_queue[u] = False
# For every edge of the current node, check
# and update if needed.
for (v, w) in g[u]:
if dist[u] != MAX_INT and dist[v] > dist[u] + w:
dist[v] = dist[u] + w
pred[v] = u
# Add the node of the updated path in the queue
# if necessary.
if in_queue[v] == False:
q.append(v)
in_queue[v] = True
return (pred, dist)
# + [markdown] slideshow={"slide_type": "slide"}
# Here are the results of the algorithm on the traffic grid example:
# + slideshow={"slide_type": "fragment"}
pred, dist = bellman_ford_qb(g, 0)
print('pred', pred)
print('dist', dist)
# + [markdown] slideshow={"slide_type": "slide"}
# The Bellman-Ford(-Mooore) algorithm is generally slower than Dijkstra's, but it handle graphs with negative weights.
#
# Consider again the [negative_weights_graph.txt](negative_weights_graph.txt):
#
# <img width="150" src="negative_weights_graph.png"/>
# + [markdown] slideshow={"slide_type": "slide"}
# We go ahead and read it:
# + slideshow={"slide_type": "fragment"}
g = read_graph('negative_weights_graph.txt', directed=True)
pprint.pprint(g)
# + [markdown] slideshow={"slide_type": "slide"}
# Then if we try `bellman_ford(g, s)` on it, we'll see that we get the right results:
# + slideshow={"slide_type": "fragment"}
pred, dist = bellman_ford(g, 0)
print('pred', pred)
print('dist', dist)
# + [markdown] slideshow={"slide_type": "slide"}
# The same with the queue-based version:
#
# + slideshow={"slide_type": "fragment"}
pred, dist = bellman_ford_qb(g, 0)
print('pred', pred)
print('dist', dist)
# + [markdown] slideshow={"slide_type": "slide"}
# What about negative cycles?
#
# Consider the [negative_cycle_graph.txt](negative_cycle_graph.txt):
#
# <img width="220" src="negative_cycle_graph.png"/>
#
#
# + [markdown] slideshow={"slide_type": "slide"}
# We go ahead and read it:
# + slideshow={"slide_type": "fragment"}
g = read_graph('negative_cycle_graph.txt', directed=True)
pprint.pprint(g)
# + [markdown] slideshow={"slide_type": "slide"}
# Then we try bellman_ford(g, s) on it, and see what we get:
# + slideshow={"slide_type": "fragment"}
pred, dist = bellman_ford(g, 0)
print('pred', pred)
print('dist', dist)
# + [markdown] slideshow={"slide_type": "slide"}
# The algorithm terminates, but the results do not make much sense.
#
# For example, the distance to node 1 is -3, but in fact it is $-\infty$, as we can go round and round the negative cycle.
#
# The real problem is that we did not get any indication that the results are bogus because of negative cycles.
# + [markdown] slideshow={"slide_type": "slide"}
# To fix this problem, we will be adding to the queue a special, *sentinel* node.
#
# That is a fictitious node that does not exist in the graph.
#
# It will demarkate each set of neighbours that we add in the queue.
#
# Each time we meet it in the queue we will know that we have handled the complete set of neighbours of one node.
#
# This cannot happen more than $n$ times, where $n$ is the number of nodes; so if it does, we have reached a negative cycle.
# + slideshow={"slide_type": "slide"}
def bellman_ford_nc(g, s):
nodes = g.keys()
num_nodes = len(nodes)
# The sentinel is equal to the number of nodes,
# as the nodes start from 0.
sentinel = num_nodes
# Initialize array holding path lengths.
dist = [ MAX_INT ] * num_nodes
dist[s] = 0
# Initialize array holding node predecessors.
pred = [ -1 ] * num_nodes
q = collections.deque()
# We'll use a list to check whether something
# is already in the queue, so that we won't
# add it twice.
in_queue = [ False ] * num_nodes
in_queue[s] = True
# We start by putting the starting node and the
# sentinel in the queue.
q.append(s)
q.append(sentinel)
i = 1 # number of iterations
# Repeat as long as the queue contains more than one
# element (the sentinel) and we have not handled
# the neighbours of all nodes.
while len(q) != 1 and i < num_nodes:
u = q.popleft()
# If we have reached the sentinel, update the
# nodes count and put the sentinel back in the
# queue.
if u == sentinel:
i += 1
q.append(sentinel)
else:
in_queue[u] = False
# For every edge of the current node, check
# and update if needed.
for (v, w) in g[u]:
if dist[u] != MAX_INT and dist[v] > dist[u] + w:
dist[v] = dist[u] + w
pred[v] = u
# Add the node of the updated path in the queue
# if necessary.
if in_queue[v] == False:
q.append(v)
in_queue[v] = True
return (pred, dist, i < num_nodes)
# + [markdown] slideshow={"slide_type": "slide"}
# So now we are able to handle graphs with negative weights and detect cycles:
# + slideshow={"slide_type": "fragment"}
pred, dist, no_negative_cycle = bellman_ford_nc(g, 0)
print('pred', pred)
print('dist', dist)
print('no_negative_cycle', no_negative_cycle)
| content/notebooks/chapter_08.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (Data Science)
# language: python
# name: python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-east-1:081325390199:image/datascience-1.0
# ---
# # Yolov5 Pytorch 1.7 for Edge Devices with Amazon SageMaker
#
# Amazon SageMaker is a fully managed machine learning service. With SageMaker, data scientists and developers can quickly and easily build and train machine learning models, and then directly deploy them into a production-ready hosted environment. It provides an integrated Jupyter authoring notebook instance for easy access to your data sources for exploration and analysis, so you don't have to manage servers. It also provides common machine learning algorithms that are optimized to run efficiently against extremely large data in a distributed environment. With native support for bring-your-own-algorithms and frameworks, SageMaker offers flexible distributed training options that adjust to your specific workflows.
#
# SageMaker also offers capabilities to prepare models for deployment at the edge. [SageMaker Neo](https://docs.aws.amazon.com/sagemaker/latest/dg/neo.html) is a capability of Amazon SageMaker that enables machine learning models to train once and run anywhere in the cloud and at the edge and [Amazon SageMaker Edge Manager](https://docs.aws.amazon.com/sagemaker/latest/dg/edge.html) provides model management for edge devices so you can optimize, secure, monitor, and maintain machine learning models on fleets of edge devices such as smart cameras, robots, personal computers, and mobile devices.
#
#
# In this notebook we'll train a [**Yolov5**](https://github.com/ultralytics/yolov5) model on Pytorch using Amazon SageMaker to draw bounding boxes around images and then, compile and package it so that it can be deployed on an edge device(in this case, a [Jetson Xavier](https://developer.nvidia.com/jetpack-sdk-441-archive)).
#
# ### Pre-requisites
#
# Let us start with setting up the pre-requisites for this notebook. First, we will sagemaker and other related libs and then set up the role and buckets and some variables. Note that, we are also specifying the size of the image and also the model size taken as Yolov5s where s stand for small. Check out the [github doc of yolov5](https://github.com/ultralytics/yolov5) to understand how model sizes differ.
# +
import sagemaker
import numpy as np
import glob
import os
from sagemaker.pytorch.estimator import PyTorch
role = sagemaker.get_execution_role()
sagemaker_session=sagemaker.Session()
bucket_name = sagemaker_session.default_bucket()
img_size=640
model_type='s' # s=small,m=medium,l=large,x=xlarge, s6,m6,l6,x6
model_name=f"yolov5-{model_type}"
# -
# ### Download the official Yolov5 repo - version 5.0
#
# Now, we will download the official Yolov5 version from the [official repository](https://github.com/ultralytics/yolov5). We will place it in a local directory `yolov5`
if not os.path.isdir('yolov5'):
# !git clone https://github.com/ultralytics/yolov5 && cd yolov5 && git checkout v5.0
# !echo 'tensorboard' > yolov5/requirements.txt
# !echo 'seaborn' >> yolov5/requirements.txt
# ### Prepare a Python script that will be the entrypoint of the training process
#
# Now, we will create a training script to train the Yolov5 model. The training script will wrap the original training scripts and expose the parameters to SageMaker Estimator. The script accepts different arguments which will control the training process.
# +
# %%writefile yolov5/sagemaker_train.py
import sys
import subprocess
## We need to remove smdebug to avoid the Hook bug https://github.com/awslabs/sagemaker-debugger/issues/401
subprocess.check_call([sys.executable, "-m", "pip", "uninstall", "-y", "smdebug"])
import os
import yaml
import argparse
import torch
import shutil
import models
import torch.nn as nn
from utils.activations import Hardswish, SiLU
if __name__ == '__main__':
os.environ['WANDB_MODE'] = 'disabled' # disable weights and bias
parser = argparse.ArgumentParser()
parser.add_argument('--num-classes', type=int, default=80, help='Number of classes')
parser.add_argument('--img-size', type=int, default=640, help='Size of the image')
parser.add_argument('--epochs', type=int, default=1, help='Number of epochs')
parser.add_argument('--batch-size', type=int, default=16, help='Batch size')
parser.add_argument('--model-dir', type=str, default=os.environ["SM_MODEL_DIR"], help='Trained model dir')
parser.add_argument('--train', type=str, default=os.environ["SM_CHANNEL_TRAIN"], help='Train path')
parser.add_argument('--validation', type=str, default=os.environ["SM_CHANNEL_VALIDATION"], help='Validation path')
parser.add_argument('--model-type', type=str, choices=['s', 'm', 'l', 'x', 's6', 'm6', 'l6', 'x6'], default="s", help='Model type')
# hyperparameters
with open('data/hyp.scratch.yaml', 'r') as f:
hyperparams = yaml.load(f, Loader=yaml.FullLoader)
for k,v in hyperparams.items():
parser.add_argument(f"--{k.replace('_', '-')}", type=float, default=v)
args,unknown = parser.parse_known_args()
base_path=os.path.dirname(__file__)
project_dir = os.environ["SM_OUTPUT_DATA_DIR"]
# prepare the hyperparameters metadata
with open(os.path.join(base_path,'data', 'hyp.custom.yaml'), 'w' ) as y:
y.write(yaml.dump({h:vars(args)[h] for h in hyperparams.keys()}))
# prepare the training data metadata
with open(os.path.join(base_path,'data', 'custom.yaml'), 'w') as y:
y.write(yaml.dump({
'names': [f'class_{i}' for i in range(args.num_classes)],
'train': args.train,
'val': args.validation,
'nc': args.num_classes
}))
# run the training script
train_cmd = [
sys.executable, os.path.join(base_path,'train.py'),
"--data", "custom.yaml",
"--hyp", "hyp.custom.yaml",
"--weights", f"yolov5{args.model_type}.pt",
"--img", str(args.img_size),
"--batch", str(args.batch_size),
"--epochs", str(args.epochs),
"--project", project_dir
]
subprocess.check_call(train_cmd)
# run the export script
export_cmd = [
sys.executable, os.path.join(base_path,'models', 'export.py'),
"--weights", os.path.join(project_dir, 'exp', 'weights', 'best.pt'),
"--batch-size", "1",
"--img-size", str(args.img_size)
]
# tracing and saving the model
inp = torch.rand(1, 3, args.img_size, args.img_size).cpu()
model = torch.load(os.path.join(project_dir, 'exp', 'weights', 'best.pt'), map_location='cpu')['model']
model.eval().float()
model(inp)
# Update model
for k, m in model.named_modules():
if isinstance(m, models.common.Conv): # assign export-friendly activations
if isinstance(m.act, nn.Hardswish):
m.act = Hardswish()
elif isinstance(m.act, nn.SiLU):
m.act = SiLU()
model.model[-1].export = True
model_trace = torch.jit.trace(model, inp, strict=False)
model_trace.save(os.path.join(args.model_dir, 'model.pth'))
# -
# ### Preparing the dataset
#
# Here we'll download a sample dataset [coco128](https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip). We can also replace this step with any other dataset.
#
# Just take a look on the labels format and create your dataset scructure following the same standard (COCO).
import os
if not os.path.exists('coco128'):
# !wget -q https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
# !unzip -q coco128.zip && rm -f coco128.zip
print('BBoxes annotation')
print('class x_center y_center width height')
# !head coco128/labels/train2017/000000000009.txt
# ### Upload the dataset to S3
#
# Once the dataset has been downloaded locally, we'll upload the dataset to an S3 bucket created earlier. We are setting up the training and validation dataset s3 locations here.
prefix='data/coco128'
# !rm -f coco128/labels/train2017.cache
train_path = sagemaker_session.upload_data('coco128', key_prefix=f'{prefix}/train')
val_path = sagemaker_session.upload_data('coco128', key_prefix=f'{prefix}/val')
print(train_path, val_path)
# ### Prepare the SageMaker Estimator to train the model
#
# Now it's time to create an Estimater and train the model with the training script created in earlier step. We are using Pytorch estimator and supplying other arguments in the estimator. Note that we are supplying the `source_dir` so that sagemaker can pick up the training script and other related files from there. Once the estimator is ready, we start the training using the `.fit()` method.
estimator = PyTorch(
'sagemaker_train.py',
source_dir='yolov5',
framework_version='1.7',
role=role,
sagemaker_session=sagemaker_session,
instance_type='ml.p3.2xlarge',
instance_count=1,
py_version='py3',
hyperparameters={
'epochs': 2,
'batch-size': 16,
'lr0': 0.0001,
'num-classes': 80,
'img-size': img_size,
'model-type': model_type
}
)
estimator.fit({'train': train_path, 'validation': val_path})
# ### Compile your trained model for the edge device
#
# Once the model has been traied, we need to compile the model using SageMaker Neo. This step is needed to compile the model for the specific hardware on which this model will be deployed.
#
# In this notebook, we will compile a model for [Jetson Xavier Jetpack 4.4.1](https://developer.nvidia.com/jetpack-sdk-441-archive).
#
# In case, you want to compile for a different hardware platform, just change the parameters bellow to adjust the target to your own edge device. Also, note, that if you dont have GPU available on the hardware device, then you can comment the `Accelerator` key:value in the `OutputConfig`.
#
# The below cell also calls the `describe_compilation_job` API in a loop to wait for the compilation job to complete. In actual applications, it is advisable to setup a cloudwatch event which can notify OR execute the next steps once the compilation job is complete.
# +
import time
import boto3
sm_client = boto3.client('sagemaker')
compilation_job_name = f'{model_name}-pytorch-{int(time.time()*1000)}'
sm_client.create_compilation_job(
CompilationJobName=compilation_job_name,
RoleArn=role,
InputConfig={
'S3Uri': f'{estimator.output_path}{estimator.latest_training_job.name}/output/model.tar.gz',
'DataInputConfig': f'{{"input": [1,3,{img_size},{img_size}]}}',
'Framework': 'PYTORCH'
},
OutputConfig={
'S3OutputLocation': f's3://{sagemaker_session.default_bucket()}/{model_name}-pytorch/optimized/',
'TargetPlatform': {
'Os': 'LINUX',
'Arch': 'ARM64', # change this to X86_64 if you need
'Accelerator': 'NVIDIA' # comment this if you don't have an Nvidia GPU
},
# Comment or change the following line depending on your edge device
# Jetson Xavier: sm_72; Jetson Nano: sm_53
'CompilerOptions': '{"trt-ver": "7.1.3", "cuda-ver": "10.2", "gpu-code": "sm_72"}' # Jetpack 4.4.1
},
StoppingCondition={ 'MaxRuntimeInSeconds': 900 }
)
#check for the compilation job to complete
while True:
resp = sm_client.describe_compilation_job(CompilationJobName=compilation_job_name)
if resp['CompilationJobStatus'] in ['STARTING', 'INPROGRESS']:
print('Running...')
else:
print(resp['CompilationJobStatus'], compilation_job_name)
break
time.sleep(5)
# -
# ### Finally create a SageMaker Edge Manager packaging job
#
# Once the model has been compiled, it is time to create an edge manager packaging job. Packaging job take SageMaker Neoโcompiled models and make any changes necessary to deploy the model with the inference engine, Edge Manager agent.
#
# We need to provide the name used for the Neo compilation job, a name for the packaging job, a role ARN, a name for the model, a model version, and the Amazon S3 bucket URI for the output of the packaging job. Note that Edge Manager packaging job names are case-sensitive.
#
#
# The below cell also calls the `describe_edge_packaging_job` API in a loop to wait for the packaging job to complete. In actual applications, it is advisable to setup a cloudwatch event which can notify OR execute the next steps once the compilation job is complete.
import time
model_version = '1.0'
edge_packaging_job_name=f'{model_name}-pytorch-{int(time.time()*1000)}'
resp = sm_client.create_edge_packaging_job(
EdgePackagingJobName=edge_packaging_job_name,
CompilationJobName=compilation_job_name,
ModelName=model_name,
ModelVersion=model_version,
RoleArn=role,
OutputConfig={
'S3OutputLocation': f's3://{bucket_name}/{model_name}'
}
)
while True:
resp = sm_client.describe_edge_packaging_job(EdgePackagingJobName=edge_packaging_job_name)
if resp['EdgePackagingJobStatus'] in ['STARTING', 'INPROGRESS']:
print('Running...')
else:
print(resp['EdgePackagingJobStatus'], compilation_job_name)
break
time.sleep(5)
# ### Done !!
#
# And we are done with all the steps needed to prepare the model for deploying to edge. The model package is avaialble in S3 and can be taken from there to deploy it to edge device. Now you need to move over to your edge device and download and setup edge manager agent(runtime), model and other related artifacts on the device. Please check out the [documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/edge.html) for detailed steps.
| models/01_YoloV5/01_Pytorch/YoloV5_Pytorch.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# ## Data Wrangling: Clean, Transform, Merge, Reshape
from __future__ import division
from numpy.random import randn
import numpy as np
import os
import matplotlib.pyplot as plt
np.random.seed(12345)
plt.rc('figure', figsize=(10, 6))
from pandas import Series, DataFrame
import pandas
import pandas as pd
np.set_printoptions(precision=4, threshold=500)
pd.options.display.max_rows = 100
# %matplotlib inline
# ## Combining and merging data sets
# ### Database-style DataFrame merges
df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
'data1': range(7)})
df2 = DataFrame({'key': ['a', 'b', 'd'],
'data2': range(3)})
df1
df2
pd.merge(df1, df2)
pd.merge(df1, df2, on='key')
df3 = DataFrame({'lkey': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
'data1': range(7)})
df4 = DataFrame({'rkey': ['a', 'b', 'd'],
'data2': range(3)})
pd.merge(df3, df4, left_on='lkey', right_on='rkey')
pd.merge(df1, df2, how='outer')
df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
'data1': range(6)})
df2 = DataFrame({'key': ['a', 'b', 'a', 'b', 'd'],
'data2': range(5)})
df1
df2
pd.merge(df1, df2, on='key', how='left')
pd.merge(df1, df2, how='inner')
left = DataFrame({'key1': ['foo', 'foo', 'bar'],
'key2': ['one', 'two', 'one'],
'lval': [1, 2, 3]})
right = DataFrame({'key1': ['foo', 'foo', 'bar', 'bar'],
'key2': ['one', 'one', 'one', 'two'],
'rval': [4, 5, 6, 7]})
pd.merge(left, right, on=['key1', 'key2'], how='outer')
pd.merge(left, right, on='key1')
pd.merge(left, right, on='key1', suffixes=('_left', '_right'))
# ### Merging on index
left1 = DataFrame({'key': ['a', 'b', 'a', 'a', 'b', 'c'],
'value': range(6)})
right1 = DataFrame({'group_val': [3.5, 7]}, index=['a', 'b'])
left1
right1
pd.merge(left1, right1, left_on='key', right_index=True)
pd.merge(left1, right1, left_on='key', right_index=True, how='outer')
lefth = DataFrame({'key1': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'key2': [2000, 2001, 2002, 2001, 2002],
'data': np.arange(5.)})
righth = DataFrame(np.arange(12).reshape((6, 2)),
index=[['Nevada', 'Nevada', 'Ohio', 'Ohio', 'Ohio', 'Ohio'],
[2001, 2000, 2000, 2000, 2001, 2002]],
columns=['event1', 'event2'])
lefth
righth
pd.merge(lefth, righth, left_on=['key1', 'key2'], right_index=True)
pd.merge(lefth, righth, left_on=['key1', 'key2'],
right_index=True, how='outer')
left2 = DataFrame([[1., 2.], [3., 4.], [5., 6.]], index=['a', 'c', 'e'],
columns=['Ohio', 'Nevada'])
right2 = DataFrame([[7., 8.], [9., 10.], [11., 12.], [13, 14]],
index=['b', 'c', 'd', 'e'], columns=['Missouri', 'Alabama'])
left2
right2
pd.merge(left2, right2, how='outer', left_index=True, right_index=True)
left2.join(right2, how='outer')
left1.join(right1, on='key')
another = DataFrame([[7., 8.], [9., 10.], [11., 12.], [16., 17.]],
index=['a', 'c', 'e', 'f'], columns=['New York', 'Oregon'])
left2.join([right2, another])
left2.join([right2, another], how='outer')
# ### Concatenating along an axis
arr = np.arange(12).reshape((3, 4))
arr
np.concatenate([arr, arr], axis=1)
s1 = Series([0, 1], index=['a', 'b'])
s2 = Series([2, 3, 4], index=['c', 'd', 'e'])
s3 = Series([5, 6], index=['f', 'g'])
pd.concat([s1, s2, s3])
pd.concat([s1, s2, s3], axis=1)
s4 = pd.concat([s1 * 5, s3])
pd.concat([s1, s4], axis=1)
pd.concat([s1, s4], axis=1, join='inner')
pd.concat([s1, s4], axis=1, join_axes=[['a', 'c', 'b', 'e']])
result = pd.concat([s1, s1, s3], keys=['one', 'two', 'three'])
result
# Much more on the unstack function later
result.unstack()
pd.concat([s1, s2, s3], axis=1, keys=['one', 'two', 'three'])
df1 = DataFrame(np.arange(6).reshape(3, 2), index=['a', 'b', 'c'],
columns=['one', 'two'])
df2 = DataFrame(5 + np.arange(4).reshape(2, 2), index=['a', 'c'],
columns=['three', 'four'])
pd.concat([df1, df2], axis=1, keys=['level1', 'level2'])
pd.concat({'level1': df1, 'level2': df2}, axis=1)
pd.concat([df1, df2], axis=1, keys=['level1', 'level2'],
names=['upper', 'lower'])
df1 = DataFrame(np.random.randn(3, 4), columns=['a', 'b', 'c', 'd'])
df2 = DataFrame(np.random.randn(2, 3), columns=['b', 'd', 'a'])
df1
df2
pd.concat([df1, df2], ignore_index=True)
# ### Combining data with overlap
a = Series([np.nan, 2.5, np.nan, 3.5, 4.5, np.nan],
index=['f', 'e', 'd', 'c', 'b', 'a'])
b = Series(np.arange(len(a), dtype=np.float64),
index=['f', 'e', 'd', 'c', 'b', 'a'])
b[-1] = np.nan
a
b
np.where(pd.isnull(a), b, a)
b[:-2].combine_first(a[2:])
df1 = DataFrame({'a': [1., np.nan, 5., np.nan],
'b': [np.nan, 2., np.nan, 6.],
'c': range(2, 18, 4)})
df2 = DataFrame({'a': [5., 4., np.nan, 3., 7.],
'b': [np.nan, 3., 4., 6., 8.]})
df1.combine_first(df2)
# ## Reshaping and pivoting
# ### Reshaping with hierarchical indexing
data = DataFrame(np.arange(6).reshape((2, 3)),
index=pd.Index(['Ohio', 'Colorado'], name='state'),
columns=pd.Index(['one', 'two', 'three'], name='number'))
data
result = data.stack()
result
result.unstack()
result.unstack(0)
result.unstack('state')
s1 = Series([0, 1, 2, 3], index=['a', 'b', 'c', 'd'])
s2 = Series([4, 5, 6], index=['c', 'd', 'e'])
data2 = pd.concat([s1, s2], keys=['one', 'two'])
data2.unstack()
data2.unstack().stack()
data2.unstack().stack(dropna=False)
df = DataFrame({'left': result, 'right': result + 5},
columns=pd.Index(['left', 'right'], name='side'))
df
df.unstack('state')
df.unstack('state').stack('side')
# ### Pivoting "long" to "wide" format
# +
data = pd.read_csv('ch07/macrodata.csv')
periods = pd.PeriodIndex(year=data.year, quarter=data.quarter, name='date')
data = DataFrame(data.to_records(),
columns=pd.Index(['realgdp', 'infl', 'unemp'], name='item'),
index=periods.to_timestamp('D', 'end'))
ldata = data.stack().reset_index().rename(columns={0: 'value'})
wdata = ldata.pivot('date', 'item', 'value')
# -
ldata[:10]
pivoted = ldata.pivot('date', 'item', 'value')
pivoted.head()
ldata['value2'] = np.random.randn(len(ldata))
ldata[:10]
pivoted = ldata.pivot('date', 'item')
pivoted[:5]
pivoted['value'][:5]
unstacked = ldata.set_index(['date', 'item']).unstack('item')
unstacked[:7]
# ## Data transformation
# ### Removing duplicates
data = DataFrame({'k1': ['one'] * 3 + ['two'] * 4,
'k2': [1, 1, 2, 3, 3, 4, 4]})
data
data.duplicated()
data.drop_duplicates()
data['v1'] = range(7)
data.drop_duplicates(['k1'])
data.drop_duplicates(['k1', 'k2'], take_last=True)
# ### Transforming data using a function or mapping
data = DataFrame({'food': ['bacon', 'pulled pork', 'bacon', 'Pastrami',
'corned beef', 'Bacon', 'pastrami', 'honey ham',
'nova lox'],
'ounces': [4, 3, 12, 6, 7.5, 8, 3, 5, 6]})
data
meat_to_animal = {
'bacon': 'pig',
'pulled pork': 'pig',
'pastrami': 'cow',
'corned beef': 'cow',
'honey ham': 'pig',
'nova lox': 'salmon'
}
data['animal'] = data['food'].map(str.lower).map(meat_to_animal)
data
data['food'].map(lambda x: meat_to_animal[x.lower()])
# ### Replacing values
data = Series([1., -999., 2., -999., -1000., 3.])
data
data.replace(-999, np.nan)
data.replace([-999, -1000], np.nan)
data.replace([-999, -1000], [np.nan, 0])
data.replace({-999: np.nan, -1000: 0})
# ### Renaming axis indexes
data = DataFrame(np.arange(12).reshape((3, 4)),
index=['Ohio', 'Colorado', 'New York'],
columns=['one', 'two', 'three', 'four'])
data.index.map(str.upper)
data.index = data.index.map(str.upper)
data
data.rename(index=str.title, columns=str.upper)
data.rename(index={'OHIO': 'INDIANA'},
columns={'three': 'peekaboo'})
# Always returns a reference to a DataFrame
_ = data.rename(index={'OHIO': 'INDIANA'}, inplace=True)
data
# ### Discretization and binning
ages = [20, 22, 25, 27, 21, 23, 37, 31, 61, 45, 41, 32]
bins = [18, 25, 35, 60, 100]
cats = pd.cut(ages, bins)
cats
cats.labels
cats.levels
pd.value_counts(cats)
pd.cut(ages, [18, 26, 36, 61, 100], right=False)
group_names = ['Youth', 'YoungAdult', 'MiddleAged', 'Senior']
pd.cut(ages, bins, labels=group_names)
data = np.random.rand(20)
pd.cut(data, 4, precision=2)
data = np.random.randn(1000) # Normally distributed
cats = pd.qcut(data, 4) # Cut into quartiles
cats
pd.value_counts(cats)
pd.qcut(data, [0, 0.1, 0.5, 0.9, 1.])
# ### Detecting and filtering outliers
np.random.seed(12345)
data = DataFrame(np.random.randn(1000, 4))
data.describe()
col = data[3]
col[np.abs(col) > 3]
data[(np.abs(data) > 3).any(1)]
data[np.abs(data) > 3] = np.sign(data) * 3
data.describe()
# ### Permutation and random sampling
df = DataFrame(np.arange(5 * 4).reshape((5, 4)))
sampler = np.random.permutation(5)
sampler
df
df.take(sampler)
df.take(np.random.permutation(len(df))[:3])
bag = np.array([5, 7, -1, 6, 4])
sampler = np.random.randint(0, len(bag), size=10)
sampler
draws = bag.take(sampler)
draws
# ### Computing indicator / dummy variables
df = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
'data1': range(6)})
pd.get_dummies(df['key'])
dummies = pd.get_dummies(df['key'], prefix='key')
df_with_dummy = df[['data1']].join(dummies)
df_with_dummy
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table('ch02/movielens/movies.dat', sep='::', header=None,
names=mnames)
movies[:10]
genre_iter = (set(x.split('|')) for x in movies.genres)
genres = sorted(set.union(*genre_iter))
dummies = DataFrame(np.zeros((len(movies), len(genres))), columns=genres)
for i, gen in enumerate(movies.genres):
dummies.ix[i, gen.split('|')] = 1
movies_windic = movies.join(dummies.add_prefix('Genre_'))
movies_windic.ix[0]
np.random.seed(12345)
values = np.random.rand(10)
values
bins = [0, 0.2, 0.4, 0.6, 0.8, 1]
pd.get_dummies(pd.cut(values, bins))
# ## String manipulation
# ### String object methods
val = 'a,b, guido'
val.split(',')
pieces = [x.strip() for x in val.split(',')]
pieces
first, second, third = pieces
first + '::' + second + '::' + third
'::'.join(pieces)
'guido' in val
val.index(',')
val.find(':')
val.index(':')
val.count(',')
val.replace(',', '::')
val.replace(',', '')
# ### Regular expressions
import re
text = "foo bar\t baz \tqux"
re.split('\s+', text)
regex = re.compile('\s+')
regex.split(text)
regex.findall(text)
# +
text = """Dave <EMAIL>
Steve <EMAIL>
Rob <EMAIL>
Ryan <EMAIL>
"""
pattern = r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'
# re.IGNORECASE makes the regex case-insensitive
regex = re.compile(pattern, flags=re.IGNORECASE)
# -
regex.findall(text)
m = regex.search(text)
m
text[m.start():m.end()]
print(regex.match(text))
print(regex.sub('REDACTED', text))
pattern = r'([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})'
regex = re.compile(pattern, flags=re.IGNORECASE)
m = regex.match('<EMAIL>')
m.groups()
regex.findall(text)
print(regex.sub(r'Username: \1, Domain: \2, Suffix: \3', text))
regex = re.compile(r"""
(?P<username>[A-Z0-9._%+-]+)
@
(?P<domain>[A-Z0-9.-]+)
\.
(?P<suffix>[A-Z]{2,4})""", flags=re.IGNORECASE|re.VERBOSE)
m = regex.match('<EMAIL>')
m.groupdict()
# ### Vectorized string functions in pandas
data = {'Dave': '<EMAIL>', 'Steve': '<EMAIL>',
'Rob': '<EMAIL>', 'Wes': np.nan}
data = Series(data)
data
data.isnull()
data.str.contains('gmail')
pattern
data.str.findall(pattern, flags=re.IGNORECASE)
matches = data.str.match(pattern, flags=re.IGNORECASE)
matches
matches.str.get(1)
matches.str[0]
data.str[:5]
# ## Example: USDA Food Database
# + active=""
# {
# "id": 21441,
# "description": "KENTUCKY FRIED CHICKEN, Fried Chicken, EXTRA CRISPY,
# Wing, meat and skin with breading",
# "tags": ["KFC"],
# "manufacturer": "Kentucky Fried Chicken",
# "group": "Fast Foods",
# "portions": [
# {
# "amount": 1,
# "unit": "wing, with skin",
# "grams": 68.0
# },
#
# ...
# ],
# "nutrients": [
# {
# "value": 20.8,
# "units": "g",
# "description": "Protein",
# "group": "Composition"
# },
#
# ...
# ]
# }
# -
import json
db = json.load(open('ch07/foods-2011-10-03.json'))
len(db)
db[0].keys()
db[0]['nutrients'][0]
nutrients = DataFrame(db[0]['nutrients'])
nutrients[:7]
info_keys = ['description', 'group', 'id', 'manufacturer']
info = DataFrame(db, columns=info_keys)
info[:5]
info
pd.value_counts(info.group)[:10]
# +
nutrients = []
for rec in db:
fnuts = DataFrame(rec['nutrients'])
fnuts['id'] = rec['id']
nutrients.append(fnuts)
nutrients = pd.concat(nutrients, ignore_index=True)
# -
nutrients
nutrients.duplicated().sum()
nutrients = nutrients.drop_duplicates()
col_mapping = {'description' : 'food',
'group' : 'fgroup'}
info = info.rename(columns=col_mapping, copy=False)
info
col_mapping = {'description' : 'nutrient',
'group' : 'nutgroup'}
nutrients = nutrients.rename(columns=col_mapping, copy=False)
nutrients
ndata = pd.merge(nutrients, info, on='id', how='outer')
ndata
ndata.ix[30000]
result = ndata.groupby(['nutrient', 'fgroup'])['value'].quantile(0.5)
result['Zinc, Zn'].order().plot(kind='barh')
# +
by_nutrient = ndata.groupby(['nutgroup', 'nutrient'])
get_maximum = lambda x: x.xs(x.value.idxmax())
get_minimum = lambda x: x.xs(x.value.idxmin())
max_foods = by_nutrient.apply(get_maximum)[['value', 'food']]
# make the food a little smaller
max_foods.food = max_foods.food.str[:50]
# -
max_foods.ix['Amino Acids']['food']
| lecture04.visualization/ch07.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Aplicando Naive Bayes em dados
# ### Dados
# Uma das etapas mais importante รฉ a coleta de dados, neste exemplo irei utilizar alguns dados gerado manualmente, jรก que o Naive Bayes รฉ uma tรฉcnica que nรฃo precisa de muitos dados para obter bons resultados.
#
# O objetivo desse Notebook serรก a utilizaรงรฃo do algotimo Naive Bayes para tentar prever se com um determinado tempo e temperatura irรก ter jogo, usando treinamento supervisonado(dados conhecidos).
#
# Os dados abaixo sรฃo os climas, temperatura e qual foi o desfecho conhecido como rรณtulo dos dados: neste caso se "Sim" houve jogo, se "Nao" nรฃo houve jogaram.
# Salvei esses dados abaixo em formato CSV(dados separados por vรญrgulas).
# Salvei dentro da pasta dados/001.csv
print(open("dados/001.csv", "r").read())
# ### Tratamento dos dados
#
# O primeiro passo antes do treinamento รฉ a preparaรงรฃo dos dados, etapa onde chega ser muito trabalho e difรญcil, pois quando trabalhamos com uma grande quantidade de dados, รฉ normal, alguns dados terem um desvio de padrรฃo dos dados normal, ou atรฉ mesmo os dados serem muito no padrรฃo, afetando e muito os resultados do modelo. Normalmente grandes empresas, utilizam de funcionรกrios para tentar normalizar os dados de forma manual, contato isso demanda muito dinheiro e tempo, porรฉm alguns algoritmos possibilitam a normalizaรงรฃo dos dados automรกticamente, jรก que a gente estamos trabalhando com dados somente para questรฃo didรกtica, nรฃo teremos esse problema.
# #### Transformar os dados em nรบmeros
# +
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
import pandas
import numpy
#Funรงรฃo que codifica os rรณtulos para uma sequรชncia de nรบmeros baseados na quantidade. Supondo que exista os rรณtulos A, B, C neste exemplo a funรงao irรก atribuir valor A=1; B=2; C=3...
le = preprocessing.LabelEncoder()
#Lendo os dados usando a biblioteca pandas.
dados = pandas.read_csv("dados/001.csv")
#Transformando os valores em nรบmeros
clima_codificado = le.fit_transform(dados["clima"])
temperatura_codificado = le.fit_transform(dados["temperatura"])
jogou_codificado = le.fit_transform(dados["jogou"])
print(clima_codificado)
# -
# #### Aplicando o algoritmo Naive Bayes de fato
# +
#Rรณtudo dos dados
y = numpy.array(jogou_codificado)
#Separando os dados para treinamento e teste, Treinamento=75% e Teste=25%
lista = list(zip(clima_codificado, temperatura_codificado))
X = numpy.asarray(lista)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)
#Criando o modelo de Naive Bayes Gaussian
modelo = GaussianNB()
#Treinamendo o modelo usando os dados
modelo.fit(X=X_train, y=y_train)
#Testando a precisรฃo do nosso modelo
print("Precisรฃo de", str(accuracy_score(y_test, modelo.predict(X_test)))+"%")
# -
| lab/naive bayes.ipynb |
# This is a comment
cars
plot(cars)
| tests/notebooks/mirror/script_to_ipynb/simple_r_script.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Data format overview
# ## In this tutorial, we will overview evaluate the following data formats
# 1. avro (structured)
# 2. csv (semi-structured)
# 3. json (semi-structured)
# 4. orc (structured)
# 5. parquet (structured)
#
# ## We evaluate the data formats via:
# 1. Disk usage
# 2. Read/Write latency
# 3. Basic stats(min, max, count)
# 4. Random data lookup
# 5. Filtering/GroupBy(column-wise)
# 6. Distinct(row-wise)
# +
from pyspark.sql import SparkSession
spark = SparkSession \
.builder.master("local[2]") \
.appName("Evaluate data format") \
.config("spark.jars.packages", "org.apache.spark:spark-avro_2.12:3.0.1") \
.getOrCreate()
# -
# You need to replace the data_dir by the path of your local data dir
data_dir="/home/pliu/data_set/format_performence_test"
json_data_path=data_dir+"/netflix.json"
parquet_data_path=data_dir+"/netflix.parquet"
avro_data_path=data_dir+"/netflix.avro"
orc_data_path=data_dir+"/netflix.orc"
csv_data_path=data_dir+"/netflix.csv"
# # Some useful functions for evaluating data format
# ### The read function read the source data file and convert it to a spark data frame
# +
# file path for storing operation stats
data_format_op_stats_path="../tmp/op-stats.csv"
# file path for storing size stats
data_format_size_stats_path="../tmp/size-stats.csv"
def write_stats(line):
file1 = open(data_format_op_stats_path,"a")
file1.write(line+"\n")
# -
import time
def read(fmt):
start = time.time()
if fmt == "json":
sdf = spark.read.option("header", "true").json(json_data_path)
elif fmt == "csv":
sdf = spark.read.option("header", "true").csv(csv_data_path)
elif fmt == "avro":
sdf = spark.read.format("avro").load(avro_data_path)
elif fmt == "parquet":
sdf = spark.read.parquet(parquet_data_path)
elif fmt == "orc":
sdf = spark.read.orc(orc_data_path)
sdf.show(5,False)
stats="{},{},{}".format(fmt, "read", time.time() - start)
write_stats(stats)
print(stats)
return sdf
# ### The get_shape function prints the shape(e.g. row number and column number) of the data frame
def get_shape(df,fmt):
start = time.time()
row_num=df.count()
col_num=len(df.columns)
stats="{},{},{}".format(fmt, "get_shape", time.time() - start)
write_stats(stats)
print("The data frame has {} rows and {} columns".format(row_num,col_num))
print(stats)
# ### The stats function prints the min, max and numbers of a column of the data frame
def stats(df,fmt, field="rating"):
start = time.time()
max=df.agg({field: "max"})
min=df.agg({field: "min"})
count=df.agg({field: "count"})
min.show(5,False)
max.show(5,False)
count.show(5,False)
stats="{},{},{}".format(fmt, "stats", time.time() - start)
write_stats(stats)
print(stats)
# ### The random_batch function randomly select rows from the data frame. It can evaluate the ability of random data lookup
def random_batch(df,fmt):
start = time.time()
result=df.sample(False, 0.05).collect()
stats="{},{},{}".format(fmt, "random_batch", time.time() - start)
write_stats(stats)
print(stats)
# return result
# ### The distinct function count distinct rows of the data frame
def distinct(df,fmt):
start = time.time()
result = df.distinct().count()
stats="{},{},{}".format(fmt, "distinct", time.time() - start)
write_stats(stats)
print(stats)
return result
# ### The group_by function group and count the data frame by a specific column
def group_by(df,fmt):
start = time.time()
result=df.groupBy("rating").count()
result.show(5,False)
stats="{},{},{}".format(fmt, "group_by", time.time() - start)
write_stats(stats)
print(stats)
#return result
# ### The filtering function filter data by using a specific boolean condition
def filtering(df, fmt, date="2005-11-15"):
start = time.time()
result = df.filter(df.date > date).count()
stats="{},{},{}".format(fmt, "filtering", time.time() - start)
write_stats(stats)
print(stats)
return result
# ### The remove_space function removes space in string of a column to avoid filtering fail.
from pyspark.sql.functions import ltrim,rtrim,trim
def remove_space(df,col_name,position):
# remove left side space
if position =="l":
return df.withColumn("tmp",ltrim(col(col_name))).drop(col_name).withColumnRenamed("tmp", col_name)
# remove right side space
elif position =="r":
return df.withColumn("tmp",rtrim(col(col_name))).drop(col_name).withColumnRenamed("tmp", col_name)
# remove all side space
elif position =="a":
return df.withColumn("tmp",trim(col(col_name))).drop(col_name).withColumnRenamed("tmp", col_name)
def saveCSV(df,outputPath,fileName): Unit ={
df.coalesce(1).write.mode("overwrite")
.option("header","true")
.option("mapreduce.fileoutputcommitter.marksuccessfuljobs","false")
.option("encoding", "UTF-8")
.option("delimiter", ",")
.csv(outputPath+"/"+fileName)
}
# # 1. Gathering stats of each data format
# ## 1.1 Get CSV format evaluation stats
csv_df=read("csv")
csv_df.printSchema()
get_shape(csv_df,"csv")
# get min, max and row number of column rating
stats(csv_df,"csv",field="rating")
random_batch(csv_df,"csv")
distinct(csv_df,"csv")
group_by(csv_df,"csv")
filtering(csv_df,"csv")
# ## 1.2 Get Json format evaluation stats
json_df=read("json")
get_shape(json_df,"json")
# get min, max and row number of column rating
stats(json_df,"json",field="rating")
random_batch(json_df,"json")
distinct(json_df,"json")
group_by(json_df,"json")
filtering(json_df,"json")
# ## 1.3 Get Avro format evaluation stats
avro_df=read("avro")
get_shape(avro_df,"avro")
stats(avro_df,"avro",field="rating")
random_batch(avro_df,"avro")
distinct(avro_df,"avro")
group_by(avro_df,"avro")
filtering(avro_df,"avro")
# ## 1.4 Get Parquet format evaluation stats
parquet_df=read("parquet")
get_shape(parquet_df,"parquet")
random_batch(parquet_df,"parquet")
stats(parquet_df,"parquet",field="rating")
distinct(parquet_df,"parquet")
group_by(parquet_df,"parquet")
filtering(parquet_df,"parquet")
# # 1.5 Get ORC format evaluation stats
orc_df=read("orc")
get_shape(orc_df,"orc")
random_batch(orc_df,"orc")
stats(orc_df,"orc",field="rating")
distinct(orc_df,"orc")
group_by(orc_df,"orc")
filtering(orc_df,"orc")
# # 2. Compare the stats of different format
# ## 2.1 Disk Usage for different file format
# +
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from pyspark.sql.functions import col
from pyspark.sql.types import StructType, StructField, DoubleType,StringType,LongType
# define a schema
op_schema = StructType([
StructField("format", StringType(), True),
StructField("command", StringType(), True),
StructField("Latency", DoubleType(), True)])
size_schema = StructType([
StructField("format", StringType(), True),
StructField("size_kb", LongType(), True)])
# +
# read size stats file
rawSizeDf=spark.read.option("header", "true").csv(data_format_size_stats_path,schema=size_schema)
# generate a new column to make data humain readable
sizeDf=rawSizeDf.withColumn("size_mb",col("size_kb")/1024)
sizeDf.orderBy(col("size_kb").asc()).show(5)
# -
# convert spark df to pandas df
pd_size_df=sizeDf.toPandas()
# show the stats in a catplot
g_size = sns.catplot(
data=pd_size_df, kind="bar",
x="format", y="size_mb",
order=['orc','parquet','avro','csv','json'],
ci="sd", palette="dark", alpha=0.8, height=8
)
g_size.despine(left=False)
g_size.set_axis_labels("", "Size (kb) ")
g_size.set(ylim=(150, 1300))
# The main objective of any file is to store data. It is necessary to store large volumes of different data types with less spaces. Because the disk usage can cost you a lot of money.
#
# Based on the above graphe, we can have the obvious conclusion **do not use JSON or csv to store the raw data, and orc, parquet are the best solution for storing data.Now we want to know why?**
#
# Note that we used the default configuration for all format during the entire benchmark. So we do not specify any compression codec anywhere. As a result, we have the following table
#
# | format | size(mb) | compression |
# |--------|----------|-------------|
# | json | 1261.90 | None |
# | csv | 472.10 | None |
# | avro | 279.91 | None |
# | parquet| 198.01 | SNAPPY |
# | orc | 186.84 | ZLIB |
#
#
# 1. JSON uses the most space, because it has huge overhead on storing "schema". Each row must repeat the column name value, which are the same for all the rows (in our example, it represents 24058262 rows).
#
# 2. CSV only has one line header for storing column names, so it uses much less space than JSON
# 3. Avro does not do any compression, but it still uses less space than CSV. Because it saves raw data in binary. And the binary codec do a bit compression with storing int and long leveraging variable-length zig-zag coding.
# 4. Parque alson stores raw data in binary, and it does compress data. In spark, it uses SNAPPY as the default compressing codec.
# 5. Orc uses ZLIB as compression codec. As ZLIB can offer better compression ratio, so Orc use less space than Parquet. But Snappy is faster.
#
#
# You could argu that, you can gzip CSV and json which will reduce the disk usage. But, json and csv are not splitable after compression. As a result, we can not benefit from the parallel processing of Spark anymore. Thus, the advantage of avro, parquet and orc is obvious.
#
# Note that avro, parquet and orc supports many compression codec. Here we only benchmark the default setting of each format. So the difference of disk usage between these three are negligible.
#
#
# ## 2.2 Visualize the data processing latency for each format
# In this section, we will examine the latency of several the most common data processing operations to determine which format is more optimal in certain context. We will first examine the common operations one by one. At last, we will give you an overview and conclusion
# +
# read stats file
rawDf=spark.read.option("header", "false").csv(data_format_op_stats_path,schema=op_schema)
rawDf.show(5)
rawDf.count()
# -
# remove duplicated rows
tmpDf=rawDf.dropDuplicates(["format","command"])
# remove space in command column
statsDf=remove_space(tmpDf,"command","l")
statsDf.count()
# convert to pandas df
pd_df=statsDf.toPandas()
pd_df.shape
# ### 2.2.1 Read data
read_op_df=pd_df[pd_df.command.eq("read")]
read_op_df.head(5)
# show the stats in a catplot
g_read_op = sns.catplot(
data=read_op_df, kind="bar",
x="format", y="Latency",
order=['orc','parquet','avro','csv','json'],
ci="sd", palette="dark", alpha=0.8, height=8
)
g_read_op.despine(left=False)
g_read_op.set_axis_labels("", "Latency (seconds) ")
g_read_op.set(ylim=(0, 10))
# You could notice that the reading speed of orc, parquet and avro are much faster than csv and json. Because they store raw data in binary, which are optimized for performence.
# ### 2.2.2 Get basic stats such as min, max, column numbers
# The basic stats of a data set such as min, max, row numbers are the basic information we will gather when we exploring un data set. Below figure shows the latency of each format.
meta_op_df=pd_df.loc[(pd_df.command.eq("stats"))|(pd_df.command.eq("get_shape"))]
meta_op_df.head(5)
g_op_meta = sns.catplot(
data=meta_op_df, kind="bar",
x="format", y="Latency", hue="command",
order=['orc','parquet','avro','csv','json'],
ci="sd", palette="dark", alpha=0.8, height=10
)
g_op_meta.despine(left=False)
g_op_meta.set_axis_labels("", "Latency (seconds)")
g_op_meta.legend.set_title(" ")
# Orc and Parquet saves the min, max and row numbers as metadata. So the basic stats operations do not require the process of the entire dataset.
# ### 2.2.3 Random batch
# Random batch select randomly a subset of rows in a dataframe. If checks the performence of radom access operations of a data format. Unlike sequential access, random access requires more sophisticated optimization to avoid read unnecessary data.
random_op_df=pd_df[pd_df.command.eq("random_batch")]
random_op_df.head(5)
# show the stats in a catplot
g_random_op = sns.catplot(
data=random_op_df, kind="bar",
x="format", y="Latency",
order=['orc','parquet','avro','csv','json'],
ci="sd", palette="dark", alpha=0.8, height=8
)
g_random_op.despine(left=False)
g_random_op.set_axis_labels("", "Latency (seconds) ")
g_random_op.set(ylim=(0, 10))
# orc, parquet, and avro split data in small chunks, and each chunk has a header which contains the metadata of the data in this chunk. As a result, when a certain row is required, the reader will check first the metadata in the header, if the condition is not matched, this chunk will be omitted. And this will avoid to read all unnecessary data
# ### 2.2.4 column-wise operations (Filtering/GroupBy)
# Many operations such as filtering or groupBy only instrested in data of certain columns. If we can avoid reading unnecessary data. We can improve dramatiquely the performence. Below figure shows the latency of filtering and groupBy operations.
col_op_df=pd_df.loc[(pd_df.command.eq("group_by"))|(pd_df.command.eq("filtering"))]
col_op_df.head(5)
g_col_op = sns.catplot(
data=col_op_df, kind="bar",hue="command",
x="format", y="Latency",
order=['orc','parquet','avro','csv','json'],
ci="sd", palette="dark", alpha=0.8, height=8
)
g_col_op.despine(left=False)
g_col_op.set_axis_labels("", "Latency (seconds) ")
g_col_op.set(ylim=(0, 10))
# We can notice orc and parquet are much quicker than avro, csv, and json. Because orc, and parquet are columnar-based data formats, and avro, csv, and json are row-based data formats. We will discuss the difference between columnar-based and row-based in another tutorial.
# ### 2.2.5.row-wise operation (Distinct)
distinct_op_df=pd_df[pd_df.command.eq("distinct")]
distinct_op_df.head(5)
g_distinct_op = sns.catplot(
data=distinct_op_df, kind="bar",
x="format", y="Latency",
order=['orc','parquet','avro','csv','json'],
ci="sd", palette="dark", alpha=0.8, height=8
)
g_distinct_op.despine(left=False)
g_distinct_op.set_axis_labels("", "Latency (seconds) ")
g_distinct_op.set(ylim=(0, 50))
# # 3. Overview and Conclusion
g_op = sns.catplot(
data=pd_df, kind="bar",
x="format", y="Latency", hue="command",
order=['orc','parquet','avro','csv','json'],
ci="sd", palette="dark", alpha=0.8, height=10
)
g_op.despine(left=False)
g_op.set_axis_labels("", "Latency (seconds)")
g_op.legend.set_title(" ")
# The above figure shows the overall operation latency of all data formats. You can easily spot the most appropriate format for you based on your use case.
#
# ## 3.1 Some basic properties of data format
# We have seen the operation latency of all data formats. But there are other properties that may impact the choice of the data format. The below table shows some basic properties of data formats when we evaluate them.
#
#
# |Property |CSV |Json|Parquet|Avro|ORC|
# |---------|----|----|-------|----|---|
# |Human Readable|YES|YES|NO|NO|NO|
# |Compressable|YES|YES|YES|YES|YES|
# |Splittable|YES*|YES*|YES|YES|YES|
# |Complex data structure|NO|YES|YES|YES|YES|
# |Schema evolution|NO|NO|YES|YES|YES|
# |Columnar|NO|NO|YES|NO|YES|
#
# Note:
#
# 1. CSV is splittable when it is a raw, uncompressed file or using a splittable compression format such as BZIP2 or LZO (note: LZO needs to be indexed to be splittable!)
# 2. JSON has the same conditions about splittability when compressed as CSV with one extra difference. When โwholeFileโ option is set to true in Spark(re: SPARK-18352), JSON is NOT splittable.
# ## 3.2 Best data format for OLAP: Parquet vs Orc
# After the above analysis, we can say that Orc and Parquet are the best data formats for OLAP applications. They both support various compression algorithms which reduce significantly disk usage. They are both very efficient on columnar-oriented data analysis operations.
#
# Parquet has better support on nested data types than Orc. Orc loses compression ratio and analysis performance when data contains complex nested data types.
#
# Orc supports data update and ACID (atomicity, consistency, isolation, durability). Parquet does not, so if you want to update a Parquet file, you need to create a new one based on the old one.
#
# Parquet has better interoperability compare to Orc. Because almost all data analysis tools and framework supports parquet. Orc is only supported by Spark, Hive, Impala, MapReduce.
#
# ## 3.3 Conclusion
# If you are building a data lake, warehouse, or mart. We strongly recommend you use Parquet as the default data format for all your data.
# If you need to constantly update(write) your data, do not use columnar-based data formats such as ORC, Parquet.
# If you need to update your data schema, use Avro.
#
# As you know, when we load data from disk to memory via a tool (Spark, Hive, Pandas, etc), the tool needs to convert the file format(disk) to object models(memory). This conversion is very expensive, and each tool provides its own object models. To avoid the conversion of object models of different tools, a standard model has been proposed(i.e. Apache Arrow). Want to know more? Stay tuned for our next tutorial.
#
# # Stop the spark cluster
# stop sparksession
spark.sparkContext.stop()
# ### Check if the spark cluster is well closed. You should not see any python-spark pods
# ! kubectl get pods
| notebooks/data_format_overview_local.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from pandas_profiling import ProfileReport
# %matplotlib inline
# +
df1=pd.read_csv("C:/Users/alraw/Documents/COSC301/survey.csv")
df1
# -
| analysis/mohamed/milestone1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:miniconda3-cesm-fsspec-tutorial]
# language: python
# name: conda-env-miniconda3-cesm-fsspec-tutorial-py
# ---
# # Build the data catalog
from ecgtools import Builder
from ecgtools.parsers.cesm import parse_cesm_timeseries
# ## Setup the Builder
b = Builder(
# Where to look for model output
"/glade/campaign/cesm/development/wawg/WACCM6-TSMLT-GEO/SAI1/",
exclude_patterns=["*/hist/*", "*/rest/*"],
njobs=-1,
)
b= b.build(parse_cesm_timeseries)
b.df
# ## Save the Catalog
b.save(
'/glade/work/mgrover/intake-esm-catalogs/silver-linings-test.csv',
# Column name including filepath
path_column_name='path',
# Column name including variables
variable_column_name='variable',
# Data file format - could be netcdf or zarr (in this case, netcdf)
data_format="netcdf",
# Which attributes to groupby when reading in variables using intake-esm
groupby_attrs=["component", "stream", "case"],
# Aggregations which are fed into xarray when reading in data using intake
aggregations=[
{
"type": "join_existing",
"attribute_name": "time_range",
"options": {"dim": "time", "coords": "minimal", "compat": "override"},
}
],
)
| 00_Create_Catalog.ipynb |