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: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/phoughton/ensign/blob/master/ensign_trainer.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="CZqmW4bNiNtI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 306} outputId="b5ccad8e-dae5-4016-af27-c1d6a258bf90" # !pip install -Uqq fastbook import fastbook fastbook.setup_book() from fastbook import * # + id="7T16L3BYPu6C" colab_type="code" colab={} key = 'XXX' # + id="x9IvDGPWPxto" colab_type="code" colab={} image_types = 'jolly rogger','british','french', 'irish', 'netherlands', 'deutschland','scottish' path = Path('flags') # + id="WIg0P1srP2fs" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 470} outputId="b724ff18-b824-4701-ed60-20ce5815a2b6" if not path.exists(): path.mkdir() for o in image_types: dest = (path/o.replace(' ', '_')) dest.mkdir(exist_ok=True) results = search_images_bing(key, f'{o} flag') download_images(dest, urls=results.attrgot('content_url')) # + id="_m_HwlCtP7-_" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="bb3547a9-3597-4c90-ff90-749ab407af94" fns = get_image_files(path) fns # + id="RyFCU_M7P_IT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="0b8a9088-3299-453b-90a3-6f52bf3c56b2" failed = verify_images(fns) failed # + id="6tstDVQ7QAGi" colab_type="code" colab={} failed.map(Path.unlink); # + id="WrzeyKchQHLn" colab_type="code" colab={} flags = DataBlock( blocks=(ImageBlock, CategoryBlock), get_items=get_image_files, splitter=RandomSplitter(valid_pct=0.2, seed=42), get_y=parent_label, item_tfms=Resize(128)) dls = flags.dataloaders(path) # + id="JkpNGvH0QdRy" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 226} outputId="f4702a18-a771-4e4c-93ee-ad3d1cec07a5" dls.valid.show_batch(max_n=4, nrows=1) # + id="F77w7TJ4QoPp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 963, "referenced_widgets": ["6e9301334cae49e080a0c385488eeb6e", "<KEY>", "0645b3332906468f98a5be7f154ba4db", "<KEY>", "887cf17c699c4eb2ad20c7083a7989af", "177f86b032b443f49a011141da68d9b3", "<KEY>", "2b532316aa4042c0a259f850f3c8f929"]} outputId="3d3a9881-630b-4393-99e6-fcb925c96a4a" learn = cnn_learner(dls, resnet18, metrics=error_rate) learn.fine_tune(4) # + id="NpavMephQxQ6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 378} outputId="91a71fbc-46be-496b-e05a-81c554208d06" interp = ClassificationInterpretation.from_learner(learn) interp.plot_confusion_matrix() # + id="_IdvCAtCQ7Bj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="f341e271-8c0f-4115-dd89-2595857eb67a" learn.export('flag_export.pkl') path = Path() path.ls(file_exts='.pkl')
ensign_trainer.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 numpy as np import pandas as pd from glob import glob from skimage.io import imread import seaborn as sns import matplotlib.pyplot as plt # %matplotlib inline # - base_sub = pd.read_csv(os.path.join('..', 'submission', 'sub-dsbowl2018-0.354.csv')) gr_sub = pd.read_csv(os.path.join('..', 'submission', 'submission-GR.csv')) gr_sub_part1 = gr_sub[:len(gr_sub) - len(gr_sub['ImageId'].unique())] gr_image_ids = set(gr_sub_part1['ImageId'].unique()) base_sub['GR'] = base_sub['ImageId'].map(lambda x: x in gr_image_ids) other_sub = base_sub[base_sub['GR'] == False] print(len(other_sub['ImageId'].unique()), len(gr_image_ids), len(base_sub['ImageId'].unique())) print(len(other_sub['ImageId'].unique()) + len(gr_image_ids) == len(base_sub['ImageId'].unique())) print(len(other_sub)) del other_sub['GR'] new_sub = gr_sub_part1.append(other_sub) new_sub.to_csv('../output/merge-GR-base354.csv', index = False) len(base_sub), len(gr_sub), len(gr_sub_part1), len(new_sub) 0.419*65/53 (0.450-0.419)*65/12 dic_image_ids = {} dic_image_ids['good_image_ids'] = list(gr_image_ids) dic_image_ids['bad_image_ids'] = other_sub['ImageId'].unique() import pickle pickle.dump(dic_image_ids, open('../output/dic_image_ids.p', 'wb'))
merge-from-GR.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/project-ccap/project-ccap.github.io/blob/master/2021cnps/notebooks/2021_0812cnps_tlpa_tSNE_plot.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="HCd-RXCh96wZ" # # 2021年8月版 tSNE を用いた tlpa 刺激語の plot # # - date: 2021_0812 # - filename: 2021_0812cnps_tSNE_demo.pynb # - author: 浅川伸一 # - 概要: # + id="VZCgA0Rdw_Nx" #グラフ中に日本語を使うために必要なライブラリをインストール # !pip install japanize_matplotlib # + id="typUIMFS0x3t" #訓練済 word2vec ファイルの取得 通信環境によっては時間がかかります # #!wget --no-check-certificate --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1B9HGhLZOja4Xku5c_d-kMhCXn1LBZgDb' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1B9HGhLZOja4Xku5c_d-kMhCXn1LBZgDb" -O 2021_05jawiki_hid128_win10_neg10_cbow.bin.gz && rm -rf /tmp/cookies.txt # #!wget --no-check-certificate --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1OWmFOVRC6amCxsomcRwdA6ILAA5s4y4M' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1OWmFOVRC6amCxsomcRwdA6ILAA5s4y4M" -O 2021_05jawiki_hid128_win10_neg10_sgns.bin.gz && rm -rf /tmp/cookies.txt # !wget --no-check-certificate --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1JTkU5SUBU2GkURCYeHkAWYs_Zlbqob0s' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1JTkU5SUBU2GkURCYeHkAWYs_Zlbqob0s" -O 2021_05jawiki_hid200_win20_neg20_cbow.bin.gz && rm -rf /tmp/cookies.txt # #!wget --no-check-certificate --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1VPL2Mr9JgWHik9HjRmcADoxXIdrQ3ds7' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1VPL2Mr9JgWHik9HjRmcADoxXIdrQ3ds7" -O 2021_05jawiki_hid200_win20_neg20_sgns.bin.gz && rm -rf /tmp/cookies.txt # + id="Z6q-E4UPzKn_" # %time #直上のセルで取得したファイルの読み込み import numpy as np import os import sys # word2vec データ処理のため gensim を使う from gensim.models import KeyedVectors from gensim.models import Word2Vec # word2vec データの読み込み # 訓練済 word2vec,訓練データは wikipedia 全文 読み込みに時間がかかります... w2v_base = '.' # ファイルの所在に応じて変更してください #w2v_file='2021_05jawiki_hid128_win10_neg10_cbow.bin.gz' #w2v_file='2021_05jawiki_hid128_win10_neg10_sgns.bin.gz' w2v_file='2021_05jawiki_hid200_win20_neg20_cbow.bin.gz' #w2v_file='2021_05jawiki_hid200_win20_neg20_sgns.bin.gz' w2v_file = os.path.join(w2v_base, w2v_file) w2v = KeyedVectors.load_word2vec_format(w2v_file, encoding='utf-8', unicode_errors='replace', binary=True) # + id="ykY_Ldb5r8Rr" # TLPA のデータ tlpa_labels = ['バス', '緑', '桜', 'のり巻き', '五重塔', 'コップ', 'ごぼう', '土踏まず', '風呂', 'ヒトデ', 'ハム', '兎', 'ロープウエイ', '学校', 'ちりとり', '縁側', '歯', 'ネギ', 'あじさい', '灰色', '天井', '鍵', '肌色', 'ワニ', '電車', '顔', '松', 'ガードレール', '柿', 'ちまき', '信号', 'すすき', 'じょうろ', 'コンセント', '天ぷら', '中指', 'ヨット', 'ピンク', 'ふくろう', 'みかん', '柱', '角砂糖', '犬', 'かご', 'バラ', '鍋', 'まぶた', 'くるみ', '黒', 'デパート', 'カーネーション', '城', '蟻', '豆腐', 'ドライバー', '紺', '階段', '戦車', '人参', '背中', '鏡餅', 'スプーン', '朝顔', '金', '足', 'ふすま', '蛇', 'レモン', '公園', '乳母車', '床', '藤', 'ピンセット', 'トラック', '苺', '黄土色', '銭湯', 'ナマズ', 'そば', 'お腹', 'オレンジ', 'バター', '工場', '鳩', '電卓', '喉仏', 'チューリップ', '白菜', 'トラクター', '廊下', 'パトカー', '押入れ', '鉛筆', '目尻', '芋', '吊り橋', '赤', 'かき氷', '豹', 'サボテン', 'ピラミッド', 'サイ', '目', 'ひまわり', 'はたき', '刺し身', '玄関', 'トマト', '黄緑', '三輪車', '鶏', 'つむじ', 'アスパラガス', 'ドア', '銀色', 'すりこ木', 'ウイスキー', '梅', 'タクシー', '動物園', '床の間', '焦げ茶', 'ぶどう', '飴', '毛虫', 'アイロン', '寺', 'そり', 'ひょうたん', '首', '消しゴム', '頬', 'いちょう', '駅', 'ギョウザ', '牛', 'びわ', '飛行機', '畳', '白', '竹', 'ペリカン', '紫', '手すり', '口', '大根', '風車', '鋏', '潜水艦', 'ステーキ', 'マッチ', '二階', '落花生', '御飯', '自転車', '歩道橋', '鯨', '茶色', '菖蒲', 'ふくらはぎ', '桃', '鯛焼き', '道路', '靴べら', '水色', '壁', 'たんぽぽ', 'いかだ', '山羊', '鼻', '海老', '台所', 'オートバイ', 'かぶ', '柳', 'しゃもじ', 'まんじゅう', 'かかと', '薄紫', '家', 'おせち料理', '青', '傘', 'つくし', 'りんご', '馬車', '線路', 'タツノオトシゴ', '耳', '便所', '蓮根', '猫', '黄色', 'へそ', '街灯', '障子', '酒', '船', '安全ピン', 'もみじ'] tlpa_fam = ['高', '高', '高', '低', '低', '高', '低', '低', '高', '低', '高', '高', '低', '高', '低', '低', '高', '高', '低', '低', '高', '高', '低', '低', '高', '高', '高', '低', '低', '低', '高', '低', '低', '低', '高', '低', '高', '高', '低', '高', '低', '低', '高', '低', '高', '高', '低', '低', '高', '高', '低', '低', '高', '高', '低', '低', '高', '低', '高', '高', '低', '高', '高', '低', '高', '低', '高', '低', '高', '低', '高', '低', '低', '高', '高', '低', '低', '低', '高', '高', '高', '高', '高', '高', '低', '低', '高', '低', '低', '低', '高', '高', '高', '低', '高', '低', '高', '低', '低', '低', '低', '低', '高', '高', '低', '高', '高', '高', '低', '低', '高', '低', '低', '高', '低', '低', '低', '高', '高', '高', '低', '低', '高', '高', '低', '高', '高', '低', '低', '高', '高', '低', '低', '高', '低', '高', '低', '高', '低', '高', '高', '低', '高', '低', '高', '高', '低', '高', '低', '低', '高', '低', '低', '高', '高', '低', '高', '高', '低', '低', '高', '低', '高', '低', '低', '高', '高', '低', '低', '高', '高', '高', '高', '低', '低', '低', '高', '低', '低', '高', '低', '高', '高', '低', '高', '低', '低', '低', '高', '高', '低', '高', '高', '低', '低', '低', '高', '高', '低', '高'] tlpa_cat = ['乗り物', '色', '植物', '加工食品', '建造物', '道具', '野菜果物', '身体部位', '屋内部位', '動物', '加工食品', '動物', '乗り物', '建造物', '道具', '屋内部位', '身体部位', '野菜果物', '植物', '色', '屋内部位', '道具', '色', '動物', '乗り物', '身体部位', '植物', '建造物', '野菜果物', '加工食品', '建造物', '植物', '道具', '屋内部位', '加工食品', '身体部位', '乗り物', '色', '動物', '野菜果物', '屋内部位', '加工食品', '動物', '乗り物', '植物', '道具', '身体部位', '野菜果物', '色', '建造物', '植物', '建造物', '動物', '加工食品', '道具', '色', '屋内部位', '乗り物', '野菜果物', '身体部位', '加工食品', '道具', '植物', '色', '身体部位', '屋内部位', '動物', '野菜果物', '建造物', '乗り物', '屋内部位', '植物', '道具', '乗り物', '野菜果物', '色', '建造物', '動物', '加工食品', '身体部位', '色', '加工食品', '建造物', '動物', '道具', '身体部位', '植物', '野菜果物', '乗り物', '屋内部位', '乗り物', '屋内部位', '道具', '身体部位', '野菜果物', '建造物', '色', '加工食品', '動物', '植物', '建造物', '動物', '身体部位', '植物', '道具', '加工食品', '屋内部位', '野菜果物', '色', '乗り物', '動物', '身体部位', '野菜果物', '屋内部位', '色', '道具', '加工食品', '植物', '乗り物', '建造物', '屋内部位', '色', '野菜果物', '加工食品', '動物', '道具', '建造物', '乗り物', '植物', '身体部位', '道具', '身体部位', '植物', '建造物', '加工食品', '動物', '野菜果物', '乗り物', '屋内部位', '色', '植物', '動物', '色', '屋内部位', '身体部位', '野菜果物', '建造物', '道具', '乗り物', '加工食品', '道具', '屋内部位', '野菜果物', '加工食品', '乗り物', '建造物', '動物', '色', '植物', '身体部位', '野菜果物', '加工食品', '建造物', '道具', '色', '屋内部位', '植物', '乗り物', '動物', '身体部位', '動物', '屋内部位', '乗り物', '野菜果物', '植物', '道具', '加工食品', '身体部位', '色', '建造物', '加工食品', '色', '道具', '植物', '野菜果物', '乗り物', '建造物', '動物', '身体部位', '屋内部位', '野菜果物', '動物', '色', '身体部位', '建造物', '屋内部位', '加工食品', '乗り物', '道具', '植物'] X = np.array([w2v[word] for word in tlpa_labels], dtype=np.float) # + id="bJQPUaWW6uhK" import matplotlib.pyplot as plt import japanize_matplotlib # %matplotlib inline #from mpl_toolkits.mplot3d import Axes3D import pandas as pd import seaborn as sns from sklearn.decomposition import PCA from sklearn.manifold import TSNE # + id="pJ8whPLgsOfA" tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=500) tsne_results = tsne.fit_transform(X) # + id="8PkDz506s9EC" df = pd.DataFrame(tsne_results, columns=["tSNE1", "tSNE2"]) df["fam"] = tlpa_fam df["cat"] = tlpa_cat plt.figure(figsize=(16, 16)) ax = sns.scatterplot(x="tSNE1", y="tSNE2", data=df, hue="cat", size="fam", sizes=(100,300)) # , legend="full") #T:乗り物, C:色, P:植物, F:加工食品, E:建造物, D:道具, V:野菜果物,B:身体部位, I:屋内部位, A:動物 # + colab={"base_uri": "https://localhost:8080/", "height": 17} id="ZxwtvtG8zhPk" outputId="a7aa331e-a582-4ae3-a61b-876141440c34" # 結果をローカルドライブに保存する場合には以下を実行 from google.colab import files fig_name = 'tlpa_tsne_plot.pdf' fig = ax.get_figure() fig.savefig(fig_name) files.download(fig_name) # + id="T-inarVm3ded" def draw_tSNE_plot(tsne_result, cats=list(set(tlpa_cat)), fontsize=16, save_figname=None): cols = [cats.index(c) for c in tlpa_cat] plt.figure(figsize=(16,16)) plt.scatter(tsne_results[:,0], tsne_results[:,1], 120, cols) #, tlpa_labels) for i,label in enumerate(tlpa_labels): plt.annotate(label, (tsne_results[i,0],tsne_results[i,1]), fontsize=fontsize) if save_figname != None: plt.savefig(save_figname) plt.show() # + id="n0xURz0S4KEr" draw_tSNE_plot(tsne_results) # + id="WV5wu6qJ39Kz" # 以下のコードは上記実行とは関係ありません。オリジナルのソースコードを掲載しているだけです import sys import numpy as np """ - source: https://lvdmaaten.github.io/tsne/ - オリジナルの tSNE python 実装を python 3 系で呼び出せるように変更したバージョン - date: 2021_0510 - author: 浅川伸一 ```python import numpy as np import tsne X = np.random.random(100, 30) result = tsne.tsne(X) ``` """ # tsne.py # # Implementation of t-SNE in Python. The implementation was tested on Python 2.7.10, and it requires a working # installation of NumPy. The implementation comes with an example on the MNIST dataset. In order to plot the # results of this example, a working installation of matplotlib is required. # # The example can be run by executing: `ipython tsne.py` # # # Created by <NAME> on 20-12-08. # Copyright (c) 2008 Tilburg University. All rights reserved. #import numpy as Math #import pylab as Plot def Hbeta(D = np.array([]), beta = 1.0): """Compute the perplexity and the P-row for a specific value of the precision of a Gaussian distribution.""" # Compute P-row and corresponding perplexity P = np.exp(-D.copy() * beta) sumP = sum(P) if sum(P) > 1e-12 else 1e-12 # to avoid division by zero ここだけ加えた。直下行が division by zero error にならないように H = np.log(sumP) + beta * np.sum(D * P) / sumP P = P / sumP return H, P def x2p(X = np.array([]), tol=1e-5, perplexity=30.0): """Performs a binary search to get P-values in such a way that each conditional Gaussian has the same perplexity.""" # Initialize some variables print("Computing pairwise distances...") (n, d) = X.shape sum_X = np.sum(np.square(X), 1) D = np.add(np.add(-2 * np.dot(X, X.T), sum_X).T, sum_X) P = np.zeros((n, n)) beta = np.ones((n, 1)) logU = np.log(perplexity) # Loop over all datapoints for i in range(n): # Print progress if i % 500 == 0: print("Computing P-values for point ", i, " of ", n, "...") # Compute the Gaussian kernel and entropy for the current precision betamin = -np.inf betamax = np.inf Di = D[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))] (H, thisP) = Hbeta(Di, beta[i]) # Evaluate whether the perplexity is within tolerance Hdiff = H - logU tries = 0 while np.abs(Hdiff) > tol and tries < 50: # If not, increase or decrease precision if Hdiff > 0: betamin = beta[i].copy() if betamax == np.inf or betamax == -np.inf: beta[i] = beta[i] * 2 else: beta[i] = (beta[i] + betamax) / 2; else: betamax = beta[i].copy() if betamin == np.inf or betamin == -np.inf: beta[i] = beta[i] / 2 else: beta[i] = (beta[i] + betamin) / 2; # Recompute the values (H, thisP) = Hbeta(Di, beta[i]) Hdiff = H - logU tries = tries + 1 # Set the final row of P P[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))] = thisP # Return final P-matrix sigma = np.mean(np.sqrt(1 / beta)) print(f'Mean value of sigma: {sigma:.3f}') return P def pca(X = np.array([]), no_dims = 50): """Runs PCA on the NxD array X in order to reduce its dimensionality to no_dims dimensions.""" print("Preprocessing the data using PCA...") (n, d) = X.shape X = X - np.tile(np.mean(X, 0), (n, 1)) (l, M) = np.linalg.eig(np.dot(X.T, X)) Y = np.dot(X, M[:,0:no_dims]) return Y def tsne(X = np.array([]), no_dims=2, initial_dims=50, perplexity=30.0): """ Runs t-SNE on the dataset in the NxD array X to reduce its dimensionality to no_dims dimensions. The syntaxis of the function is Y = tsne.tsne(X, no_dims, perplexity), where X is an NxD NumPy array. """ # Check inputs if isinstance(no_dims, float): print("Error: array X should have type float.") return -1 if round(no_dims) != no_dims: print("Error: number of dimensions should be an integer.") return -1 # Initialize variables X = pca(X, initial_dims).real (n, d) = X.shape max_iter = 1000 initial_momentum = 0.5 final_momentum = 0.8 eta = 500 min_gain = 0.01 Y = np.random.randn(n, no_dims) dY = np.zeros((n, no_dims)) iY = np.zeros((n, no_dims)) gains = np.ones((n, no_dims)) # Compute P-values P = x2p(X, 1e-5, perplexity) P = P + np.transpose(P) P = P / np.sum(P) P = P * 4 # early exaggeration P = np.maximum(P, 1e-12) #P = np.maximum(P, 1e-5) interval = int(max_iter >> 2) # Run iterations for iter in range(max_iter): # Compute pairwise affinities sum_Y = np.sum(np.square(Y), 1) num = 1 / (1 + np.add(np.add(-2 * np.dot(Y, Y.T), sum_Y).T, sum_Y)) num[range(n), range(n)] = 0 Q = num / np.sum(num) Q = np.maximum(Q, 1e-12) #Q = np.maximum(Q, 1e-5) # Compute gradient PQ = P - Q; for i in range(n): dY[i,:] = np.sum(np.tile(PQ[:,i] * num[:,i], (no_dims, 1)).T * (Y[i,:] - Y), 0) # Perform the update if iter < 20: momentum = initial_momentum else: momentum = final_momentum gains = (gains + 0.2) * ((dY > 0) != (iY > 0)) + (gains * 0.8) * ((dY > 0) == (iY > 0)) gains[gains < min_gain] = min_gain iY = momentum * iY - eta * (gains * dY) Y = Y + iY Y = Y - np.tile(np.mean(Y, 0), (n, 1)) # Compute current value of cost function #if (iter + 1) % 10 == 0: if (iter + 1) % interval == 0: C = np.sum(P * np.log(P / Q)) print(f"Iteration {(iter + 1):<5d}: error is {C:.3f}") # Stop lying about P-values if iter == 100: P = P / 4; # Return solution return Y; # if __name__ == "__main__": # print("Run Y = tsne.tsne(X, no_dims, perplexity) to perform t-SNE on your dataset.") # print("Running example on 2,500 MNIST digits...") # X = np.loadtxt("mnist2500_X.txt"); # labels = np.loadtxt("mnist2500_labels.txt"); # Y = tsne(X, 2, 50, 20.0); # Plot.scatter(Y[:,0], Y[:,1], 20, labels); # Plot.show();
2021cnps/notebooks/2021_0812cnps_tlpa_tSNE_plot.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 (''.venv'': venv)' # name: pythonjvsc74a57bd071f3d0049937cc818ce2f9b352ba946595cd1ac61856b9bde9007f94463dcc87 # --- import cv2 import numpy as np # + img_path = '/home/erik/Riksarkivet/Projects/handwritten-text-recognition/data/1930_census/Gotland/cyclegan/cyclegan_datasets/only_overwritten/testA/B0001097_00007_31.jpg' img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) u, i = np.unique(np.array(img).flatten(), return_inverse=True) bg = int(u[np.argmax(np.bincount(i))]) wt, ht, _ = (1024, 128, 1) h, w = np.asarray(img).shape f = max((w / wt), (h / ht)) new_size = (max(min(wt, int(w / f)), 1), max(min(ht, int(h / f)), 1)) img = cv2.resize(img, new_size) target = np.ones([ht, wt], dtype=np.uint8) * bg target[0:new_size[1], 0:new_size[0]] = img cv2.imwrite('/home/erik/Riksarkivet/Projects/handwritten-text-recognition/src/notebooks/test.jpg', target) # + from matplotlib import pyplot as plt plt.imshow(cv2.cvtColor(target, cv2.COLOR_BGR2RGB)) # -
src/notebooks/test_resize.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # + [markdown] nbsphinx="hidden" # This notebook is part of the $\omega radlib$ documentation: https://docs.wradlib.org. # # Copyright (c) $\omega radlib$ developers. # Distributed under the MIT License. See LICENSE.txt for more info. # - # # RADOLAN Radar Network # In this chapter the RW-product is shown in WGS84 and the RADOLAN [Polar Stereographic Projection](radolan_grid.ipynb#Polar-Stereographic-Projection). All for the compositing process used radars are extracted from the metadata and plotted with their respective maximum range rings and location information. # + import datetime import wradlib as wrl import matplotlib.pyplot as pl import matplotlib as mpl import warnings from IPython import get_ipython from wetterdienst.provider.dwd.radar import DwdRadarParameter, DwdRadarValues from wetterdienst.provider.dwd.radar.api import DwdRadarSites warnings.filterwarnings('ignore') try: get_ipython().magic("matplotlib inline") except: pl.ion() import numpy as np from osgeo import osr # load radolan data start_date = datetime.datetime.utcnow() radar_data = DwdRadarValues( parameter=DwdRadarParameter.RADOLAN_CDC.RW_REFLECTIVITY, start_date=start_date - datetime.timedelta(hours=2), end_date=start_date, ) results = radar_data.query() rwdata, rwattrs = wrl.io.read_radolan_composite(next(results).data) # - # print the available attributes print("RW Attributes:", rwattrs) # + # mask data sec = rwattrs['secondary'] rwdata.flat[sec] = -9999 rwdata = np.ma.masked_equal(rwdata, -9999) # create radolan projection object proj_stereo = wrl.georef.create_osr("dwd-radolan") # create wgs84 projection object proj_wgs = osr.SpatialReference() proj_wgs.ImportFromEPSG(4326) # get radolan grid radolan_grid_xy = wrl.georef.get_radolan_grid(900, 900) x1 = radolan_grid_xy[:, :, 0] y1 = radolan_grid_xy[:, :, 1] # convert to lonlat radolan_grid_ll = wrl.georef.reproject(radolan_grid_xy, projection_source=proj_stereo, projection_target=proj_wgs) lon1 = radolan_grid_ll[:, :, 0] lat1 = radolan_grid_ll[:, :, 1] # - # range array 150 km print("Max Range: ", rwattrs['maxrange']) r = np.arange(1, 151) * 1000 # azimuth array 1 degree spacing az = np.linspace(0, 360, 361)[0:-1] # get radar dict radars = DwdRadarSites() def plot_radar(radar, ax, proj): site = (radar['longitude'], radar['latitude'], radar['heightantenna'] ) # build polygons for maxrange rangering polygons = wrl.georef.spherical_to_polyvert(r, az, 0, site, proj=proj) polygons = polygons[..., 0:2] polygons.shape = (len(az), len(r), 5, 2) polygons = polygons[:, -1, :, :] x_loc, y_loc = wrl.georef.reproject(site[0], site[1], projection_source=proj_wgs, projection_target=proj) # create PolyCollections and add to respective axes polycoll = mpl.collections.PolyCollection(polygons, closed=True, edgecolors='r', facecolors='r') ax.add_collection(polycoll, autolim=True) # plot radar location and information text ax.plot(x_loc, y_loc, 'r+') ax.text(x_loc, y_loc, radar['location'], color='r') # plot two projections side by side fig1 = pl.figure(figsize=(10,8)) ax1 = fig1.add_subplot(111, aspect='equal') pm = ax1.pcolormesh(lon1, lat1, rwdata, cmap='viridis') cb = fig1.colorbar(pm, shrink=0.75) cb.set_label("mm/h") pl.xlabel("Longitude ") pl.ylabel("Latitude") pl.title( 'RADOLAN RW Product \n' + rwattrs['datetime'].isoformat() + '\n WGS84') pl.xlim((lon1[0, 0], lon1[-1, -1])) pl.ylim((lat1[0, 0], lat1[-1, -1])) pl.grid(color='r') for radar_id in rwattrs['radarlocations']: # get radar coords etc from dict radar = radars.by_odimcode(radar_id) plot_radar(radar, ax1, proj_wgs) fig2 = pl.figure(figsize=(10,8)) ax2 = fig2.add_subplot(111, aspect='equal') pm = ax2.pcolormesh(x1, y1, rwdata, cmap='viridis') cb = fig2.colorbar(pm, shrink=0.75) cb.set_label("mm/h") pl.xlabel("x [km]") pl.ylabel("y [km]") pl.title('RADOLAN RW Product \n' + rwattrs[ 'datetime'].isoformat() + '\n Polar Stereographic Projection') pl.xlim((x1[0, 0], x1[-1, -1])) pl.ylim((y1[0, 0], y1[-1, -1])) pl.grid(color='r') for radar_id in rwattrs['radarlocations']: # get radar coords etc from dict radar = radars.by_odimcode(radar_id) plot_radar(radar, ax2, proj_stereo)
notebooks/radolan/radolan_network.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 # --- # + [markdown] colab_type="text" id="view-in-github" # <a href="https://colab.research.google.com/github/wesleybeckner/python_foundations/blob/main/notebooks/extras/X1_Spotify_API.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="kHWV9Cs-TpBA" # # Python Foundations <br>X1: The Spotify API # # **Instructor**: <NAME> # # **Contact**: <EMAIL> # # **Solved**: [Notebook](https://wesleybeckner.github.io/python_foundations/solutions/SOLN_X1_Spotify_API/) # # --- # # <br> # # For this workbook we're going to use the [`spotipy`](https://spotipy.readthedocs.io/en/2.19.0/#) library to access the Spotify Web API! # # <br> # # --- # # + [markdown] id="T-hVr_WQZr8z" # ## Install and import libraries # # First we will need to install it: # + colab={"base_uri": "https://localhost:8080/"} id="PMEAW4TEPhpp" outputId="861ab30e-87cf-448d-fbab-0d20779b1930" # !pip install spotipy # + [markdown] id="olzLi0-UT3nx" # And then import # + id="nveMRJENSYT1" from spotipy import client import spotipy from spotipy.oauth2 import SpotifyClientCredentials, SpotifyOAuth import sys import pandas as pd import numpy as np import matplotlib.pyplot as plt # + [markdown] id="4OBdhG6RRLF8" # ## Setup developer account # # You'll need to visit this [link](https://developer.spotify.com/dashboard/) to setup a developer account, then fill in your authorization information below # + id="YrkvXucRPrM4" SPOTIPY_CLIENT_ID = "" SPOTIPY_CLIENT_SECRET = "" # + [markdown] id="-Hi-p_ZTSInw" # ## Top 10 tracks of an artist # # We can grab the first 10 tracks of Led Zepplin: # + colab={"base_uri": "https://localhost:8080/"} id="BXUbVw0SPcBx" outputId="0ae8d1c7-a05c-485b-fb7d-d7bcbba20e9d" lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp' results = spotify.artist_top_tracks(lz_uri) ids = [] for i, track in enumerate(results['tracks']): ids.append(track['id']) if i < 5: print('track : ' + track['name']) print('audio : ' + track['preview_url']) print('cover art: ' + track['album']['images'][0]['url']) print() # + [markdown] id="Va_TUWtNW8DO" # the top tracks API only gives the top 10 tracks by an artist: # + colab={"base_uri": "https://localhost:8080/"} id="O09tzRiFV6sk" outputId="1d766a2f-6c21-41b0-9b0e-a7a11b0b3aba" len(ids) # + [markdown] id="wFRnAQL2XAvK" # Spotify has an audio features API that can be used for ML or data visualization: # + colab={"base_uri": "https://localhost:8080/"} id="O8h_2TFuSJMN" outputId="6e616863-6d8b-437b-e1b6-8b36ae84025f" features = spotify.audio_features(ids) features # + colab={"base_uri": "https://localhost:8080/", "height": 600} id="WuhWXEokSTyJ" outputId="79bc48d4-ca27-4e71-e6ae-b6ca824de21a" pd.DataFrame(features) # + [markdown] id="twwhUVrSZLMZ" # ### Add additional artists # # Let's get some other artist data to compare with: # + id="thcVOXiUYYh_" artist_dict = {'zep': '36QJpDe2go2KgaRleHCDTp', 'tswift': '06HL4z0CvFAxyc27GXpf02', 'debussy': '1Uff91EOsvd99rtAupatMP', 'luttrell': '4EOyJnoiiOJ4vuNhSBArB2', 'johnwill': '3dRfiJ2650SZu6GbydcHNb'} color_dict = {'zep': 'tab:blue', 'tswift': 'tab:green', 'debussy': 'tab:orange', 'luttrell': 'tab:red', 'johnwill': 'tab:pink'} # + colab={"base_uri": "https://localhost:8080/"} id="Vz9DntnAaVpg" outputId="7c37a9c7-19fb-485d-e5c2-39502bf9565a" ids = [] artists = [] colors = [] for artist, uri in artist_dict.items(): results = spotify.artist_top_tracks('spotify:artist:' + uri) for i, track in enumerate(results['tracks']): ids.append(track['id']) artists.append(artist) colors.append(color_dict[artist]) if i < 1: print('track : ' + track['name']) print('cover art: ' + track['album']['images'][0]['url']) print() # + colab={"base_uri": "https://localhost:8080/"} id="EgLHW8zaa8Th" outputId="33371848-f6de-47ff-f7dd-2d2484337808" features = spotify.audio_features(ids) df = pd.DataFrame(features) df['artist'] = artists df['color'] = colors feat_names = df.columns[:11] print(feat_names) # + colab={"base_uri": "https://localhost:8080/", "height": 357} id="WLgLNNsUcBCV" outputId="68c523c5-410b-4d34-ad1e-b524729ca8c3" df.head() # + [markdown] id="ZQ3QyicRbxpm" # ### Visualize the audio features # + colab={"base_uri": "https://localhost:8080/", "height": 237} id="4FQ8pRWrbz7y" outputId="4fd791a3-31e0-46ac-967a-5b90ebe1392f" df.groupby('artist')[feat_names].mean() # + colab={"base_uri": "https://localhost:8080/", "height": 609} id="gCNkND8YcWT2" outputId="0cf18fbf-2204-424f-9469-a1deba50daf1" fig, ax = plt.subplots(figsize=(10,10)) df.groupby('artist')[feat_names].mean().plot(kind='barh', ax=ax) # + [markdown] id="aPwpskx5dEa0" # we see that it is difficult to see all the features together at once. One tactic may be to normalize the features # + id="WuM2mGeAdI1_" scaled = df[feat_names].apply(lambda x: (x - x.mean()) / (x.std())) scaled['artist'] = df['artist'] # + colab={"base_uri": "https://localhost:8080/", "height": 609} id="77Qd-S89eeRA" outputId="dd514d7d-4dae-40fd-f90b-4c480371c805" fig, ax = plt.subplots(figsize=(10,10)) scaled.groupby('artist')[feat_names].mean().plot(kind='barh', ax=ax) # + [markdown] id="KeQiM75ChKNJ" # We can then investigate if these scaled and centered features separate out under a dimensionality reduction (a topic we explore in unsupervised learning): # + colab={"base_uri": "https://localhost:8080/"} id="7I0DjchmfOmD" outputId="22e8bd84-fba2-4db0-8ac9-5c14ed8019c0" from sklearn.decomposition import PCA pca = PCA(n_components=2) pca.fit(scaled[feat_names]) # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="p1RpmK0ifZvm" outputId="58165e05-fd6f-48d6-a9e1-54faf1779768" X_pca = pca.transform(df[feat_names]) plt.scatter(X_pca[:, 0], X_pca[:, 1], alpha=0.8, c=df['color'].values, edgecolor='grey') plt.xlabel('First PC') plt.ylabel('Second PC') # + [markdown] id="0nPCrrzpZgAE" # ## 🏋️‍♀️ Exercises # + [markdown] id="zWdX6NwZrBT9" # ### 🕵️‍♀️ Exercise 1: Find artist urls and build dataset # # a. Navigate to the Spotify web application, pick 5 artists and update the the dictionary below # + id="khExXw4_q4zZ" # Cell for 1.a artist_dict = {'zep': '36QJpDe2go2KgaRleHCDTp', 'tswift': '06HL4z0CvFAxyc27GXpf02', 'debussy': '1Uff91EOsvd99rtAupatMP', 'luttrell': '4EOyJnoiiOJ4vuNhSBArB2', 'johnwill': '3dRfiJ2650SZu6GbydcHNb'} color_dict = {'zep': 'tab:blue', 'tswift': 'tab:green', 'debussy': 'tab:orange', 'luttrell': 'tab:red', 'johnwill': 'tab:pink'} # + [markdown] id="6ioIfKEerbnM" # b. build feature set using `spotify.artist_top_tracks('spotify:artist:' + uri)` and storing the resultant track information # + id="tEWkxlsfrnCo" # Cell for 1.b # + [markdown] id="kO2rgwqLrMcc" # ### 💫 Exercise 2: Visualize Features # # a. Create a boxplot of each feature, grouped by artist (similar to example above) # + id="jmxoCuyurt56" # Cell for 2.a # + [markdown] id="YT7RPvofr3Tk" # b. Normalize the features this time, then create the boxplot # + id="K6M7K5vYr8oq" # Cell for 2.b # + [markdown] id="dgRT7O6er9mv" # ### ⚖️ Exercise 3: Write a function that returns a similarity score between two artists # # + id="-fJ6VDpRsN1g" # Cell for 3
notebooks/extras/X1_Spotify_API.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:root] * # language: python # name: conda-root-py # --- # # DeepVCF: A Variant Caller using deep learning # ##### This tutorial on how to train and use DeepVCF to call variants and produce a Variant Call Format (VCF) file # + from pprint import pprint import pandas as pd import seaborn as sns from DeepVCF import pathing from DeepVCF import biopandas as bpd from DeepVCF import alignment from DeepVCF.core import DeepVCF deepvcf = DeepVCF() # - # # Pulling in Training & Testing Data # ### We created these through the read simulator DWGSIM in the [tutorial](./creating-data-for-usage-demo.ipynb). The training and testing will be for both 2% platform base error (low) rate and 10% platform base error (high) rate with a .5% mutation rate for each. The goal is compare DeepVCF againset BCFtools regarding SNP variant calling when given low and high platform error rates. # + ref_train_be10percent = pathing('./example_files/staphylococcus/train/MRSA107.fasta') bam_train_be10percent = pathing('./example_files/staphylococcus/train/train-base-error-10percent.mapped.bam') vcf_train_be10percent = pathing('./example_files/staphylococcus/train/train-base-error-10percent.mutations.vcf') ref_test_be10percent = pathing('./example_files/staphylococcus/test/GCF_000013425.1_ASM1342v1_genomic_reference.fasta') bam_test_be10percent = pathing('./example_files/staphylococcus/test/test-base-error-10percent.mapped.bam') vcf_test_be10percent = pathing('./example_files/staphylococcus/test/test-base-error-10percent.mutations.vcf') ref_train_be2percent = pathing('./example_files/staphylococcus/train/MRSA107.fasta') bam_train_be2percent = pathing('./example_files/staphylococcus/train/train-base-error-2percent.mapped.bam') vcf_train_be2percent = pathing('./example_files/staphylococcus/train/train-base-error-2percent.mutations.vcf') ref_test_be2percent = pathing('./example_files/staphylococcus/test/GCF_000013425.1_ASM1342v1_genomic_reference.fasta') bam_test_be2percent = pathing('./example_files/staphylococcus/test/test-base-error-2percent.mapped.bam') vcf_test_be2percent = pathing('./example_files/staphylococcus/test/test-base-error-2percent.mutations.vcf') samtools_variant_calls_be2percent = pathing('./example_files/staphylococcus/test-base-error-2percent.bcftools.vcf') samtools_variant_calls_be10percent = pathing('./example_files/staphylococcus/test-base-error-10percent.bcftools.vcf') # - # # Train Model # ### VCF file needed to train and assumed to be high-confidence or "truth" # %%time deepvcf.train( reference_file=ref_train_be2percent, alignment_file=bam_train_be2percent, vcf_file=vcf_train_be2percent, mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, # save_pileup_to_destination='./example_files/staphylococcus/train/train.pileup.npy', # use_saved_pileup='./example_files/staphylococcus/train/train.pileup.npy', # Ignore the error, this will fail the first time if it doesn't exist ) # # Model Structure deepvcf.model.summary() # # Example Pileup & Tensor position = 9 print(deepvcf.preprocess.ref_seq[position:position+15]) print('=== Tensor ===') deepvcf.preprocess.pileup[4:19, :] position = 9 print(deepvcf.preprocess.ref_seq[position:position+15]) print('=== Tensor ===') deepvcf.preprocess.get_window(position+8).transpose() # # Model Internal Loss/Validation from matplotlib import rcParams, pyplot as plt import dataframe_image as dfi import seaborn as sns # figure size in inches rcParams['figure.figsize'] = 12,9 rcParams["legend.framealpha"] = 0.0 sns.set_theme() sns.set(font_scale=1.0) snsplot = sns.lineplot(data=pd.DataFrame(deepvcf.model.history.history)) snsplot.set(xlabel='epoch', ylabel='score', title='Model History', xlim=0) snsplot.figure.savefig('example_files/images/bacterial-model-history.png') # # Use Model to generate a Variant Format File (VCF) # %%time predicted_vcf_test = deepvcf.create_vcf( reference_file=ref_test_be2percent, alignment_file=bam_test_be2percent, # save_pileup_to_destination='./example_files/staphylococcus/test/test.pileup.npy', # use_saved_pileup='./example_files/staphylococcus/test/test.pileup.npy', # Ignore the error, this will fail the first time if it doesn't exist mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, output_folder='./example_files/staphylococcus/test/', # save as an actual .vcf file output_prefix='test' ) # # Your predicted Variant Calls from the return predicted_vcf_test.head() # # Your predicted Variant Calls from the file saved predicted_vcf_test = bpd.read_vcf('./example_files/staphylococcus/test/test.deepvcf.vcf') predicted_vcf_test # # Valitdation Metrics bpd.read_vcf(vcf_test_be2percent) # compare test to predicted metrics = deepvcf.validation( predicted_vcf=predicted_vcf_test, real_vcf=vcf_test_be2percent, ) metrics # # Now we know the complete pipeline lets compare metrics for DeepVCF VS. BCFtools when base errors are 2% and 10% # # 2% trained - 2% tested deepvcf = DeepVCF() pileup = './example_files/staphylococcus/train/train-base-error-2percent.pileup.npy' deepvcf.train( reference_file=ref_train_be2percent, alignment_file=bam_train_be2percent, vcf_file=vcf_train_be2percent, mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, # save_pileup_to_destination=pileup, # use_saved_pileup=pileup, # Ignore the error, this will fail the first time if it doesn't exist verbose=0, ) dvf_be2 = deepvcf.create_vcf( reference_file=ref_test_be2percent, alignment_file=bam_test_be2percent, # save_pileup_to_destination='./example_files/staphylococcus/test/test-base-error-2percent.pileup.npy', # use_saved_pileup='./example_files/staphylococcus/test/test-base-error-2percent.pileup.npy', mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, output_folder='./example_files', # save as an actual .vcf file output_prefix='demo-be-2-2' ) dvf_be2_metrics = deepvcf.validation(real_vcf=vcf_test_be2percent, predicted_vcf=dvf_be2) dvf_be2_metrics # # 2% trained - 10% tested deepvcf = DeepVCF() deepvcf.train( reference_file=ref_train_be2percent, alignment_file=bam_train_be2percent, vcf_file=vcf_train_be2percent, mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, # save_pileup_to_destination='./example_files/staphylococcus/train/train-base-error-2percent.pileup.npy', # use_saved_pileup='./example_files/staphylococcus/train/train-base-error-2percent.pileup.npy', # Ignore the error, this will fail the first time if it doesn't exist verbose=0, ) dvf_be_2_10 = deepvcf.create_vcf( reference_file=ref_test_be10percent, alignment_file=bam_test_be10percent, # save_pileup_to_destination='./example_files/staphylococcus/test/test-base-error-10percent.pileup.npy', # use_saved_pileup='./example_files/staphylococcus/test/test-base-error-10percent.pileup.npy', # Ignore the error, this will fail the first time if it doesn't exist mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, output_folder='./example_files/', # save as an actual .vcf file output_prefix='demo-be-2-10' ) dvf_be_2_10_metrics = deepvcf.validation(real_vcf=vcf_test_be10percent, predicted_vcf=dvf_be_2_10) dvf_be_2_10_metrics # # 10% trained - 10% tested deepvcf = DeepVCF() deepvcf.train( reference_file=ref_train_be10percent, alignment_file=bam_train_be10percent, vcf_file=vcf_train_be10percent, mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, # save_pileup_to_destination='./example_files/staphylococcus/train/train-base-error-10percent.pileup.npy', # use_saved_pileup='./example_files/staphylococcus/train/train-base-error-10percent.pileup.npy', # Ignore the error, this will fail the first time if it doesn't exist verbose=0, ) dvf_be10 = deepvcf.create_vcf( reference_file=ref_test_be10percent, alignment_file=bam_test_be10percent, # save_pileup_to_destination='./example_files/staphylococcus/test/test-base-error-10percent.pileup.npy', # use_saved_pileup='./example_files/staphylococcus/test/test-base-error-10percent.pileup.npy', # Ignore the error, this will fail the first time if it doesn't exist mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, output_folder='./example_files', # save as an actual .vcf file output_prefix='demo-be-10-10' ) dvf_be10_metrics = deepvcf.validation(real_vcf=vcf_test_be10percent, predicted_vcf=dvf_be10) dvf_be10_metrics deepvcf = DeepVCF() deepvcf.train( reference_file=ref_train_be10percent, alignment_file=bam_train_be10percent, vcf_file=vcf_train_be10percent, mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, # save_pileup_to_destination='./example_files/staphylococcus/train/train-base-error-10percent.pileup.npy', # use_saved_pileup='./example_files/staphylococcus/train/train-base-error-10percent.pileup.npy', # Ignore the error, this will fail the first time if it doesn't exist verbose=0, ) dvf_be_10_2 = deepvcf.create_vcf( reference_file=ref_test_be2percent, alignment_file=bam_test_be2percent, # save_pileup_to_destination='./example_files/staphylococcus/test/test-base-error-10percent.pileup.npy', # use_saved_pileup='./example_files/staphylococcus/test/test-base-error-2percent.pileup.npy', # Ignore the error, this will fail the first time if it doesn't exist mimimum_alignment_coverage=.75, minimum_coverage=30, heterozygous_threshold=.25, minimum_variant_radius=15, output_folder='./example_files', # save as an actual .vcf file output_prefix='demo-be-10-2' ) dvf_be_10_2_metrics = deepvcf.validation(real_vcf=vcf_test_be2percent, predicted_vcf=dvf_be_10_2) dvf_be_10_2_metrics # # BCFtools Variant calling # ## 2% base error bcf_be2_metrics = deepvcf.validation( predicted_vcf=samtools_variant_calls_be2percent, real_vcf=vcf_test_be2percent, ) pprint(bcf_be2_metrics) # ## 10% base error bcf_be10_metrics = deepvcf.validation( predicted_vcf=samtools_variant_calls_be10percent, real_vcf=vcf_test_be10percent, ) pprint(bcf_be10_metrics) # # Comparting DeepVCF with BCFtools when using noisy data metrics = [ dvf_be2_metrics, dvf_be10_metrics, dvf_be_2_10_metrics, dvf_be_10_2_metrics, bcf_be2_metrics, bcf_be10_metrics, ] names = [ 'DVCF-2', 'DVCF-10', 'DVCF-2-10', 'DVCF-10-2', 'BCF-2', 'BCF-10' ] hom_alts = [{**{'tool':name}, **m['hom_alt']} for name, m in zip(names, metrics)] hets = [{**{'tool': name}, **m['het']} for name, m in zip(names, metrics)] hom_alt = pd.DataFrame(hom_alts) het = pd.DataFrame(hets) hom_alt.style.background_gradient() het.style.background_gradient() # Here we can see BCFtools has a higher percision when the data is normal, but when the data has a high 10% base error rate it becomes unusable with heterozygous cals on the default settings and okay at homzygous alternatives.
jupyter_nb/tutorial.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 everything and define a test runner function from importlib import reload from helper import run_test import ecc import helper # + # Addition/Subtraction example print((11 + 6) % 19) print((17 - 11) % 19) print((8 + 14) % 19) print((4 - 12) % 19) # - # ### Exercise 1 # # Remember the % operator does the actual modulo operation. Also remember that `+` and `-` need to be in `()` because in the order of operations `%` comes before `+` and `-`. # # #### 1.1. Solve these equations in \\(F_{31}\\): # # * \\(2+15=?\\) # * \\(17+21=?\\) # * \\(29-4=?\\) # * \\(15-30=?\\) # # #### 1.2. Make [these tests](/edit/session1/ecc.py) pass: # ``` # ecc.py:FieldElementTest:test_add # ecc.py:FieldElementTest:test_sub # ``` # + # Exercise 1.1 # remember that % is the modulo operator prime = 31 # # 2+15=? print((2+15) % prime) # # 17+21=? print((17+21) % prime) # # 29-4=? print((29-4) % prime) # # 15-30=? print((15-30) % prime) # + # Exercise 1.2 reload(ecc) run_test(ecc.FieldElementTest('test_add')) run_test(ecc.FieldElementTest('test_sub')) # + # Multiplication/Exponentiation Example print(2 * 4 % 19) print(7 * 3 % 19) print(11 ** 3 % 19) print(pow(11, 3, 19)) # - # ### Exercise 2 # # #### 2.1. Solve these equations in \\(F_{31}\\): # # * \\(24\cdot19=?\\) # * \\(17^3=?\\) # * \\(5^5\cdot18=?\\) # # #### 2.2. Write a program to calculate \\(0\cdot k, 1\cdot k, 2\cdot k, 3\cdot k, ... 30\cdot k\\) for some \\(k\\) in \\(F_{31}\\). Notice anything about these sets? # # #### 2.3. Make [these tests](/edit/session1/ecc.py) pass: # ``` # ecc.py:FieldElementTest:test_mul # ecc.py:FieldElementTest:test_pow # ``` # # #### Bonus. Write a program to calculate \\(k^{30}\\) for all k in \\(F_{31}\\). Notice anything? # + # Exercise 2.1 # remember that ** is the exponentiation operator prime = 31 # # 24*19=? print(24*19 % prime) # # 17^3=? print(17**3 % prime) # # 5^5*18=? print(5**5*18 % prime) # + # Exercise 2.2 from random import randint prime = 31 k = randint(1,prime) # use range(prime) to iterate over all numbers from 0 to 30 inclusive print(sorted([i*k % prime for i in range(prime)])) # + # Exercise 2.3 reload(ecc) run_test(ecc.FieldElementTest('test_mul')) run_test(ecc.FieldElementTest('test_pow')) # + # Bonus prime = 31 # use range(1, prime) to iterate over all numbers from 1 to 30 inclusive print([i**30 % prime for i in range(1, prime)]) # + # Division Example print(2 * 3**17 % 19) print(2 * pow(3, 17, 19) % 19) print(3 * 15**17 % 19) print(3 * pow(15, 17, 19) % 19) # - # ### Exercise 3 # # #### 3.1. Solve these equations in \\(F_{31}\\): # # * \\(3/24 = ?\\) # * \\(17^{-3} = ?\\) # * \\(4^{-4}\cdot{11} = ?\\) # # #### 3.2. Make [these tests](/edit/session1/ecc.py) pass: # # ``` # ecc.py:FieldElementTest:test_div # ``` # + # Exercise 3.1 # remember pow(x, p-2, p) is the same as 1/x in F_p prime = 31 # 3/24 = ? print(3*24**(prime-2) % prime) # 17^(-3) = ? print(pow(17, prime-4, prime)) # 4^(-4)*11 = ? print(pow(4, prime-5, prime) * 11 % prime) # + # Exercise 3.2 reload(ecc) run_test(ecc.FieldElementTest('test_div')) # Hint: the __pow__ method needs a positive number for the exponent. # You can mod by p-1 # + # Elliptic Curve Example x, y = -1, -1 print(y**2 == x**3 + 5*x + 7) # - # ### Exercise 4 # # #### 4.1. For the curve \\(y^2 = x^3 + 5x + 7\\), which of these are on the curve? # # \\((-2,4), (3,7), (18,77)\\) # # #### 4.2. Make [this test](/edit/session1/ecc.py) pass # ``` # ecc.py:PointTest:test_on_curve # ``` # + # Exercise 4.1 # (-2,4), (3,7), (18,77) # equation in python is: y**2 == x**3 + 5*x + 7 points = ((-2,4), (3,7), (18,77)) for x, y in points: # determine whether (x,y) is on the curve if y**2 == x**3 + 5*x + 7: print('({},{}) is on the curve'.format(x,y)) else: print('({},{}) is not on the curve'.format(x,y)) # + # Exercise 4.2 reload(ecc) run_test(ecc.PointTest('test_on_curve')) # - # ### Exercise 5 # # #### 5.1. Make [this test](/edit/session1/ecc.py) pass # ``` # ecc.py:PointTest:test_add0 # ``` # + # Exercise 5.1 reload(ecc) run_test(ecc.PointTest('test_add0')) # + # Point Addition where x1 != x2 Example x1, y1 = (2, 5) x2, y2 = (3, 7) s = (y2-y1)/(x2-x1) x3 = s**2 - x2 - x1 y3 = s*(x1-x3)-y1 print(x3, y3) # - # ### Exercise 6 # # #### 6.1. For the curve \\(y^2 = x^3 + 5x + 7\\), what is \\((2,5) + (-1,-1)\\)? # # #### 6.2. Make [this test](/edit/session1/ecc.py) pass # ``` # ecc.py:PointTest:test_add1 # ``` # + # Exercise 6.1 x1, y1 = (2,5) x2, y2 = (-1,-1) # formula in python: # s = (y2-y1)/(x2-x1) s = (y2-y1)/(x2-x1) # x3 = s**2 - x2 - x1 x3 = s**2 - x2 - x1 # y3 = s*(x1-x3)-y1 y3 = s*(x1-x3) - y1 print(x3, y3) # + # Exercise 6.2 reload(ecc) run_test(ecc.PointTest('test_add1')) # + # Point Addition where x1 = x2 Example a = 5 x1, y1 = (2, 5) s = (3*x1**2+a)/(2*y1) x3 = s**2 - 2*x1 y3 = s*(x1-x3) - y1 print(x3, y3) # - # ### Exercise 7 # # #### 7.1. For the curve \\(y^2 = x^3 + 5x + 7\\), what is \\((-1,1) + (-1,1)\\)? # # #### 7.2. Make [this test](/edit/session1/ecc.py) pass # ``` # ecc.py:PointTest:test_add2 # ``` # + # Exercise 7.1 a, b = 5, 7 x1, y1 = -1, -1 # formula in python # s = (3*x1**2+a)/(2*y1) s = (3*x1**2+a)/(2*y1) # x3 = s**2 - 2*x1 x3 = s**2 - 2*x1 # y3 = s*(x1-x3) - y1 y3 = s*(x1-x3) - y1 print(x3, y3) # + # Exercise 7.2 reload(ecc) run_test(ecc.PointTest('test_add2'))
session1/complete/session1.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 ('base') # language: python # name: python3 # --- # ### 1 S​uppose you toss a fair coin 10 times, and random variable XX is the number of heads in total. What's the mathematical expectation of XX?
Financial Engineering & Risk Management/Introduction to Financial Engineering and Risk Management/Prerequisite Qualification1Probability(I).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 numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D x_train =np.random.rand(1024,2) y_train = np.dot(x_train,[2,1])+3+np.random.rand() y_train=y_train.reshape(1024,1) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(x_train[:,0], x_train[:,1], y_train, c='blue') ax.set_xlabel('X1') ax.set_ylabel('X2') ax.set_zlabel('Y') plt.show() # - # **从图中可以看出,这些点大概是在一个平面之上的** # # $$ # Y=X_1 +X_2*2 + 3 # $$ # + x = tf.placeholder('float',shape=[None,2]) y_ = tf.placeholder('float',shape=[None,1]) W = tf.Variable(tf.zeros([2,1])) b = tf.Variable(tf.zeros([1])) y = tf.add(tf.matmul(x,W),b) loss = tf.reduce_mean(tf.square(tf.subtract(y,y_))) train = tf.train.GradientDescentOptimizer(0.01).minimize(loss) init =tf.global_variables_initializer() # print(x_train.shape) # print(y_train.shape) # + n=10 x_test =np.random.rand(n,2) y_test = np.dot(x_test,[2,1])+3+np.random.rand() y_test = y_test.reshape(n,1) params=tf.trainable_variables() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(1000): sess.run(train,feed_dict={x:x_train,y_:y_train}) if i%100 == 0: print('W:{}\n,b:{}\n--------'.format(sess.run(W),sess.run(b))) print('train:{}'.format(sess.run(loss,feed_dict={x:x_train,y_:y_train}))) y_pred=sess.run(y,feed_dict={x:x_test}) print('predict:{}'.format(sess.run(loss,feed_dict={x:x_test,y_:y_test}))) y_pred2=sess.run(y,feed_dict={x:x_train}) # for i in range(len(x_test)): # print('{}:{}:{}'.format(x_test[i],y_test[i],y_pred[i])) # for i in range(len(x_train)): # print('{}:{}:{}'.format(x_train[i],y_train[i],y_pred2[i])) # + fig = plt.figure(2) ax = fig.add_subplot(111, projection='3d') ax.scatter(x_test[:,0], x_test[:,1], y_test, c='blue',label='True') ax.scatter(x_test[:,0], x_test[:,1], y_pred, c='yellow',label='Predict') ax.set_xlabel('X1') ax.set_ylabel('X2') ax.set_zlabel('Y') plt.show() # -
src/.ipynb_checkpoints/linear_regression_test-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 # --- from pyspark import SparkContext, SparkConf conf = SparkConf().setAppName("Basics").setMaster("local[*]") sc = SparkContext(conf=conf) print("Initializing Spark") lines = sc.textFile("/data/README.md") lineLengths = lines.map(lambda s: len(s)) totalLength = lineLengths.reduce(lambda a, b: a + b) import time sTime = time.time() a = lineLengths.collect() eTime = time.time() print("execution time:%s" % (eTime-sTime)) # + lines = sc.textFile("/data/README.md") lineLengths = lines.map(lambda s: len(s)) lineLengths.persist() totalLength = lineLengths.reduce(lambda a, b: a + b) import time sTime = time.time() a = lineLengths.collect() eTime = time.time() print("execution time:%s" % (eTime-sTime)) # + lines = sc.textFile("/data/README.md") lineLengths = lines.map(lambda s: len(s)) totalLength = lineLengths.reduce(lambda a, b: a + b) lineLengths.persist() import time sTime = time.time() a = lineLengths.collect() eTime = time.time() print("execution time:%s" % (eTime-sTime)) print("persist function must be executed before action(reduce)")
Basics.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 # --- # Plot ad hoc mnist instances from keras.datasets import mnist import matplotlib.pyplot as plt # load (downloaded if needed) the MNIST dataset (X_train, y_train), (X_test, y_test) = mnist.load_data() # plot 4 images as gray scale plt.subplot(221) plt.imshow(X_train[0], cmap=plt.get_cmap('gray')) plt.subplot(222) plt.imshow(X_train[1], cmap=plt.get_cmap('gray')) plt.subplot(223) plt.imshow(X_train[2], cmap=plt.get_cmap('gray')) plt.subplot(224) plt.imshow(X_train[3], cmap=plt.get_cmap('gray')) # show the plot plt.show() import numpy from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.utils import np_utils # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) # load data (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train.shape[1]*X_train.shape[2] # flatten 28*28 images to a 784 vector for each image num_pixels = X_train.shape[1] * X_train.shape[2] X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32') X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32') # normalize inputs from 0-255 to 0-1 X_train = X_train / 255 X_test = X_test / 255 # one hot encode outputs y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1] # define baseline model def baseline_model(): # create model model = Sequential() model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu')) model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # build the model model = baseline_model() # Fit the model model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2) # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("Baseline Error: %.2f%%" % (100-scores[1]*100)) print(model.predict(X_test)[0]) j = 900 d = X_test[j] d.shape=(28,28) plt.imshow(255-d,cmap="gray") plt.show() a = model.predict(X_test)[j] print("PREDICTED ANSWER:",a.argmax(axis=0)) print("CORRECT ANSWER :",y_test[j].argmax())
hand_written_digit_recognition2.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 # --- # # Mastering PyTorch # # ## Supervised learning # # ### Extend the UNet with skip connections and data augmentation # # #### Accompanying notebook to Video 1.3 # + # Include libraries import numpy as np from PIL import Image import os import random import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torch.autograd import Variable from torchvision import transforms import torchvision.transforms.functional as TF from utils import get_image_name, get_number_of_cells, \ split_data, download_data, SEED from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # %matplotlib inline # + root = './' download_data(root=root) data_paths = os.path.join('./', 'data_paths.txt') if not os.path.exists(data_paths): # !wget http://pbialecki.de/mastering_pytorch/data_paths.txt if not os.path.isfile(data_paths): print('data_paths.txt missing!') # - # Setup Globals use_cuda = torch.cuda.is_available() np.random.seed(SEED) torch.manual_seed(SEED) if use_cuda: torch.cuda.manual_seed(SEED) print('Using: {}'.format(torch.cuda.get_device_name(0))) print_steps = 10 # Utility functions def weights_init(m): ''' Initialize the weights of each Conv2d layer using xavier_uniform ("Understanding the difficulty of training deep feedforward neural networks" - Glor<NAME>. & <NAME>. (2010)) ''' if isinstance(m, nn.Conv2d): nn.init.xavier_uniform(m.weight.data) m.bias.data.zero_() if isinstance(m, nn.ConvTranspose2d): nn.init.xavier_uniform(m.weight.data) m.bias.data.zero_() class CellDataset(Dataset): def __init__(self, image_paths, target_paths, size, train=False): self.image_paths = image_paths self.target_paths = target_paths self.size = size resize_size = [s+10 for s in self.size] self.resize_image = transforms.Resize( size=resize_size, interpolation=Image.BILINEAR) self.resize_mask = transforms.Resize( size=resize_size, interpolation=Image.NEAREST) self.train = train def transform(self, image, mask): # Resize image = self.resize_image(image) mask = self.resize_mask(mask) # Perform data augmentation if self.train: # Random cropping i, j, h, w = transforms.RandomCrop.get_params( image, output_size=self.size) image = TF.crop(image, i, j, h, w) mask = TF.crop(mask, i, j, h, w) # Random horizontal flipping if random.random() > 0.5: image = TF.hflip(image) mask = TF.hflip(mask) # Random vertical flipping if random.random() > 0.5: image = TF.vflip(image) mask = TF.vflip(mask) else: center_crop = transforms.CenterCrop(self.size) image = center_crop(image) mask = center_crop(mask) # Transform to tensor image = TF.to_tensor(image) mask = TF.to_tensor(mask) return image, mask def __getitem__(self, index): image = Image.open(self.image_paths[index]) mask = Image.open(self.target_paths[index]) x, y = self.transform(image, mask) return x, y def __len__(self): return len(self.image_paths) def get_random_sample(dataset): ''' Get a random sample from the specified dataset. ''' data, target = dataset[int(np.random.choice(len(dataset), 1))] data.unsqueeze_(0) target.unsqueeze_(0) if use_cuda: data = data.cuda() target = target.cuda() data = Variable(data) target = Variable(target) return data, target # ### Add Residual to BaseConv # * Add an additional Conv layer, if channels do not match # # ![base_conv_skip](images/base_conv_skip.png) class BaseConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, padding, stride): super(BaseConv, self).__init__() self.act = nn.ReLU() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size, padding, stride) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size, padding, stride) self.downsample = None if in_channels != out_channels: self.downsample = nn.Sequential( nn.Conv2d( in_channels, out_channels, kernel_size, padding, stride) ) def forward(self, x): residual = x out = self.act(self.conv1(x)) out = self.conv2(out) if self.downsample: residual = self.downsample(x) out += residual out = self.act(out) return out class DownConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, padding, stride): super(DownConv, self).__init__() self.pool1 = nn.MaxPool2d(kernel_size=2) self.conv_block = BaseConv(in_channels, out_channels, kernel_size, padding, stride) def forward(self, x): x = self.pool1(x) x = self.conv_block(x) return x class UpConv(nn.Module): def __init__(self, in_channels, in_channels_skip, out_channels, kernel_size, padding, stride): super(UpConv, self).__init__() self.conv_trans1 = nn.ConvTranspose2d( in_channels, in_channels, kernel_size=2, padding=0, stride=2) self.conv_block = BaseConv( in_channels=in_channels + in_channels_skip, out_channels=out_channels, kernel_size=kernel_size, padding=padding, stride=stride) def forward(self, x, x_skip): x = self.conv_trans1(x) x = torch.cat((x, x_skip), dim=1) x = self.conv_block(x) return x class ResUNet(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, padding, stride): super(ResUNet, self).__init__() self.init_conv = BaseConv(in_channels, out_channels, kernel_size, padding, stride) self.down1 = DownConv(out_channels, 2 * out_channels, kernel_size, padding, stride) self.down2 = DownConv(2 * out_channels, 4 * out_channels, kernel_size, padding, stride) self.down3 = DownConv(4 * out_channels, 8 * out_channels, kernel_size, padding, stride) self.up3 = UpConv(8 * out_channels, 4 * out_channels, 4 * out_channels, kernel_size, padding, stride) self.up2 = UpConv(4 * out_channels, 2 * out_channels, 2 * out_channels, kernel_size, padding, stride) self.up1 = UpConv(2 * out_channels, out_channels, out_channels, kernel_size, padding, stride) self.out = nn.Conv2d(out_channels, 1, kernel_size, padding, stride) def forward(self, x): # Encoder x = self.init_conv(x) x1 = self.down1(x) x2 = self.down2(x1) x3 = self.down3(x2) # Decoder x_up = self.up3(x3, x2) x_up = self.up2(x_up, x1) x_up = self.up1(x_up, x) x_out = F.sigmoid(self.out(x_up)) return x_out def train(epoch): ''' Main training loop ''' # Set model to train mode model.train() # Iterate training set for batch_idx, (data, mask) in enumerate(train_loader): if use_cuda: data = data.cuda() mask = mask.cuda() data = Variable(data) mask = Variable(mask.squeeze()) optimizer.zero_grad() output = model(data) loss = criterion(output.squeeze(), mask) loss.backward() optimizer.step() if batch_idx % print_steps == 0: loss_data = loss.data[0] train_losses.append(loss_data) print( 'Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'. format(epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss_data)) def validate(): ''' Validation loop ''' # Set model to eval mode model.eval() # Setup val_loss val_loss = 0 # Disable gradients (to save memory) with torch.no_grad(): # Iterate validation set for data, mask in val_loader: if use_cuda: data = data.cuda() mask = mask.cuda() data = Variable(data) mask = Variable(mask.squeeze()) output = model(data) val_loss += F.binary_cross_entropy(output.squeeze(), mask).data[0] # Calculate mean of validation loss val_loss /= len(val_loader) val_losses.append(val_loss) print('Validation loss: {:.4f}'.format(val_loss)) # + # Get train data folders and split to training / validation set with open(data_paths, 'r') as f: data_paths = f.readlines() image_paths = [line.split(',')[0].strip() for line in data_paths] target_paths = [line.split(',')[1].strip() for line in data_paths] # Split data into train/validation datasets im_path_train, im_path_val, tar_path_train, tar_path_val = split_data( image_paths, target_paths) # + # Create datasets train_dataset = CellDataset( image_paths=im_path_train, target_paths=tar_path_train, size=(96, 96), train=True ) val_dataset = CellDataset( image_paths=im_path_val, target_paths=tar_path_val, size=(96, 96), train=False ) # Wrap in DataLoader train_loader = DataLoader( dataset=train_dataset, batch_size=32, num_workers=12, shuffle=True ) val_loader = DataLoader( dataset=val_dataset, batch_size=64, num_workers=12, shuffle=True ) # - # Creae model model = ResUNet( in_channels=1, out_channels=32, kernel_size=3, padding=1, stride=1) # Initialize weights model.apply(weights_init) # Push to GPU, if available if use_cuda: model.cuda() # Create optimizer and scheduler optimizer = optim.SGD(model.parameters(), lr=1e-3) # Create criterion criterion = nn.BCELoss() # Start training train_losses, val_losses = [], [] epochs = 30 for epoch in range(1, epochs): train(epoch) validate() # Let's visualize the loss curves and some validation images! # + train_losses = np.array(train_losses) val_losses = np.array(val_losses) val_indices = np.linspace(0, (epochs-1)*len(train_loader)/print_steps, epochs-1) plt.plot(train_losses, '-', label='train loss') plt.plot(val_indices, val_losses, '--', label='val loss') plt.yscale("log", nonposy='clip') plt.xlabel('Iterations') plt.ylabel('BCELoss') plt.legend() plt.show() # + val_data, val_target = get_random_sample(val_dataset) val_pred = model(val_data) val_pred_arr = val_pred.data.cpu().squeeze_().numpy() val_target_arr = val_target.data.cpu().squeeze_().numpy() fig, (ax1, ax2, ax3) = plt.subplots(1, 3) ax1.imshow(val_pred_arr) ax1.set_title('Prediction') ax2.imshow(val_target_arr) ax2.set_title('Target') ax3.imshow(np.abs(val_pred_arr - val_target_arr)) ax3.set_title('Absolute error')
code/section1/video1_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 # --- # + import sys sys.path.append('../src') from numpy import * from Params import * from NeutrinoFuncs import * E_th = 1.0e-4 Names,Solar,E_nu_all,Flux_all,Flux_norm,Flux_err = GetNuFluxes(E_th,Nuc=Xe131) n_nu = shape(Flux_all)[0] EmaxAr = MaxNuRecoilEnergies(Ar40) EmaxXe = MaxNuRecoilEnergies(Xe131) for i in range(0,n_nu): print(Names[i],'$',NuMaxEnergy[i],'$ & $','{0:.3f}'.format(EmaxXe[i]),'$ & $','{0:.3f}'.format(EmaxAr[i]),'$') # + def rms_energy(E_nu,Flux): return sqrt(trapz(Flux*E_nu**2,E_nu)/trapz(Flux,E_nu)) m_N_Xe = (Xe131.MassNumber)*m_p_keV m_N_Ar = (Ar40.MassNumber)*m_p_keV for i in range(0,n_nu): E_rms = rms_energy(E_nu_all[i,:],Flux_all[i,:]) E_r_90_Xe = (0.05*2*m_N_Xe*(1000.0*E_rms)**2.0/(m_N_Xe+1000*E_rms)**2.0)*(1 - 0.9/2) E_r_90_Ar = (0.05*2*m_N_Ar*(1000.0*E_rms)**2.0/(m_N_Ar+1000*E_rms)**2.0)*(1 - 0.9/2) print(Names[i],'$','{0:.4f}'.format(E_rms),'{0:.4f}'.format(E_r_90_Xe),'{0:.4f}'.format(E_r_90_Ar)) # + Flux = Flux_all[0,:] E_nu = E_nu_all[0,:] # + import matplotlib.pyplot as plt for i in range(0,n_nu): Flux = Flux_all[i,:] E_nu = E_nu_all[i,:] if Flux[1]<0: E_peak = E_nu[argmax(Flux)] else: E_peak = E_nu[0] print(Names[i],'$','{0:.4f}'.format(E_peak)) # - E_r = logspace(-3,3,10000) t = 0 dR_Ar = AllNuRates(E_r,t,Solar,E_nu_all,Flux_all,Nuc=Params.Ar40) dR_Xe = AllNuRates(E_r,t,Solar,E_nu_all,Flux_all,Nuc=Params.Xe131) # + from scipy.integrate import cumtrapz def E_r_median(dR): R_cum = cumtrapz(dR,E_r) R_cum /= R_cum[-1] E_med = E_r[argmin(abs(R_cum-0.5))] return E_med for i in range(0,n_nu): E_nu_rms = rms_energy(E_nu_all[i,:],Flux_all[i,:]) E_peak_Ar = E_r_median(dR_Ar[i,:]) E_peak_Xe = E_r_median(dR_Xe[i,:]) print(Names[i],'$','{0:.4f}'.format(E_nu_rms),'$ & $','{0:.4f}'.format(E_peak_Xe),'$ & $','{0:.4f}'.format(E_peak_Ar),'$') # -
notebooks/Show_NuMaxEnergies.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 # --- # # This is a simple handwritting recognition example with conv-net to show how to use tensorboard # # Importing libraries import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import os # # Defining models placeholders # + x = tf.placeholder(tf.float32, shape=[None, 784],name = "Image") y_ = tf.placeholder(tf.float32, shape=[None, 10],name = "Correct_Image_label") #Reshaping the input for convnet x_image = tf.reshape(x, [-1,28,28,1],name = "Reshaped_Image") # - # # Definning some important functions # + def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) # + def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # - # # Definning variables # + #Variables for first convolutional layers W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) #Variables for second convolutional layers W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) #Variables for first fully connected layers W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) #Variables for final fully connected layers W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) # - # # Adding the layer of the graphs # + # First convolutional layer h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # First pooling layer h_pool1 = max_pool_2x2(h_conv1) # + # Second convolutional layer h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # Second pooling layer h_pool2 = max_pool_2x2(h_conv2) # + # Flattening the final pooled layer h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) #First fully connected layer h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # - # Introducing dropoutacc keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # Final softmax output y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # ### Loss cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) # ### Trainning step #Trainning step train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # ### Accuracy # + #Correct prediction correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) #Accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # - # # Creating summery for log data # + # Create a summary to monitor loss tensor tf.scalar_summary("loss", cross_entropy) # Create a summary to monitor accuracy tensor tf.scalar_summary("accuracy", accuracy) # Merge all summaries into a single op merged_summary_op = tf.merge_all_summaries() # - # # Initializing the session variables sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) # # Defining the log directory where the summery will remian and also the summery writer logs_path = os.path.join(os.getcwd(),"logdata") summary_writer = tf.train.SummaryWriter(logs_path, graph=tf.get_default_graph()) # # Loading the MNIST dataset mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # # Trainning and writting the log data # + print "Please go to %s directory and write 'tensorboard --logdir logdata/' on terminal and hit enter"%os.getcwd() print "Now open the browser and type http://0.0.0.0:6006 and now you can see the tensorboard" try: for i in range(20000): #Getting the batch batch = mnist.train.next_batch(50) if i%100 == 0: train_accuracy = accuracy.eval(feed_dict={ x:batch[0], y_: batch[1], keep_prob: 1.0}) print("step %d, training accuracy %g"%(i, train_accuracy)) #Running the trainning and getting the summery out _,summary = sess.run([train_step,merged_summary_op],feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) #Writting the summerys summary_writer.add_summary(summary, i) print("test accuracy %g"%accuracy.eval(feed_dict={ x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) except KeyboardInterrupt: pass
Tensorboard/Tensorboard.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/luchorivera/Prueba/blob/master/introduccion_a_pandas_gc.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] colab_type="text" id="JndnmDMp66FL" # #### Copyright 2017 Google LLC. # + colab_type="code" id="hMqWDc_m6rUC" cellView="both" colab={} # 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="rHLcriKWLRe4" # # Intro to pandas # + [markdown] colab_type="text" id="QvJBqX8_Bctk" # **Learning Objectives:** # * Gain an introduction to the `DataFrame` and `Series` data structures of the *pandas* library # * Access and manipulate data within a `DataFrame` and `Series` # * Import CSV data into a *pandas* `DataFrame` # * Reindex a `DataFrame` to shuffle data # + [markdown] colab_type="text" id="TIFJ83ZTBctl" # [*pandas*](http://pandas.pydata.org/) is a column-oriented data analysis API. It's a great tool for handling and analyzing input data, and many ML frameworks support *pandas* data structures as inputs. # Although a comprehensive introduction to the *pandas* API would span many pages, the core concepts are fairly straightforward, and we'll present them below. For a more complete reference, the [*pandas* docs site](http://pandas.pydata.org/pandas-docs/stable/index.html) contains extensive documentation and many tutorials. # + [markdown] colab_type="text" id="s_JOISVgmn9v" # ## Basic Concepts # # The following line imports the *pandas* API and prints the API version: # + colab_type="code" id="aSRYu62xUi3g" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="5c37702e-28fc-4199-f4f3-5993b2325465" from __future__ import print_function import pandas as pd pd.__version__ # + [markdown] colab_type="text" id="daQreKXIUslr" # The primary data structures in *pandas* are implemented as two classes: # # * **`DataFrame`**, which you can imagine as a relational data table, with rows and named columns. # * **`Series`**, which is a single column. A `DataFrame` contains one or more `Series` and a name for each `Series`. # # The data frame is a commonly used abstraction for data manipulation. Similar implementations exist in [Spark](https://spark.apache.org/) and [R](https://www.r-project.org/about.html). # + [markdown] colab_type="text" id="fjnAk1xcU0yc" # One way to create a `Series` is to construct a `Series` object. For example: # + colab_type="code" id="DFZ42Uq7UFDj" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="080f197d-df3f-4a0e-a06f-50a868125315" pd.Series(['San Francisco', 'San Jose', 'Sacramento']) # + [markdown] colab_type="text" id="U5ouUp1cU6pC" # `DataFrame` objects can be created by passing a `dict` mapping `string` column names to their respective `Series`. If the `Series` don't match in length, missing values are filled with special [NA/NaN](http://pandas.pydata.org/pandas-docs/stable/missing_data.html) values. Example: # + colab_type="code" id="avgr6GfiUh8t" colab={"base_uri": "https://localhost:8080/", "height": 142} outputId="2aa8091f-e7ce-4d6d-f2ea-e0859656097a" city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento']) population = pd.Series([852469, 1015785, 485199]) pd.DataFrame({ 'City name': city_names, 'Population': population }) # + [markdown] colab_type="text" id="oa5wfZT7VHJl" # But most of the time, you load an entire file into a `DataFrame`. The following example loads a file with California housing data. Run the following cell to load the data and create feature definitions: # + colab_type="code" id="av6RYOraVG1V" colab={"base_uri": "https://localhost:8080/", "height": 297} outputId="56904460-ad65-44fd-8e9b-38079a3079fa" california_housing_dataframe = pd.read_csv("https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv", sep=",") california_housing_dataframe.describe() # + [markdown] colab_type="text" id="WrkBjfz5kEQu" # The example above used `DataFrame.describe` to show interesting statistics about a `DataFrame`. Another useful function is `DataFrame.head`, which displays the first few records of a `DataFrame`: # + colab_type="code" id="s3ND3bgOkB5k" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="0e048dd5-1cc6-499b-8c8e-babf9cef8816" california_housing_dataframe.head() # + [markdown] colab_type="text" id="w9-Es5Y6laGd" # Another powerful feature of *pandas* is graphing. For example, `DataFrame.hist` lets you quickly study the distribution of values in a column: # + colab_type="code" id="nqndFVXVlbPN" colab={"base_uri": "https://localhost:8080/", "height": 315} outputId="4a69b4e6-69c4-4c99-c90f-a8a635e3f375" california_housing_dataframe.hist('housing_median_age') # + [markdown] colab_type="text" id="XtYZ7114n3b-" # ## Accessing Data # # You can access `DataFrame` data using familiar Python dict/list operations: # + colab_type="code" id="_TFm7-looBFF" colab={"base_uri": "https://localhost:8080/", "height": 102} outputId="cfeb74cd-c201-40d4-8c10-39d9ef114baf" cities = pd.DataFrame({ 'City name': city_names, 'Population': population }) print(type(cities['City name'])) cities['City name'] # + colab_type="code" id="V5L6xacLoxyv" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="200304bc-e7c7-4532-a788-b83cbd482510" print(type(cities['City name'][1])) cities['City name'][1] # + colab_type="code" id="gcYX1tBPugZl" colab={"base_uri": "https://localhost:8080/", "height": 128} outputId="6f6f432f-2560-483b-87de-30c3bf52dffc" print(type(cities[0:2])) cities[0:2] # + [markdown] colab_type="text" id="65g1ZdGVjXsQ" # In addition, *pandas* provides an extremely rich API for advanced [indexing and selection](http://pandas.pydata.org/pandas-docs/stable/indexing.html) that is too extensive to be covered here. # + [markdown] colab_type="text" id="RM1iaD-ka3Y1" # ## Manipulating Data # # You may apply Python's basic arithmetic operations to `Series`. For example: # + colab_type="code" id="XWmyCFJ5bOv-" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="298a999b-66fb-40cc-de39-27645b2aa10d" population / 1000. # + [markdown] colab_type="text" id="TQzIVnbnmWGM" # [NumPy](http://www.numpy.org/) is a popular toolkit for scientific computing. *pandas* `Series` can be used as arguments to most NumPy functions: # + colab_type="code" id="ko6pLK6JmkYP" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="a4abb77b-ddc3-4189-a9ed-62562cfbf9a8" import numpy as np np.log(population) # + [markdown] colab_type="text" id="xmxFuQmurr6d" # For more complex single-column transformations, you can use `Series.apply`. Like the Python [map function](https://docs.python.org/2/library/functions.html#map), # `Series.apply` accepts as an argument a [lambda function](https://docs.python.org/2/tutorial/controlflow.html#lambda-expressions), which is applied to each value. # # The example below creates a new `Series` that indicates whether `population` is over one million: # + colab_type="code" id="Fc1DvPAbstjI" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="fc0c3f7d-23c9-4dd4-f3d1-2bbf4ab93f9a" population.apply(lambda val: val > 1000000) # + [markdown] colab_type="text" id="ZeYYLoV9b9fB" # # Modifying `DataFrames` is also straightforward. For example, the following code adds two `Series` to an existing `DataFrame`: # + colab_type="code" id="0gCEX99Hb8LR" colab={"base_uri": "https://localhost:8080/", "height": 142} outputId="896e469d-8552-4131-94ae-f654d25aa9d1" cities['Area square miles'] = pd.Series([46.87, 176.53, 97.92]) cities['Population density'] = cities['Population'] / cities['Area square miles'] cities # + [markdown] colab_type="text" id="6qh63m-ayb-c" # ## Exercise #1 # # Modify the `cities` table by adding a new boolean column that is True if and only if *both* of the following are True: # # * The city is named after a saint. # * The city has an area greater than 50 square miles. # # **Note:** Boolean `Series` are combined using the bitwise, rather than the traditional boolean, operators. For example, when performing *logical and*, use `&` instead of `and`. # # **Hint:** "San" in Spanish means "saint." # + colab_type="code" id="zCOn8ftSyddH" colab={} # Your code here # + [markdown] colab_type="text" id="YHIWvc9Ms-Ll" # ### Solution # # Click below for a solution. # + colab_type="code" id="T5OlrqtdtCIb" colab={"base_uri": "https://localhost:8080/", "height": 142} outputId="bc78ca7d-59f4-4da4-bdec-60bf56bc0712" cities['Is wide and has saint name'] = (cities['Area square miles'] > 50) & cities['City name'].apply(lambda name: name.startswith('San')) cities # + [markdown] colab_type="text" id="f-xAOJeMiXFB" # ## Indexes # Both `Series` and `DataFrame` objects also define an `index` property that assigns an identifier value to each `Series` item or `DataFrame` row. # # By default, at construction, *pandas* assigns index values that reflect the ordering of the source data. Once created, the index values are stable; that is, they do not change when data is reordered. # + colab_type="code" id="2684gsWNinq9" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="e3703e8f-f1d4-4f91-cae8-1feb47ca291e" city_names.index # + colab_type="code" id="F_qPe2TBjfWd" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="504c335f-9900-4498-df06-6cfef850b47b" cities.index # + [markdown] colab_type="text" id="hp2oWY9Slo_h" # Call `DataFrame.reindex` to manually reorder the rows. For example, the following has the same effect as sorting by city name: # + colab_type="code" id="sN0zUzSAj-U1" colab={"base_uri": "https://localhost:8080/", "height": 142} outputId="17c4a933-e625-4c7e-829a-64768ff1d116" cities.reindex([2, 0, 1]) # + [markdown] colab_type="text" id="-GQFz8NZuS06" # Reindexing is a great way to shuffle (randomize) a `DataFrame`. In the example below, we take the index, which is array-like, and pass it to NumPy's `random.permutation` function, which shuffles its values in place. Calling `reindex` with this shuffled array causes the `DataFrame` rows to be shuffled in the same way. # Try running the following cell multiple times! # + colab_type="code" id="mF8GC0k8uYhz" colab={"base_uri": "https://localhost:8080/", "height": 142} outputId="189eb786-7e49-4232-d0a4-04f240a45929" cities.reindex(np.random.permutation(cities.index)) # + [markdown] colab_type="text" id="fSso35fQmGKb" # For more information, see the [Index documentation](http://pandas.pydata.org/pandas-docs/stable/indexing.html#index-objects). # + [markdown] colab_type="text" id="8UngIdVhz8C0" # ## Exercise #2 # # The `reindex` method allows index values that are not in the original `DataFrame`'s index values. Try it and see what happens if you use such values! Why do you think this is allowed? # + colab_type="code" id="PN55GrDX0jzO" colab={} # Your code here # + [markdown] colab_type="text" id="TJffr5_Jwqvd" # ### Solution # # Click below for the solution. # + [markdown] colab_type="text" id="8oSvi2QWwuDH" # If your `reindex` input array includes values not in the original `DataFrame` index values, `reindex` will add new rows for these "missing" indices and populate all corresponding columns with `NaN` values: # + colab_type="code" id="yBdkucKCwy4x" colab={"base_uri": "https://localhost:8080/", "height": 173} outputId="88482882-f534-4c82-9dc1-7f501a8c3a5a" cities.reindex([0, 4, 5, 2]) # + [markdown] colab_type="text" id="2l82PhPbwz7g" # This behavior is desirable because indexes are often strings pulled from the actual data (see the [*pandas* reindex # documentation](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html) for an example # in which the index values are browser names). # # In this case, allowing "missing" indices makes it easy to reindex using an external list, as you don't have to worry about # sanitizing the input.
introduccion_a_pandas_gc.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 style="float: left; padding-right: 10px; width: 45px" src="https://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/iacs.png"> CS109A Introduction to Data Science # # ## Standard Section 2: kNN and Linear Regression # # **Harvard University**<br/> # **Fall 2019**<br/> # **Instructors**: <NAME>, <NAME>, and <NAME><br/> # **Section Leaders**: <NAME>, Abhimanyu (Abhi) Vasishth, Robbert (<NAME><br/> # # # # <hr style='height:2px'> #RUN THIS CELL import requests from IPython.core.display import HTML styles = requests.get("http://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/cs109.css").text HTML(styles) # For this section, our goal is to get you familiarized with k-Nearest Neighbors (kNN) and Linear Regression. We have learned how some aspects of dealing with data (loading in data files, scraping data from the web, visualizing data) and now we're moving to data modeling. # # Specifically, we will: # # - Load in the Bikeshare dataset # - Do some basic exploratory data analysis (EDA) of the dataset # - Split it into a training and test dataset and understand why this is needed # - Learn to use kNN using the sklearn package (bonus: we will also look at writing the algorithm without sklearn) # - Learn to use the statsmodels and sklearn packages for Linear Regression. # - Learn about confidence intervals and how to extract them. # For this section we will be using the following packages: #Matrices, Dataframe and Plotting Operations import numpy as np import pandas as pd import seaborn as sns import matplotlib import matplotlib.pyplot as plt # %matplotlib inline # # Working with Dataframes # ## Load in the Bikeshare dataset and perform EDA: # The task is to build a regression model for a bike share system to **predict the total number of bike rentals in a given day**, based on attributes about the day. Such a demand forecasting model would be useful in planning the number of bikes that need to be available in the system on any given day, and also in monitoring traffic in the city. The data for this problem was collected from the Capital Bikeshare program in Washington D.C. over two years. # # The data set is provided in the file 'bikeshare.csv'. Each row in these files contains 10 attributes describing a day and its weather. # # **Description of variables** # # - season (1 = spring, 2 = summer, 3 = fall, 4 = winter) # - month (1 through 12, with 1 denoting Jan) # - holiday (1 = the day is a holiday, 0 = otherwise) # - day_of_week (0 through 6, with 0 denoting Sunday) # - workingday (1 = the day is neither a holiday or weekend, 0 = otherwise) # - weather # - 1: Clear, Few clouds, Partly cloudy, Partly cloudy # - 2: Mist + Cloudy, Mist + Broken clouds, Mist + Few clouds, Mist # - 3: Light Snow, Light Rain + Thunderstorm + Scattered clouds, Light Rain + Scattered clouds # - 4: Heavy Rain + Ice Pallets + Thunderstorm + Mist, Snow + Fog # - temp (temperature in Celsius) # - atemp (apparent, or relative outdoor, or real feel temperature, in Celsius) # - humidity (relative humidity) # - windspeed (wind speed) # - **count** (response variable i.e. total number of bike rentals on the day) # # **Load the BikeShare dataset and drop the unnecessary columns** # bikeshare = pd.read_csv('../data/bikeshare.csv').drop(columns=['Unnamed: 0']) print("Length of Dataset:",len(bikeshare)) display(bikeshare.head()) display(bikeshare.describe()) # **We can also use the groupby function to look at mean stats aggregated by month** # + # Your code here # + # # %load '../solutions/sol1.py' # - # **Let's plot the variation of count with month. Is there a seasonal change?** # + # Your code here # + # # %load '../solutions/sol2.py' # - # **What is temp, a_temp, is there a difference? Let us plot them both** # + # Your code here # + # # %load '../solutions/sol3.py' # - # **What did we do wrong here? Why does the plot look like this?** # **Sorting!** Whenever your plot makes zig-zag changes across the scale, it is because ```matplotlib``` is trying to connect the points *sequentially* from the top (using a line plot) and skipping across the scale when $x_{i+1}$ is lower than $x_{i}$. So let's sort. # + # Sorting new = bikeshare.sort_values(['temp']) plt.plot(new['temp'], new['atemp'],'-b',alpha=1) plt.xlabel('Temp') plt.ylabel('A - Temp') plt.title('A - Temp vs Temp') plt.show() # - # **It still looks weird, why?** # Let's have a closer look at the dataframe: display(new.head(10)) # There are multiple ```atemp``` values for each ```temp``` value, which if not sorted will bounce around at the same x-value. Thus, we need to sort both axes simultaneously. new = bikeshare.sort_values(['temp','atemp']) plt.plot(new['temp'], new['atemp'],'-b') plt.xlabel('Temp') plt.ylabel('A - Temp') plt.title('A - Temp vs Temp') plt.show() # By plotting efficiently, we found an anomaly we would have otherwise overlooked. It looks like there is a problem with the data around ```temp greater than 30``` and ```atemp less than 10```. # **Show all rows in the dataframe where the temp is greater than 30 and the atemp is less than 10** # + # Your code here # + # # %load '../solutions/sol4.py' # - # Anomaly! ```atemp``` and ```temp``` are usually lineary related except at this one datapoint. Now, we get to make a judgement call as to whether we should keep the datapoint? We'll come back to this question after the lecture on Missing Data and Imputation. Worth a thought though. bikeshare= bikeshare.drop([188]) # We can now try what we wrote and we should end up with no rows in the dataframe where the temp is greater than 30 and the atemp is less than 10 # + # # %load '../solutions/sol4.py' # - # ## Split up the data into a training set and a test set using the 'train_test_split' function from sklearn: # Having an idea of what the data looks like, we want to predict count. We will be breaking up the data into a **training** and a **testing** set. The **training** set will be used to train the model, while the **testing** set will be used to quantify how well our model does. The **testing** set is a way for us to ensure our model doesn't overfit our training data. # **Let us first create a function that will randomly split the data up into a 70-30 split, with 70% of the data going into the training set:** # + from sklearn.model_selection import train_test_split train_data, test_data = train_test_split(bikeshare, test_size=0.30, random_state=42) print("Length of Training set = ",len(train_data)) print("Length of Testing set = ",len(test_data)) # - # **Calculate the ratio of the number of points in the training set to the number of points in the testing set to see if we have split the data correctly** # + # Your code here # + # # %load '../solutions/sol5.py' # - # # kNN Regression # # ![knn](../fig/knn_1.png) # ![knn](../fig/knn_2.png) # ![knn](../fig/knn_3.png) # # # ## Using sklearn to implement kNN: # We will now use the [scikit learn (sklearn)](https://scikit-learn.org/stable/index.html) package to implement kNN. Then, we can fit the model and use various metrics to assess our accuracy. # # **General sklearn model fitting code-structure :** # # ``` # #Split Data into Train and Test Set # x_train, y_train = training_data.drop('Response_Variable', axis=1), training_data['Response_Variable'] # x_test, y_test = test_data.drop('Response_Variable', axis=1), test_data['Response_Variable'] # # #Define Model # model = sklearn_model_name(hyper_parameter1 = value1, hyper_parameter2 = value2) # # #Fit Model # model.fit(x_train, y_train) # # #Get Prediction # y_pred_train = model.predict(x_train) # y_pred_test = model.predict(x_test) # # #Evaluate Model # r2_train = model.score(y_train, y_pred_train) # r2_test = model.score(y_test, y_pred_test) # # #Print Results # print("Score for Model (Training):", r2_train) # print("Score for Model (Testing) :", r2_test) # ``` # # * Every model has a list of hyperparameters that can be set using sklearn for the specific problem. In practice it is advisable to cross-validate a list of values to find best model fit. # # * ```model.fit``` calculates the parameters of your model corresponding to the training data and hyperparameters you provided. # # * ```model.predict(X)``` is the standard method called to make the model predict values for a specific X. Depending on if you feed x_train or x_test, you will get a y_prediction_train or y_prediction_test respectively. # # * Evaluation of model can vary according to the task at hand i.e. Regression or Classification. For Regression, $R^2$ Score is standard while for Classification, Accuracy (%) is standard. # + from sklearn.neighbors import KNeighborsRegressor # Set kNN parameter: k = 5 # Now we can fit the model, predict our variable of interest, and then evaluate our fit: # First, we create the classifier object: neighbors = KNeighborsRegressor(n_neighbors=k) # Then, we fit the model using x_train as training data and y_train as target values: neighbors.fit(train_data[['temp']], train_data['count']) # Retreieve our predictions: prediction_knn = neighbors.predict(test_data[['temp']]) # This returns the mean accuracy on the given test data and labels, or in other words, # the R squared value -- A constant model that always predicts the expected value of y, # disregarding the input features, would get a R^2 score of 1. r2_train = neighbors.score(train_data[['temp']], train_data['count']) r2_test = neighbors.score(test_data[['temp']], test_data['count']) print("Length of Test Data:", len(test_data['count'])) print("R^2 Score of kNN on training set:", r2_train) print("R^2 Score of kNN on testing set: ", r2_test) # + # SubPlots fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20,6)) axes[0].set_ylim([0,10000]) axes[0].plot(train_data['temp'], train_data['count'], 'o', label = 'Data' ) sorted_temp = train_data.sort_values(['temp']) prediction_knn = neighbors.predict(sorted_temp[['temp']]) axes[0].plot(sorted_temp['temp'], prediction_knn, '*-', label = 'Prediction') axes[0].set_xlabel('Temperature') axes[0].set_ylabel('# of Rides') axes[0].set_title("Temp vs Count kNN Regression Training Set (k={})".format(k)) axes[0].legend() axes[1].set_ylim([0,10000]) axes[1].plot(test_data['temp'], test_data['count'],'o', label = 'Data' )#, '*') sorted_temp = test_data.sort_values(['temp']) prediction_knn = neighbors.predict(sorted_temp[['temp']]) axes[1].plot(sorted_temp['temp'], prediction_knn, '*-', label = 'Prediction') axes[1].set_xlabel('Temperature') axes[1].set_ylabel('# of Rides') axes[1].set_title("Temp vs Count kNN Regression Test Set (k={})".format(k)) axes[1].legend() fig.suptitle("Bike Rides"); # - # # Linear Regression # # ![linear regression](../fig/linear_regression.png) # We just went over the kNN prediction method. Now, we will fit the same data with Linear Regression model. We will use a the same training/testing dataset as before and create our linear regression objects. # + from sklearn.linear_model import LinearRegression from statsmodels.api import OLS import statsmodels.api as sm #Split Data into X,Y x_train, y_train = train_data['temp'], train_data['count'] x_test, y_test = test_data['temp'], test_data['count'] #Add constant x_train_ca = sm.add_constant(x_train) x_test_ca = sm.add_constant(x_test) # - # **Fit a Linear Regression (OLS) model using statsmodels and print out the coefficients of `temp` and `const`** # # *Hint*: StatsModels use a Y followed by X structure while feeding data in contrast to sklearn that uses X followed by Y. # # Give the name *results* to your fit model # + # Your code here # - # # %load '../solutions/sol6.py' # + # Plotting our model fig, axes = plt.subplots(1,2,figsize=(20,6)) axes = axes.ravel() axes[0].plot(x_train, y_train, 'o') sorted_temp = train_data.sort_values(['temp']) prediction_lr = results.predict(sm.add_constant(sorted_temp[['temp']])) axes[0].plot(sorted_temp['temp'], prediction_lr, '*-', label = 'Prediction') axes[0].set_title('Temp vs Count Linear Regression for Training Set') axes[1].plot(x_test, y_test, 'o') sorted_temp = test_data.sort_values(['temp']) prediction_lr = results.predict(sm.add_constant(sorted_temp[['temp']])) axes[1].plot(sorted_temp['temp'], prediction_lr, '*-', label = 'Prediction') axes[1].set_title('Temp vs Count Linear Regression for Test Set') for i, ax in enumerate(axes): ax.set_ylim(0,10000) ax.set_xlabel('Temperature') ax.set_ylabel('# of Rides') ax.legend() # + # Metrics, Performance Evaluation and Helpful functions from sklearn import metrics # To compute the mean squared error (notice that we are now using the TEST set): print("R^2 Score for Linear Regression (Training):", metrics.r2_score(y_train, results.predict(x_train_ca))) print("R^2 Score for Linear Regression (Testing) :", metrics.r2_score(y_test, results.predict(x_test_ca))) # - # **Check out `results.summary()` and pay close attention to the table that shows up** results.summary() # ### Confidence Intervals # # In Data Science, a confidence interval (CI) is a type of interval estimate, computed from the statistics of the observed data, that might contain the true value of an unknown population parameter. Simply speaking, a Confidence Interval is a range of values we are fairly sure our true value lies in. # # It is important to remind ourselves here that Confidence Intervals belong to a parameter and not a statistic. Thus, they represent the window in which the true value exists for the entire population when all we have is a sample. # # ![ci](../fig/confidence_intervals.png) # # **See if you can implement a 95% confidence interval using statsmodels** # + # Your code here # + # # %load '../solutions/sol7.py' # Confidence Interval using Stats Model Summary thresh = 0.05 intervals = results.conf_int(alpha=thresh) # Renaming column names first_col = str(thresh/2*100)+"%" second_col = str((1-thresh/2)*100)+"%" intervals = intervals.rename(columns={0:first_col,1:second_col}) display(intervals) # - # In the above block of code, ```results.conf_int(alpha=thresh)``` returns a dataframe with columns 0 and 1. We explained Confidence Intervals above where because we assume normal symetric distribution of data, the 95% Confidence Interval means there's 2.5% chance of the true value lying below the values in Column 0 and 2.5% chance of the true value lying above Column 1. # ---------------- # ### End of Standard Section # --------------- # ## Extra: Train-Test Split using a mask #Function to Split data into Train and Test Set def split_data(data): #Calculate Length of Dataset length = len(data) #Define Split split = 0.7 #Set a random Seed For Shuffling np.random.seed(9001) #Generate a Mask with a X:Y Split mask = np.random.rand(length) < split #Separate train and test data data_train = data[mask] data_test = data[~mask] #Return Separately return data_train, data_test #Split data using defined function train_data_manual, test_data_manual = split_data(bikeshare) print("Length of Training set:",len(train_data_manual)) print("Length of Testing set:",len(test_data_manual)) ## Check that the ratio between test and train sets is right test_data_manual.shape[0]/(test_data_manual.shape[0]+train_data_manual.shape[0]) # ## Extra: Implementing the kNN Algorithm by hand # To really understand how the kNN algorithm works, it helps to go through the algorithm line by line in code. #kNN Algorithm def knn_algorithm(train, test, k): #Create any empty list to store our predictions in predictions = [] #Separate the response and predictor variables from training and test set: train_x = train['temp'] train_y = train['count'] test_x = test['temp'] test_y = test['count'] for i, ele in enumerate(test_x): #For each test point, store the distance between all training points and test point distances = pd.DataFrame((train_x.values - ele)**2 , index=train.index) distances.columns =['dist'] #display(distances) #Then, we sum across the columns per row to obtain the Euclidean distance squared ##distances = vec_distances.sum(axis = 1) #Sort the distances to training points (in ascending order) and take first k points nearest_k = distances.sort_values(by='dist').iloc[:k] #For simplicity, we omitted the square rooting of the Euclidean distance because the #square root function preserves order. #Take the mean of the y-values of training set corresponding to the nearest k points k_mean = train_y[nearest_k.index].mean() #Add on the mean to our predicted y-value list predictions.append(k_mean) #Create a dataframe with the x-values from test and predicted y-values predict = test.copy() predict['predicted_count'] = pd.Series(predictions, index=test.index) return predict # Now to run the algorithm on our dataset with $k = 5$: # + #Run the kNN function k = 5 predicted_knn = knn_algorithm(train_data, test_data, k) predicted_knn.head() # - # We want to have a way to evaluate our predictions from the kNN algorithm with $k=5$. One way is to compute the $R^2$ coefficient. Let's create a function for that: #Test predictions in comparison to true value of test set def evaluate(predicted, true): #Find the squared error: squared_error = (predicted['predicted_count'] - true['count'])**2 #Finding the mean squared error: error_var = squared_error.sum() sample_var = ((true['count'] - true['count'].mean())**2).sum() r = (1 - (error_var / sample_var)) return r # Then let's apply this function to our predictions: print("Length of Test Data:",len(test_data)) print("R^2 Score of kNN test:", evaluate(predicted_knn, test_data)) predicted_knn_train = knn_algorithm(test_data, train_data, k) print("R^2 Score of kNN train:", evaluate(predicted_knn_train, train_data)) # ## Extra: Computing different performance metrics by hand # Now, we will compute metrics that can be used to assess fit. # # **Note: sklearn.metrics is class of functions that consists of all the metrics we care about to evaluate our models. While it is not hard to implement them yourself, it is helpful to go through http://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics.** # + model = sm.OLS(y_train, x_train_ca) results = model.fit() #Find the squared error: y_pred_train = results.predict(x_train_ca) squared_error_train = (y_pred_train - y_train)**2 #Finding the mean squared error: error_var_train = squared_error_train.mean() sample_var_train = ((y_train - y_train.mean())**2).mean() y_pred_test = results.predict(x_test_ca) squared_error_test = (y_pred_test - y_test)**2 #Finding the mean squared error: error_var_test = squared_error_test.mean() sample_var_test = ((y_test - y_test.mean())**2).mean() print(error_var_train, sample_var_train, 1 - error_var_train/sample_var_train) print(error_var_test, sample_var_test, 1 - error_var_test/sample_var_test) # - # ---
content/sections/section2/notebook/cs109a_section_2.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:hsds] # language: python # name: conda-env-hsds-py # --- # # NREL - HSDS Data Export # This notebook demonstrates data export from the National Renewable Energy Laboratory (NREL) Wind Integration National Dataset (WIND) Toolkit and National Solar Radiation Database (NSRDB) data. The data is provided from Amazon Web Services using the HDF Group's Highly Scalable Data Service (HSDS). # # For this to work you must first install h5pyd: # # ``` # pip install --user h5pyd # ``` # # Next you'll need to configure HSDS: # # ``` # hsconfigure # ``` # # and enter at the prompt: # # ``` # hs_endpoint = https://developer.nrel.gov/api/hsds # hs_username = None # hs_password = <PASSWORD> # hs_api_key = <KEY> # ``` # # *The example API key here is for demonstation and is rate-limited per IP. To get your own API key, visit https://developer.nrel.gov/signup/* # # You can also add the above contents to a configuration file at ~/.hscfg # + # %matplotlib inline import h5pyd import numpy as np import pandas as pd import dateutil import matplotlib.pyplot as plt import matplotlib.image as mpimg import sys sys.path.append('../bin') # convenience functions from functions import WTK_idx, NSRDB_idx, datetimeIndex # - # [WTK](#WIND-Toolkit-(WTK)) | [NSRDB](#National-Solar-Radiation-Database-(NSRDB)) # ## WIND Toolkit (WTK) # ### Single Multivariate Timeseries wtk = h5pyd.File("/nrel/wtk-us.h5", 'r') list(wtk) # The following code fetches daily timeseries data for a given lat/lon for three variables. LongsPeak_idx = WTK_idx(wtk, (40.2549, -105.6160)) LongsPeak_idx # %time df = pd.DataFrame({"temperature_100m": wtk['temperature_100m'][:, LongsPeak_idx[0], LongsPeak_idx[1]],\ # "windspeed_100m": wtk['windspeed_100m'][:, LongsPeak_idx[0], LongsPeak_idx[1]],\ # "pressure_100m": wtk['pressure_100m'][:, LongsPeak_idx[0], LongsPeak_idx[1]]},\ # index=map(dateutil.parser.parse, wtk["datetime"][:])) df.index.name = 'datetime' df.head() # save data to csv df.to_csv('longspeak_wtk.csv') # ### All Within Bounding Box # + def indicesForBBox(wtk, lat_range, lon_range): xmin = None xmax = None ymin = None ymax = None for i in [0,1]: for j in [0,1]: yx = WTK_idx(wtk, (lat_range[i], lon_range[j])) if xmin is None or yx[1] < xmin: xmin = yx[1] if xmax is None or yx[1] > xmax: xmax = yx[1] if ymin is None or yx[0] < ymin: ymin = yx[0] if ymax is None or yx[0] > ymax: ymax = yx[0] return ([xmin, xmax], [ymin, ymax]) # This bounding box is the state of Colorado, more or less (x_range,y_range) = indicesForBBox(wtk, [36.96744946416934, 41.02964338716638], [-109.05029296875, -102.0849609375]) print("x range for Colorado = (%d,%d)" % (x_range[0], x_range[1])) print("y range for Colorado = (%d,%d)" % (y_range[0], y_range[1])) # - # Get every other windspeed measurement within this box for a given time step dtdf = datetimeIndex(wtk) dset = wtk['windspeed_100m'] timestep = dtdf.loc[dtdf.datetime == '2012-04-01 12:00:00'].index[0] # %time data = dset[timestep, y_range[0]:y_range[1]:2, x_range[0]:x_range[1]:2] # :2 means every second point plt.imshow(data, origin="lower") print( "There are ...") print( " %d points within this box a 2km resolution" % ((x_range[1] - x_range[0]) * (y_range[1] - y_range[0]),)) print( " %d points within this box at 4km resolution" % ((x_range[1] - x_range[0]) / 2 * (y_range[1] - y_range[0]) / 2,)) print( " %d points within this box at 8km resolution" % ((x_range[1] - x_range[0]) / 4 * (y_range[1] - y_range[0]) / 4,)) print( " %d points within this box at 16km resolution" % ((x_range[1] - x_range[0]) / 8 * (y_range[1] - y_range[0]) / 8,)) spacing = 8 # every 8th point is 16km resolution cube = dset[::(24 * 30), y_range[0]:y_range[1]:spacing, x_range[0]:x_range[1]:spacing] # every 30 days # + # Convert data cube to a datafame where each location is a column ll_for_coords = wtk['coordinates'][y_range[0]:y_range[1]:spacing, x_range[0]:x_range[1]:spacing] df = pd.DataFrame() for i in range(len(ll_for_coords)): for j in range(len(ll_for_coords[i])): colname = "%.03f,%.03f" % (ll_for_coords[i][j][1], ll_for_coords[i][j][0]) df[colname] = cube[:, i, j] df.index = wtk["datetime"][::(24 * 30)] df.index.name = 'datetime' df.head() # - df.to_csv("colorado_wtk-wspd.csv") wtk.close() # ## National Solar Radiation Database (NSRDB) # ### Single Multivariate Timeseries nsrdb = h5pyd.File("/nrel/nsrdb/nsrdb_2017.h5", 'r') list(nsrdb) LongsPeak_idx = NSRDB_idx(nsrdb, (40.2549, -105.6160)) LongsPeak_idx # function to unscale nsrdb timeseries def unscale_dset(nsrdb, dset_name, idx): dset = nsrdb[dset_name] return dset[:, idx] / dset.attrs['psm_scale_factor'] # %time df = pd.DataFrame({"air_temperature": unscale_dset(nsrdb, 'air_temperature', LongsPeak_idx),\ # "wind_speed": unscale_dset(nsrdb, 'wind_speed', LongsPeak_idx),\ # "ghi": unscale_dset(nsrdb, 'ghi', LongsPeak_idx),\ # "dhi": unscale_dset(nsrdb, 'dhi', LongsPeak_idx),\ # "dni": unscale_dset(nsrdb, 'dni', LongsPeak_idx)},\ # index=nsrdb['time_index'][...].astype(str)) df.index.name = 'datetime' df.head() # save data to csv df.to_csv('longspeak_nsrdb.csv') # ### Variable for a geographic region (State) # + def metaForState(nsrdb, state): meta = pd.DataFrame(nsrdb['meta'][...]) state = meta.loc[meta['state'] == str.encode(state)] # Note .h5 saves strings as bit-strings return state # Extract all of Colorado CO_sites = metaForState(nsrdb, 'Colorado') # - print( "There are ...") print( " {} points within CO at 4km resolution".format(len(CO_sites))) print( " {} points within CO at 8km resolution".format(len(CO_sites[::2]))) print( " {} points within CO at 16km resolution".format(len(CO_sites[::4]))) # + # Map GHI for July 4th time_index = pd.to_datetime(nsrdb['time_index'][...].astype(str)) timestep = np.where(time_index == '2017-07-04 20:00:00')[0][0] ghi = nsrdb['ghi'][timestep][CO_sites.index] / nsrdb['ghi'].attrs['psm_scale_factor'] df = CO_sites[['longitude', 'latitude']].copy() df['ghi'] = ghi df.plot.scatter(x='longitude', y='latitude', c='ghi', colormap='YlOrRd', title=str(time_index[timestep])) plt.show() # + # Pull hourly ghi for every 4th site in CO: df = pd.DataFrame() for idx, row in CO_sites.iloc[::4].iterrows(): lat_lon = '{:.2f}, {:.2f}'.format(*row[['latitude', 'longitude']].values) df[lat_lon] = unscale_dset(nsrdb, 'ghi', idx)[::2] df.index = time_index[::2] df.index.name = 'datetime' df.head() # - # Save to .csv df.to_csv("colorado_nsrdb-ghi.csv") nsrdb.close()
notebooks/06_data_export.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 # --- # This script extends the simple example posed in CompareGammaDistribution by examining a generic Markov chain with forward and backward transition rates. # # Last updated by: <NAME>, 10/20/2020 #Import necessary packages #matplotlib inline import numpy as np from scipy.spatial import ConvexHull import matplotlib.pyplot as plt import scipy.special as sps # + #Simulation for calculating onset times for a generic Markov chain def CalculatetOn_GenericMarkovChain(time,dt,Q,n,N_cells): #Calculates the onset time for a linear Markov chain with forward and backward rates. #The transition rate can be time-varying, but is the same #global rate for each transition. The model assumes n states, beginning #in the 1st state. Using finite timesteps and a Markov chain formalism, it #simulates N_cells realizations of the overall time it takes to reach the #nth state. # Inputs: # time: simulation time vector # dt: simulation timestep # Q: 3D transition rate matrix, where q_kji is the transition rate at time k from state i to j for i =/= j and # q_kii is the sum of transition rates out of state i # n: number of states # N_cells: number of cells to simulate # Outputs: # t_on: time to reach the final state for each cell (length = N_cells) ## Setup variables t_on = np.empty(N_cells) #Time to transition to final ON state for each cell t_on[:] = np.nan state = np.zeros(N_cells, dtype=int) #State vector describing current state of each cell finished_states = np.zeros(N_cells, dtype=int) #Vector storing finished statuses of each cell ## Run simulation #Loop over time #q = waitbar(0,'Running simulation...') for i in range(len(time)): if np.sum(finished_states) == N_cells: #If all cells have turned on, stop the simulation #print('Halting simulation since all cells have turned on.') break #Simulate binomial random variable to see if each cell has transitioned #If the input transition rate is a nan, this will manifest as never #transitioning. #Find indices of that have not finished yet incompleteCells = np.transpose(np.where(finished_states != 1)) #Loop over cells for j in incompleteCells: #The probability that a state i switches is given by -Q_ii * dt p = -Q[i,state[j],state[j]] * dt #Probability of transition at this timestep for this cell transitioned = np.random.binomial(1,p,1) #Binary transition decision for this cell #The state to transition to is given by the ratio of the individual rates in the column j over the total rate -Q_ii if transitioned == 1: Q_temp = np.copy(Q) #Temporary matrix where we will remove Q_ii for this cell and state Q_temp[i,state[j],state[j]] = 0 pState = np.squeeze(Q_temp[i,:,state[j]]/-Q[i,state[j],state[j]]) #print(Q[i,:,:]) newState = np.random.choice(n, 1, p=pState) #print('cell ' + str(j) + ' transitioned from state ' + str(state[j]) + \ # ' to state ' + str(newState) + 'at time ' + str(time[i])) state[j] = newState #Record the time if it transitioned to the new state if newState == n-1: t_on[j] = time[i] #See if any states have reached the ON state finished_states[state == n-1] = 1 return t_on # + #Test this script with the simple case of equal irreversible transitions #Function for analytical Gamma distribution def GamPDF(x,shape,rate): return x**(shape-1)*(np.exp(-bins*rate) / sps.gamma(shape)*(1/rate)**shape) #First, with constant rate time = np.arange(0,10,0.1) dt = 0.1 w = 1 N_cells = 1000 #Transition matrix examples Q_2 = np.array([[-w,0],[w,0]]) #two states Q_3 = np.array([[-w,0,0],[w,-w,0],[0,w,0]]) Q_4 = np.array([[-w,0,0,0],[w,-w,0,0],[0,w,-w,0],[0,0,w,0]]) #Tile into the time dimension Q_2_full = np.tile(Q_2,(len(time),1,1)) Q_3_full = np.tile(Q_3,(len(time),1,1)) Q_4_full = np.tile(Q_4,(len(time),1,1)) t_on_2 = CalculatetOn_GenericMarkovChain(time,dt,Q_2_full,2,N_cells) t_on_3 = CalculatetOn_GenericMarkovChain(time,dt,Q_3_full,3,N_cells) t_on_4 = CalculatetOn_GenericMarkovChain(time,dt,Q_4_full,4,N_cells) # - #Plot the distributions plt.figure() count, bins, ignored = plt.hist(t_on_2, 30,density=True, alpha=0.5, label='n=2') plt.plot(bins, GamPDF(bins,1,w), linewidth=2) count, bins, ignored = plt.hist(t_on_3, 30,density=True, alpha=0.5, label='n=3') plt.plot(bins, GamPDF(bins,2,w), linewidth=2) count, bins, ignored = plt.hist(t_on_4, 30,density=True, alpha=0.5, label='n=4') plt.plot(bins, GamPDF(bins,3,w), linewidth=2) plt.xlabel('time') plt.ylabel('PDF') plt.legend() # Nice, it looks like it works. For next time, try laying down a grid of transition rates to calculate a crude state space area and compare with the transient regime. # # Eventually, we need to code up the boundary exploration algorithm. # For now, let's examine the n=2 and n=3 chains in parameter space by laying down a grid of transition rate values. We'll cap the rates at $0.5 < \beta < 5$. #Function returning the mean and variance of a Gamma distribution def MeanVarGamDist(shape,rate): return shape/rate, shape/rate**2 # + #Define grid of parameter values k_min = 1 k_max = 5 k_gap = 1 k_grid = np.arange(k_min,k_max,k_gap) n = [2,3] #Analytical results for equal, irreversible transitions (n=2 and n=3 for now) meanGamma = np.zeros((len(n),len(k_grid))) varGamma = np.zeros((len(n),len(k_grid))) for i in range(len(n)): for j in range(len(k_grid)): meanGamma[i,j], varGamma[i,j] = MeanVarGamDist(n[i]-1,k_grid[j]) #Note that for n=2 the Gamma distribution limit is the full state space, since n=2 is the final state #and we don't allow reverse transitions from the final state. #Grid of transition matrices for n=3 Q_3 = [] for i in range(len(k_grid)): for j in range(len(k_grid)): for k in range(len(k_grid)): Q_3.append(np.array([[-k_grid[i],k_grid[j],0],[k_grid[i],-(k_grid[j]+k_grid[k]),0],[0,k_grid[k],0]])) print('Q_3 done') # + #Simulate distributions time = np.arange(0,10,0.1) dt = 0.1 w = 1 N_cells = 1000 #n=3 mean_3 = np.zeros(len(Q_3)) var_3 = np.zeros(len(Q_3)) for i in range(len(Q_3)): Q_3_time = np.tile(Q_3[i],(len(time),1,1)) #Tile into the time dimension t_on_3 = CalculatetOn_GenericMarkovChain(time,dt,Q_3_time,3,N_cells) mean_3[i] = np.nanmean(t_on_3) var_3[i] = np.nanvar(t_on_3) print(str(i+1) + ' of ' + str(len(Q_3)), end='\r') # - #Plot results plt.figure() for i in range(len(n)): plt.plot(meanGamma[i,:], varGamma[i,:], label='n = ' + str(n[i]) + ' Gamma distribution') plt.plot(mean_3,var_3, 'b.', label='n = 3 generic Markov chain') plt.xlabel('mean') plt.ylabel('variance') plt.xlim(0,2) plt.ylim(0,2) plt.legend() plt.title('parameter space for generic Markov chains') a = [0] * 10 print(a)
GenericMarkovChain.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 # --- # ## ${\textbf{Libraries}}$ # + import numpy as np import pandas as pd import scipy import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.preprocessing import StandardScaler from scipy.cluster.hierarchy import dendrogram, linkage from sklearn.cluster import KMeans from sklearn.decomposition import PCA # - # ## ${\textbf{Import Data}}$ df_segmentation = pd.read_csv('segmentation data.csv', index_col = 0) # ## ${\textbf{Explore Data}}$ df_segmentation.head() df_segmentation.describe() # ## ${\textbf{Correlation Estimate}}$ df_segmentation.corr() plt.figure(figsize = (12, 9)) s = sns.heatmap(df_segmentation.corr(), annot = True, cmap = 'RdBu', vmin = -1, vmax = 1) s.set_yticklabels(s.get_yticklabels(), rotation = 0, fontsize = 12) s.set_xticklabels(s.get_xticklabels(), rotation = 90, fontsize = 12) plt.title('Correlation Heatmap') plt.show() # ## ${\textbf{Visualize Raw Data}}$ plt.figure(figsize = (12, 9)) plt.scatter(df_segmentation.iloc[:, 2], df_segmentation.iloc[:, 4]) plt.xlabel('Age') plt.ylabel('Income') plt.title('Visualization of raw data') # ## ${\textbf{Standardization}}$ scaler = StandardScaler() segmentation_std = scaler.fit_transform(df_segmentation) # ## ${\textbf{Hierarchical Clustering}}$ hier_clust = linkage(segmentation_std, method = 'ward') plt.figure(figsize = (12,9)) plt.title('Hierarchical Clustering Dendrogram') plt.xlabel('Observations') plt.ylabel('Distance') dendrogram(hier_clust, truncate_mode = 'level', p = 5, show_leaf_counts = False, no_labels = True) plt.show() # ## ${\textbf{K-means Clustering}}$ wcss = [] for i in range(1,11): kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42) kmeans.fit(segmentation_std) wcss.append(kmeans.inertia_) plt.figure(figsize = (10,8)) plt.plot(range(1, 11), wcss, marker = 'o', linestyle = '--') plt.xlabel('Number of Clusters') plt.ylabel('WCSS') plt.title('K-means Clustering') plt.show() kmeans = KMeans(n_clusters = 4, init = 'k-means++', random_state = 42) kmeans.fit(segmentation_std) # ### ${\textbf{Results}}$ df_segm_kmeans = df_segmentation.copy() df_segm_kmeans['Segment K-means'] = kmeans.labels_ df_segm_analysis = df_segm_kmeans.groupby(['Segment K-means']).mean() df_segm_analysis df_segm_analysis['N Obs'] = df_segm_kmeans[['Segment K-means','Sex']].groupby(['Segment K-means']).count() df_segm_analysis['Prop Obs'] = df_segm_analysis['N Obs'] / df_segm_analysis['N Obs'].sum() df_segm_analysis df_segm_analysis.rename({0:'well-off', 1:'fewer-opportunities', 2:'standard', 3:'career focused'}) df_segm_kmeans['Labels'] = df_segm_kmeans['Segment K-means'].map({0:'well-off', 1:'fewer opportunities', 2:'standard', 3:'career focused'}) x_axis = df_segm_kmeans['Age'] y_axis = df_segm_kmeans['Income'] plt.figure(figsize = (10, 8)) sns.scatterplot(x_axis, y_axis, hue = df_segm_kmeans['Labels'], palette = ['g', 'r', 'c', 'm']) plt.title('Segmentation K-means') plt.show() # ### ${\textbf{PCA}}$ pca = PCA() pca.fit(segmentation_std) pca.explained_variance_ratio_ plt.figure(figsize = (12,9)) plt.plot(range(1,8), pca.explained_variance_ratio_.cumsum(), marker = 'o', linestyle = '--') plt.title('Explained Variance by Components') plt.xlabel('Number of Components') plt.ylabel('Cumulative Explained Variance') pca = PCA(n_components = 3) pca.fit(segmentation_std) # ### ${\textbf{PCA Results}}$ pca.components_ df_pca_comp = pd.DataFrame(data = pca.components_, columns = df_segmentation.columns.values, index = ['Component 1', 'Component 2', 'Component 3']) df_pca_comp sns.heatmap(df_pca_comp, vmin = -1, vmax = 1, cmap = 'RdBu', annot = True) plt.yticks([0, 1, 2], ['Component 1', 'Component 2', 'Component 3'], rotation = 45, fontsize = 9) pca.transform(segmentation_std) scores_pca = pca.transform(segmentation_std) # ### ${\textbf{K-means clustering with PCA}}$ wcss = [] for i in range(1,11): kmeans_pca = KMeans(n_clusters = i, init = 'k-means++', random_state = 42) kmeans_pca.fit(scores_pca) wcss.append(kmeans_pca.inertia_) plt.figure(figsize = (10,8)) plt.plot(range(1, 11), wcss, marker = 'o', linestyle = '--') plt.xlabel('Number of Clusters') plt.ylabel('WCSS') plt.title('K-means with PCA Clustering') plt.show() kmeans_pca = KMeans(n_clusters = 4, init = 'k-means++', random_state = 42) kmeans_pca.fit(scores_pca) # ### ${\textbf{K-means clustering with PCA Results}}$ df_segm_pca_kmeans = pd.concat([df_segmentation.reset_index(drop = True), pd.DataFrame(scores_pca)], axis = 1) df_segm_pca_kmeans.columns.values[-3: ] = ['Component 1', 'Component 2', 'Component 3'] df_segm_pca_kmeans['Segment K-means PCA'] = kmeans_pca.labels_ df_segm_pca_kmeans df_segm_pca_kmeans_freq = df_segm_pca_kmeans.groupby(['Segment K-means PCA']).mean() df_segm_pca_kmeans_freq df_segm_pca_kmeans_freq['N Obs'] = df_segm_pca_kmeans[['Segment K-means PCA','Sex']].groupby(['Segment K-means PCA']).count() df_segm_pca_kmeans_freq['Prop Obs'] = df_segm_pca_kmeans_freq['N Obs'] / df_segm_pca_kmeans_freq['N Obs'].sum() df_segm_pca_kmeans_freq = df_segm_pca_kmeans_freq.rename({0:'standard', 1:'career focused', 2:'fewer opportunities', 3:'well-off'}) df_segm_pca_kmeans_freq df_segm_pca_kmeans['Legend'] = df_segm_pca_kmeans['Segment K-means PCA'].map({0:'standard', 1:'career focused', 2:'fewer opportunities', 3:'well-off'}) x_axis = df_segm_pca_kmeans['Component 2'] y_axis = df_segm_pca_kmeans['Component 1'] plt.figure(figsize = (10, 8)) sns.scatterplot(x_axis, y_axis, hue = df_segm_pca_kmeans['Legend'], palette = ['g', 'r', 'c', 'm']) plt.title('Clusters by PCA Components') plt.show() # ## ${\textbf{Homework}}$ # ### ${\textbf{Plot Data by PCA Components 1 and 3}}$ # + # - # ### ${\textbf{Plot Data by PCA Components 2 and 3}}$ # +
21 - Customer Analytics in Python/5_K-Means Clustering based on Principal Component Analysis/7_K-Means Clustering with Principal Components: Homework/Customer Analytics Segmentation 6.5 Homework.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 torch import pickle from torchvision import transforms # # %matplotlib widget import matplotlib.pyplot as plt import numpy as np import sys sys.path.append("..") # Adds higher directory to python modules path. from inertia_bVAE.models import inertiaVAE32, beta_from_normalized_beta, loss_function, reconstruction_loss, kl_divergence, prediction_loss from data.dspritesbT import dSpriteBackgroundDatasetTime # + normalized_beta_values = np.logspace(np.log(.001), np.log(5), 6, base=np.e) N = 1 * 32 * 32 M = 10 beta = beta_from_normalized_beta(normalized_beta_values, N = N, M = M) for ii,_ in enumerate(normalized_beta_values): print(['betanorm = %0.3f / beta = %0.1f' % (normalized_beta_values[ii],beta[ii])]) # + n_latent = 4 gamma_values = np.linspace(0, 1, 6) vae = list() training_stats = list() for _,beta_norm in enumerate(normalized_beta_values): # beta values in the file name of checkpoints have varying number of decimal points (not so smart) beta_norm_str = '%0.4f' % (beta_norm) while beta_norm_str[-1] == '0' and beta_norm_str[-2] != '.': beta_norm_str = beta_norm_str[:-1] for _,gamma in enumerate(gamma_values): trainedpath = 'trained/inertiavae32_nlatent=%s_betanorm=%s_gamma=%s_dspritesT_circle_last_500K' % (beta_norm_str,n_latent,gamma) trainstatspath = 'trained/inertiavae32_nlatent=%s_betanorm=%s_gamma=%s_dspritesT_circle_500K.pkl' % (beta_norm_str,n_latent,gamma) vae.append(inertiaVAE32(n_latent = n_latent, gamma=gamma)) # checkpoint = torch.load(trainedpath) # vae[ii].load_state_dict(checkpoint['model_states']['net']) # # training_stats.append(pickle.load(open(trainstatspath, 'rb'))) print(gamma_values) # - vae[0] dt = dSpriteBackgroundDatasetTime(transform=transforms.Resize((32,32)), shapetype='circle',data_dir='data/dsprites-dataset/') from data.dspritesb import show_images_grid show_images_grid(dt[3][0]) from torch.utils.data import Dataset, DataLoader dataloader = DataLoader(dt, batch_size=25,shuffle=True, num_workers=4) for i,[samples,latents] in enumerate(dataloader): print(samples.shape) # show_images_grid(samples.view(25*10,1,32,32)) break x = samples x.shape x.view(vae[0].n_frames*x.size(0),vae[0].img_channels,32,32).shape x1=vae[0].conv1(x.view(vae[0].n_frames*x.size(0),vae[0].img_channels,32,32)) x1.shape x4=vae[0].conv4(vae[0].conv3(vae[0].conv2(x1))) x4.shape x1show = x1[:,0,:,:].view(-1,1,16,16).detach().numpy() show_images_grid(x1show) x4show = x4[:,0,:,:].view(-1,1,2,2).detach().numpy() show_images_grid(x4show) vae[0].fc_enc_mu(x4.view(-1,256)).shape # + firstone = vae[0].fc_enc_mu(x4.view(-1,256)).view(25,10,n_latent)[:1,:,:] firstone.shape second = torch.zeros_like(firstone) pred = torch.zeros_like(firstone) second[:,:-1,:] = firstone[:,1:,:] # second pred[:,2:,:] = second[:,:-2,:] + (second[:,:-2,:]-firstone[:,:-2,:]) # pred[:,1:,:] = np.append(np.zeros((25,2,10)),pred[:,:-2,:],1) pred plt.figure(figsize=(10,5)) plt.plot(firstone.detach().numpy().reshape(-1,n_latent)) plt.plot(second.detach().numpy().reshape(-1,n_latent)) plt.plot(pred.detach().numpy().reshape(-1,n_latent)) # + gg=2 gamma = gamma_values[gg] _,mu_enc,_,_,logvar_enc,_ = vae[0].encode(x) # _,mu_enc,_,logvar_enc = vae[0].encode(x) ### MU's mu_enc = mu_enc.view(-1,vae[0].n_frames-1,n_latent) mu_enc.shape # first mu_pred is just mu_enc mu_pred = torch.zeros_like(mu_enc) mu = torch.zeros_like(mu_enc) mu_pred[:,0,:] = mu_enc[:,0,:] # as a consequence, first mu is also just mu_enc mu[:,0,:] = mu_pred[:,0,:] # second mu_pred is same as first mu_pred mu_pred[:,1,:] = mu_pred[:,0,:] ### LOGVAR's logvar_enc = logvar_enc.view(-1,vae[0].n_frames-1,vae[0].n_latent) # first logvar_pred is just logvar_enc logvar_pred = torch.zeros_like(logvar_enc) logvar = list()# torch.zeros_like(logvar_enc) logvar_pred[:,0,:] = logvar_enc[:,0,:] # as a consequence, first logvar is also just logvar_enc logvar.append(logvar_pred[:,0,:]) # second logvar_pred is same as first logvar_pred logvar_pred[:,1,:] = logvar_pred[:,0,:] for i in range(1,vae[0].n_frames-1): mu[:,i,:] = (1-gamma)*mu_enc[:,i,:] + gamma*mu_pred[:,i,:] # variance for weighted mixture of gaussians has additional term accounting for the weighted dispersion of the means logvar.append((1-gamma)*logvar_enc[:,i,:] + gamma*logvar_pred[:,i,:] + \ (1-gamma)*(mu_enc[:,i,:]**2) + gamma*(mu_pred[:,i,:]**2) - mu[:,i,:]**2 ) if i < vae[0].n_frames-2: mu_pred[:,i+1,:] = 1*(mu[:,i,:] - mu[:,i-1,:]) + mu[:,i,:] # Equally weight the variances from the previous two time steps # Simplified based on expansion of (0.5*logvar[:,i-1,:] + 0.5*logvar[:,i,:])**2 : # 0.25*logvar[:,i-1,:]**2 + 0.25*logvar[:,i,:]**2 + 0.5*logvar[:,i-1,:]*logvar[:,i,:] logvar_pred[:,i+1,:] = 0.5*logvar[i-1] + 0.5*logvar[i] + 0.25*(mu[:,i-1,:]**2) + \ 0.25*(mu[:,i,:]**2) - 0.5*mu[:,i-1,:]*mu[:,i,:] # mu1 = mu.view(-1,vae[0].n_frames,vae[0].n_latent) # mu1.size(0) logvar = torch.stack(logvar).permute(1,0,2) gamma,1000*mu_enc[0,:,0],1000*mu_pred[0,:,0],1000*mu[0,:,0],1000*logvar_enc[0,:,0],1000*logvar_pred[0,:,0],1000*logvar[0,:,0] # - # # %pdb on recon,mu, mu_enc, mu_pred, logvar, logvar_enc, logvar_pred = vae[0].forward(x) recon.size(),mu.size(),mu_enc.size(),mu_pred.size(),logvar.size(),logvar_enc.size(),logvar_pred.size() # recon,mu, mu_enc, mu_pred, logvar = vae[0].forward(x) # recon.size(),mu.size(),mu_enc.size(),mu_pred.size(),logvar.size() plt.imshow(recon[0][4][0].detach().numpy()) 0.5*torch.sum((mu[:2,:]-mu_pred[:2,:])**2) # # %pdb on recon_loss = reconstruction_loss(x, recon) recon_loss total_kld = kl_divergence(mu, logvar) total_kld pred_loss = prediction_loss(mu,mu_pred) pred_loss actLoss = loss_function(recon_loss=recon_loss,total_kld=total_kld[0],beta=beta[0]) actLoss torch.autograd.set_detect_anomaly(True) actLoss.backward(retain_graph=True) # var_pred = torch.Tensor(size=logvar_enc.size()) torch.exp(0.5*logvar_pred) gamma*mu_enc[:,i,:]**2 # + # from main.py from solver import Solver import argparse def str2bool(v): # codes from : https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser(description='inertia bVAE (dynamic beta VAE with representational inertia)') parser.add_argument('--model', default='inertiaVAE32', type=str, help='which model to train (inertiaVAE32, inertiaVAE64))') parser.add_argument('--seed', default=1, type=int, help='random seed') parser.add_argument('--cuda', default=True, type=str2bool, help='enable cuda') parser.add_argument('--batch_size', default=64, type=int, help='batch size') parser.add_argument('--shuffle', default=True, type=str2bool, help='shuffle training data') parser.add_argument('--max_iter', default=500000, type=int, help='number of training iterations') parser.add_argument('--lr', default=1e-4, type=float, help='learning rate') parser.add_argument('--n_latent', default=4, type=int, help='dimension of the latent code') parser.add_argument('--img_channels', default=1, type=int, help='number of image channels') parser.add_argument('--beta', default=1, type=float, help='beta for the beta VAE with representational inertia') parser.add_argument('--beta_is_normalized', default=True, type=str2bool, help='flag whether input beta should be interpreted as normalized beta (default) or as unnormalized beta') parser.add_argument('--gamma', default=1, type=float, help='gamma hyperparameter for the prediction contribution to inertia') parser.add_argument('--dset_dir', default='data', type=str, help='dataset directory') parser.add_argument('--dataset', default='dsprites_circle', type=str, help='dataset name') parser.add_argument('--image_size', default=32, type=int, help='image size. now only (32,32) is supported') parser.add_argument('--num_workers', default=6, type=int, help='dataloader num_workers') parser.add_argument('--trainstats_gather_step', default=100, type=int, help='numer of iterations after which training stats are gathered and stored') parser.add_argument('--trainstats_dir', default='trainstats', type=str, help='training statistics directory') parser.add_argument('--display_step', default=10, type=int, help='number of iterations after which loss data is printed and visdom is updated') parser.add_argument('--save_step', default=2000, type=int, help='number of iterations after which a checkpoint is saved') parser.add_argument('--ckpt_dir', default='checkpoints', type=str, help='checkpoint directory') parser.add_argument('--load_last_checkpoint', default=True, type=str2bool, help='load previous checkpoint if it exists') # - args = parser.parse_known_args()[0] seed = args.seed torch.manual_seed(seed) torch.cuda.manual_seed(seed) np.random.seed(seed) net = Solver(args) net.train(plotmode=True) import importlib importlib.reload(models) from models import inertiaVAE32, reconstruction_loss, prediction_loss importlib.reload(solver) from solver import Solver show_images_grid(dt[200000][0]) pwd
src/inertia_bVAE/prototyping.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 # --- # # VSCode # ## Extensions # 1. [python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) # 2. [TODO Highlight](https://marketplace.visualstudio.com/items?itemName=wayou.vscode-todo-highlight) # 3. [Python Docstring Generator](https://marketplace.visualstudio.com/items?itemName=njpwerner.autodocstring)
Tools/VSCode.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 # --- # ## FEC 2018 Campaign Finance: # # ### Contributions from committees to candidates & independent expenditures # + import pandas as pd import numpy as np import matplotlib.patches as mpatches import matplotlib.pyplot as plt # import seaborn as sns import warnings warnings.filterwarnings('ignore') from copy import deepcopy # from datetime import datetime as dt from matplotlib import font_manager as fm, rcParams from matplotlib.lines import Line2D from matplotlib.offsetbox import ( AnnotationBbox, OffsetImage, ) from scatterparty import * from getscatters import * # %matplotlib inline # - gave = pd.read_csv('data/04/committee_stats_2.csv') gave.head(2) cand = pd.read_csv('data/04/df_cleaned_04b.csv') cand.head(2) # ### SKDKNICKERBOCKER comm = 'SKDKNICKERBOCKER' cand.loc[cand['cand_pty_affiliation'] == 'Republican', comm].value_counts().sort_index() cand.loc[ (cand['cand_pty_affiliation'] == 'Republican') & \ (cand[comm] > 851), [ 'cand_name', 'contest', 'cand_ici', 'cand_pty_affiliation', comm, 'winner_flag', ] ].sort_values([comm], ascending = False) cand.loc[cand['cand_pty_affiliation'] == 'Democrat', comm].value_counts().sort_index() cand.loc[ (cand['cand_pty_affiliation'] == 'Democrat') & \ (cand[comm] > 0), [ 'cand_name', 'contest', 'cand_ici', 'cand_pty_affiliation', comm, 'winner_flag', ] ].sort_values([comm], ascending = False) # + scatterparty( getscatters(cand, comm), title=f'{comm}:\nHouse of Representatives,\n*Republican & Democrat* received funds', ) # - scatterparty( getscatters(cand, comm, party = 'rep'), title=f'{comm}:\nHouse of Representatives,\n*Republican only* received funds', ) scatterparty( getscatters(cand, comm, party = 'dem'), title=f'{comm}:\nHouse of Representatives,\n*Democrat only* received funds', ) # ### WATERFRONT STRATEGIES comm = 'WATERFRONT STRATEGIES' cand.loc[cand['cand_pty_affiliation'] == 'Republican', comm].value_counts().sort_index() cand.loc[ (cand['cand_pty_affiliation'] == 'Republican') & \ (cand[comm] > 0), [ 'cand_name', 'contest', 'cand_ici', 'cand_pty_affiliation', comm, 'winner_flag', ] ].sort_values([comm], ascending = False) cand.loc[cand['cand_pty_affiliation'] == 'Democrat', comm].value_counts().sort_index() cand.loc[ (cand['cand_pty_affiliation'] == 'Democrat') & \ (cand[comm] > 0), [ 'cand_name', 'contest', 'cand_ici', 'cand_pty_affiliation', comm, 'winner_flag', ] ].sort_values([comm], ascending = False) scatterparty( getscatters(cand, comm), title=f'{comm}:\nHouse of Representatives,\n*Republican & Democrat* received funds', ) scatterparty( getscatters(cand, comm, party = 'dem'), title=f'{comm}:\nHouse of Representatives,\n*Democrat only* received funds', ) scatterparty( getscatters(cand, comm, party = 'rep'), title=f'{comm}:\nHouse of Representatives,\n*Republican only* received funds', ) # ### NEBO MEDIA comm = 'NEBO MEDIA' cand.loc[cand['cand_pty_affiliation'] == 'Democrat', comm].value_counts().sort_index() cand.loc[ (cand['cand_pty_affiliation'] == 'Democrat') & \ (cand[comm] > 0), [ 'cand_name', 'contest', 'cand_ici', 'cand_pty_affiliation', comm, 'winner_flag', ] ].sort_values([comm], ascending = False) scatterparty( getscatters(cand, comm), title=f'{comm}:\nHouse of Representatives,\n*Both candidates* received funds', ) scatterparty( getscatters(cand, comm, party = 'dem'), title=f'{comm}:\nHouse of Representatives,\n*Democrat only* received funds', )
projects/FEC/2018/04c - 2018_CommitteeContributions_EDA.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 # --- import timeit import numpy as np import statsmodels.stats.weightstats as stats import statsmodels.tsa.stattools as stattools def weighted_quantile(values, quantiles, sample_weight=None, values_sorted=False): """ Very close to np.percentile, but supports weights. NOTE: quantiles should be in [0, 1]! :param values: np.array with data :param quantiles: array-like with many quantiles needed :param sample_weight: array-like of the same length as `array` :param values_sorted: bool, if True, then will avoid sorting of initial array :param old_style: if True, will correct output to be consistent with np.percentile. :return: np.array with computed quantiles. """ values = np.array(values) quantiles = np.array(quantiles) if sample_weight is None: sample_weight = np.ones(len(values)) sample_weight = np.array(sample_weight) assert np.all(quantiles >= 0) and np.all(quantiles <= 1), 'quantiles should be in [0, 1]' if not values_sorted: sorter = np.argsort(values) values = values[sorter] sample_weight = sample_weight[sorter] weighted_quantiles = np.cumsum(sample_weight) - 0.5 * sample_weight weighted_quantiles /= np.sum(sample_weight) return np.interp(quantiles, weighted_quantiles, values) # + def desc_stats(x, w): s = stats.DescrStatsW(x, weights = w) d = {} d['mean'] = s.mean d['std' ] = s.std q = s.quantile( np.array([0.10, 0.25, 0.5, 0.75, 0.90]), return_pandas = False) d['decile_1'] = q[0] # save 10% and 90% intervals as well d['Q1'] = q[1] d['median'] = q[2] d['Q3'] = q[3] d['decile_9'] = q[4] d['inner_quartile_range'] = d['Q3'] - d['Q1'] d['q90_q10_range'] = d['decile_9'] - d['decile_1'] d['variance'] = d['std']*d['std'] d['min'] = np.min(x) d['max'] = np.max(x) return d def numpy_stats(x, w): d = {} d['mean'] = np.average(x, weights=w) d['variance'] = np.average( (x-d['mean'])**2, weights=w) d['std'] = np.sqrt(d['variance']) q = weighted_quantile(x, [0.1, 0.25, 0.5, 0.75, 0.9], sample_weight=w) d['decile_1'] = q[0] # save 10% and 90% intervals as well d['Q1'] = q[1] d['median'] = q[2] d['Q3'] = q[3] d['decile_9'] = q[4] d['inner_quartile_range'] = d['Q3'] - d['Q1'] d['q90_q10_range'] = d['decile_9'] - d['decile_1'] d['min'] = np.min(x) d['max'] = np.max(x) return d def numpy_stats2(x, w): d = {} d['mean'] = np.average(x, weights=w) d['variance'] = np.average( (x-d['mean'])**2, weights=w) d['std'] = np.sqrt(d['variance']) q = weighted_quantile(x, [0.1, 0.25, 0.5, 0.75, 0.9], sample_weight=w, old_style = True) d['decile_1'] = q[0] # save 10% and 90% intervals as well d['Q1'] = q[1] d['median'] = q[2] d['Q3'] = q[3] d['decile_9'] = q[4] d['inner_quartile_range'] = d['Q3'] - d['Q1'] d['q90_q10_range'] = d['decile_9'] - d['decile_1'] d['min'] = np.min(x) d['max'] = np.max(x) return d data = np.random.rand(10000) dataw = np.random.normal(size = 10000) dataw = dataw + np.abs(np.min(dataw))*1.000001 # make all positive and non-zero dataw *= 1000 def wrapped_numpy_stats(): numpy_stats(data,dataw) return def wrapped_desc_stats(): desc_stats(data,dataw) return # - # + active="" # # # + number = 100 np_time = (timeit.timeit(wrapped_numpy_stats, number = number)) desc_time = (timeit.timeit(wrapped_desc_stats, number = number)) print "For 100 tries of both" print "numpy: ", np_time print "desc: ", desc_time print "desc / numpy: ", desc_time / np_time print np_time / desc_time # - np_result = numpy_stats(data,dataw) #np_result_2 = numpy_stats2(data,dataw) desc_result = desc_stats(data,dataw) for k in np_result.keys(): print "%20s %5.5E %5.5E %5.5E"%(k, np_result[k], np_result_2[k], desc_result[k]) (np_result['median'] - desc_result['median']) / (desc_result['median'])
notebooks/Stats 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 import numpy as np import matplotlib.pyplot as plt df = pd.read_csv('50_Startups.csv') df X = df.iloc[:,:-1].values y = df.iloc[:,-1].values from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder CT =ColumnTransformer(transformers=[('encoder',OneHotEncoder(),[3])],remainder = 'passthrough') X =np.array(CT.fit_transform(X)) X 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 = 0) from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train,y_train) y_pred = model.predict(X_test) New = [y_pred,y_test] New np.set_printoptions(precision = 2) New np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1)
Multiple Linear.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 # --- # # Understanding Python # Here I am listing my understandings in python for Data Science Stuff. # # Python is a high level, interpretable language. # # Build in keywords at a glance: # - `in` operator, returns boolean, can be used to find an object in list. For eg, char in string. # - `True` and `False` are constants to hold boolean values. # - `not and or` used for boolean operations. # - `if elif else` conditional statements. # - `map lambda apply` # - `for range break continue while with` iterating words. # - `file open quit` # - `try catch raise` # # > We can use `else` with `for`. like for this do this else this. # # **Data Types** # - `str` string class, has many string methods, alos converts other data type to sting. # - `int` integer data type class, also converts variable passed to integer. # - `float` float class, has functions to work on decimal numbers. # - `chr` converts integer to string. # - `bool` boolean class, converts to boolean. # # **Data Structures** # - `list` class for DS list or array. has many functions related to list operations. # - `dict` class for DS dictionaries, has functions like .keys, .values etc. # - `tuple` class for DS tuple, has function index and count.Value cannot be changed # - `set`class for DS set. Has unique values. Defined in {}. # # **Functions** # - `def` to define a new function. def my_func(a=5, \*numbers, \**keywords): # - `type` method, returns string, type of a variable. # - `len` method, returns int, length of object passed. For eg, `len(s1)` length of string # - `max` and `min` works on list, string etc. # - `sum` adds numbers in list. # - `sorted` sorts any list using a key. default is alpanum. # - `file` is a class for file operations. Obejct created when we open. # # # %history # Gives history of commands run in notebook # **Run external commands** # # % can be used to run linux commands from notebook. It is called magic commands. For eg, `%mkdir, %ls, %pwd` etc. # %run '~/code/py/life.py' # **Variables and Data Structures** # - Built-in data types: # - Integer, Floating point, String, Boolean Values, Date and Time # - Additional data structures: # - Tuples # - Lists # - Dictionary # - Sets # # **Strings** # - A built in class `str` has many string related functions. # - String can be sliced using [:] operator. Starts from 0 and -1 from end. Also works in list or array. # - Operator `+` for concatenation and `*` for repetition. # - We can call `str.function(my_string)` or `my_string.function(args)` # - `len(s1)` length of string # - `in` operator can be used to find an object in list, char in string. # # **Note:** See example below. # # + s1 = 'Vaibhav' print (s1[4]) # prints char at 4th index print (s1[:4]) # prints chars before 4th index, 4th index excluded. # Same for -ve index print (s1[-2]) # prints char at 2nd last index print (s1[:-2]) # prints chars before 2nd last index, 2nd last index excluded. print ( len(s1) ) # prints length, number of characters in string. str.upper(s1) # same as below s1.upper() # same as above strList = list(s1) # converts to list data type, array of each char in string print (strList) # Formatting myFormat = '%.2f %% this as fraction, and string %s and value INR%d' myFormat %(2,1,4.8) # takes 3 args, convers and prints as per definition. # - # find in string 'bh' in s1 type(float('23')) # **Lists** # - List is a built in data structure. # - They can hold list of any object. # - Can have mixed data types. # - Can hold list in list. # - declared in [], separated by , # - it is similar to array, index works from 0 and -1 from end # - \* to repeat, + to concatenate, it combines lists to single list. # - has functions like, append, pop, remove, index etc. # + a_list = ['amit', 'pranav', 'ramesh', 123, 22.4] a_list.append(5) print a_list a_list.reverse() # reverses in place, returns nothing print a_list a_list.sort() print (a_list) # - sorted('hello World 4') # **Dictionary** # - A built in data structure # - Consists of key-value pair # - Key can be anything but mostly num or string # - values can be any object # - declared using {} and : # - accessed using key in [] # + my_dict = { 'k1': 'value1', 'k2': 'value2', 'k3': 'value3' } my_dict.items() # returns list of tuples print type(my_dict) print type(my_dict.items()) print type(my_dict.items()[0]) print type(my_dict.items()[0][1]) # - sorted(my_dict.values(), reverse=True) bool(1.2) x**4 True and not False type(chr(97) ) sum(range(0,10)) # last, 10, is not included # **File Operations** # - `open` pass filename and mode to open file. handle = open('./roedata.csv', 'r') for line in handle: print (line) handle.close() type(handle) handle.name handle.mode new_file = open('new.txt', 'w') new_file.write('some text') new_file.close() # %cat new.txt
_posts/Understanding Python Basics.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 serial import serial.tools.list_ports from time import sleep import sounddevice as sd ports = serial.tools.list_ports.comports() for i in range(len(ports)): print(ports[i]) # Essa porta você deve escolher de acordo com sua Porta conectada ser = serial.Serial(ports[3].device, baudrate=115200, timeout=1) def gerador_de_onda(frequencia, pontos_por_seg= 44100, duracao=0.7): ''' Função que pega a frequência e duração do tempo de uma onda como base de entrada e retorna um Array de valores com todos os pontos no tempo. ''' amplitude = 4096 t = np.linspace(0, duracao, int(pontos_por_seg * duracao)) som = amplitude * np.sin(2 * np.pi * frequencia * t) return som def gerar_notas_piano(base_freq): ''' base_freq = 261.63 é a frequência da nota C4 (Dó da quarta oitava) A Função retorna um dicionário para todas as frequências das notas do Piano ''' # Teclas brancas estão em Maiúsculo, teclas pretas (sustenido) estão em Minúsculo oitava = ['C', 'c', 'D', 'd', 'E', 'F', 'f', 'G', 'g', 'A', 'a', 'B'] # Gerar dicionário com as frequências das oitavas, usando a base escolhida (C4) freq_notas = {oitava[i]: base_freq * pow(2,(i/12)) for i in range(len(oitava))} freq_notas[''] = 0.0 # silêncio return freq_notas def gerar_musica(notas_musicais, pontos_por_seg=44100, duracao=0.25, base_freq=261.63): ''' Função que concatena todas as ondas (notas) ''' freq_notas = gerar_notas_piano(base_freq) som = [gerador_de_onda(freq_notas[nota], pontos_por_seg, duracao) for nota in notas_musicais.split(',')] som = np.concatenate(som) # som = np.round(som * 16300 / np.max(som),2) return som # Parâmetros samplerate=40000 freq_notas = gerar_notas_piano(261.63) acordes = list(freq_notas) frequencias = list(freq_notas.values()) freq_min=250 freq_max=505 tom = 'C' freq_notas while True: # Lendo as frequências convertidas que vem do microcontrolador dados_freq = int(ser.readline().decode('utf-8','ignore')) for nota in range(len(freq_notas)-1): if dados_freq >= frequencias[nota] and dados_freq <= frequencias[nota+1]: print('Acorde', acordes[nota], 'freq', round(frequencias[nota],2)) tom = acordes[nota] # sí (B) está de fora, tem que colocar if dados_freq > freq_notas['B'] and dados_freq < freq_max: tom = 'B' print('Acorde B, freq', round(freq_notas['B'],2)) if dados_freq <= freq_min or dados_freq >= freq_max: tom = ',,' musica = gerar_musica(notas_musicais=tom, pontos_por_seg=samplerate, duracao=0.7) sd.play(musica, samplerate)
piano_ultrassonico/Criar Sons.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: tequila # language: python # name: tequila # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/AnnaMHua/AnnaMHua.github.io/blob/master/Kitaev.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="ZidAcB8D3gbf" # # Exactly simulation of Kitaev Honeycomb model on IBMQ # + [markdown] id="l5UA8bws3gbl" # # Jordan-Wigner transformation # # We can use JW transformation to go from spin basis to fermion basis. The JW transformation for 2D Kitaev Honeycomb model is: # # $$a_{i,j}=(\Pi_{j'<j}\Pi_{i'}\sigma_{i',j'}^z)(\Pi_{i'<i}\sigma^z_{i',j})\frac{\sigma^x+i\sigma_y}{2}$$ # $$a_{i,j}^\dagger=(\prod_{j'<j}\prod_{i'}\sigma_{i',j'}^z)(\prod_{i'<i}\sigma^z_{i',j})\frac{\sigma^x-i\sigma_y}{2}$$ # # $$\{a_{i,j},a_{i',j'}\}=0,\quad \{a_{i,j},a_{i',j'}^\dagger\}=\delta_{ii'}\delta_{jj'}$$ # The first product represent every site above $j$-th column and the second product represent all the sites after site $(i,j)$ following the blue string.<img src = JWstring.png style = "width : 600px"> # # In this case we can restore the anticommutation relation for fermions. Very similar to XY model, we have :$$\sigma^z_{i,j} = 2a^\dagger_{i,j}a_{i,j}-1$$ # $$\sigma^z_{i,j}a^\dagger_{i,j}=(2a^\dagger_{i,j}a_{i,j}-1)a^\dagger_{i,j}=2a^\dagger_{i,j}(1-a^\dagger_{i,j}a_{i,j})-a^\dagger_{i,j}=a^\dagger_{i,j}(1-2a_{i,j}^\dagger a_{i,j})=-a^\dagger_{i,j}\sigma^z_{i,j}$$ # The interaction terms in Hamiltonian transform into: # # # # $$ # \begin{align} # \sigma^x_{i,j}\sigma^x_{i+1,j}&=(\sigma^+_{i,j}+\sigma^-_{i,j})_w(\sigma^+_{i+1,j}+\sigma^-_{i+1,j})_d\\ # &=(\prod_{j'<j}\prod_{i'}\sigma_{i',j'}^z)(\prod_{i'<i}\sigma^z_{i',j})(a_{i,j}^\dagger+a_{i,j})(\prod_{j'<j}\prod_{i'}\sigma_{i',j'}^z)(\prod_{i'<i+1}\sigma^z_{i',j})(a_{i+1,j}^\dagger+a_{i+1,j})\\ # &=(\prod_{i'<i}\sigma^z_{i',j})(a_{i,j}^\dagger+a_{i,j})(\prod_{i'<i+1}\sigma^z_{i',j})(a_{i+1,j}^\dagger+a_{i+1,j})\\ # &=(a_{i,j}^\dagger+a_{i,j})_w\sigma^z_{i,j}(a_{i+1,j}^\dagger+a_{i+1,j})_d\\ # &=-(a_{i,j}^\dagger-a_{i,j})_w(a_{i+1,j}^\dagger+a_{i+1,j})_d # \end{align} # $$ # # $$\sigma^y_{i,j}\sigma^y_{i+1,j}=(a^\dagger_{i-1,j}+a_{i-1,j})_d(a_{i,j}^\dagger-a_{i,j})_w$$ # # # $$\sigma^z_{i,j}\sigma^z_{i+1,j}=(2a^\dagger_{i,j}a_{i,j}-1)(2a^\dagger_{i+1,j}a_{i+1,j}-1)$$ # + [markdown] id="pbfMBp-v3gbm" # The Hamiltonian becomes $$\hat{H}=J_x\sum_{x\text{ links}}(a_{i,j}^\dagger-a_{i,j})(a_{i+1,j}^\dagger+a_{i+1,j})-J_y\sum_{y\text{ links}}(a_{i-1,j}^\dagger+a_{i-1,j})(a_{i,j}^\dagger-a_{i,j})-J_z\sum_{z\text{ links}}(2a^\dagger_{i,j}a_{i,j}-1)(2a^\dagger_{i+1,j}a_{i+1,j}-1)$$ # + [markdown] id="BL0JFFjc3gbm" # # Transform into Majorana fermions # # $$c_w=i(a_{i,j}^\dagger-a_{i,j}),\quad d_w=a_{i,j}^\dagger+a_{i,j},\quad \text{where $i+j$ even=white}$$ # # $$c_d=a_{i,j}^\dagger+a_{i,j},\quad d_d=i(a_{i,j}^\dagger-a_{i,j}),\quad \text{where $i+j$ odd=dark}$$ # # The Hamiltonian becomes: # # $$\hat{H}=-iJ_x\sum_{x\text{ links}}c_wc_d+iJ_y\sum_{y\text{ links}}c_dc_w-iJ_z\sum_{z \text{ links}}(id_dd_w)c_dc_w$$ # # By putting everything in a square lattice with the unit cell containing one while site and one dark site <img src = squarelattice.png style = "width : 600px"> # # we can rewrite the Hamiltonian interms of the position $\vec{r}$ of unitcell: # # $$\hat{H}=i\sum_{x\text{ links}}(J_xc_{w,r}c_{d,r+r_1}+iJ_yc_{d,r}c_{w,r+r_2}-iJ_z\alpha_rc_{d,r}c_{w,r})$$ # # we define a new operator $\alpha_r=(id_{d,r}d_{w,r})$. It commutes with the $\hat{H}$ so they can be diagonalized simutanuously. # + id="QvHrj5DN3gbm"
Kitaev.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # URL: http://matplotlib.org/examples/showcase/bachelors_degrees_by_gender.html # # Most examples work across multiple plotting backends equivalent, this example is also available for: # # * [Bokeh - bachelors_degress_by_gender](../bokeh/bachelors_degress_by_gender.ipynb) import holoviews as hv from holoviews import opts hv.extension('matplotlib') hv.output(fig='svg') # ## Define data # + import pandas as pd from matplotlib.cbook import get_sample_data fname = get_sample_data('percent_bachelors_degrees_women_usa.csv') gender_degree_data = pd.read_csv(fname) title = ('Percentage of Bachelor\'s degrees conferred to women in ' 'the U.S.A. by major (1970-2011)\n') # These are the colors that will be used in the plot color_sequence = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'] # Offsets for degree labels y_offsets = {'Foreign Languages': 0.5, 'English': -0.5, 'Communications and Journalism': 0.75, 'Art and Performance': -0.25, 'Agriculture': 1.25, 'Social Sciences and History': 0.25, 'Business': -0.75, 'Math and Statistics': 0.75, 'Architecture': -0.75, 'Computer Science': 0.75, 'Engineering': -0.25} # Load the data into a dataframe and us pd.melt to unpivot the degree column df = pd.DataFrame(gender_degree_data) df = pd.melt(df, id_vars='Year', var_name='Degree', value_name='conferred') df['Degree'] = [d.replace('_', ' ').title() for d in df.Degree] # Define a formatter that works for both bokeh and matplotlib def percent_format(x): try: return '{:0.0f}%'.format(x) except: return '%d%' % x # Define the value dimensions vdim = hv.Dimension('conferred', value_format=percent_format, range=(0, 90)) # Define the dataset ds = hv.Dataset(df, vdims=vdim) curves = ds.to(hv.Curve, 'Year', groupby='Degree').overlay() # Define a function to get the text annotations max_year = ds['Year'].max() def offset(row): row['conferred'] += y_offsets.get(row.Degree, 0) return row label_df = df[df.Year==max_year].apply(offset, axis=1) labels = hv.Labels(label_df, ['Year', 'conferred'], 'Degree') # - # ## Display in matplotlib # + # Define a callback to define a custom grid along the y-axis and disabling the (ugly) axis spines def cb(plot, element): ax = plot.handles['axis'] ax.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) (curves * labels).opts( opts.Curve( aspect=0.7, bgcolor='white', hooks=[cb], labelled=[], fig_size=350, show_frame=False, show_grid=False, show_legend=False, xlim=(1970, 2011), xticks=5, color=hv.Cycle(values=color_sequence), linewidth=2, title=title), opts.Labels(color='Degree', cmap=color_sequence, horizontalalignment='left'))
examples/gallery/demos/matplotlib/bachelors_degrees_by_gender.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 # --- # # Formally Defining Conditional Probability # In {doc}`Conditional Probability: Notation and Intuition<notation-and-intuition>`, we introduced the idea of a *conditional sample space*. Suppose that we are interested in the conditional probability of $A$ given that event $B$ occurred. A Venn diagram for a general set of events $A$ and $B$ is shown in {numref}`cond-prob-two-events` # # :::{figure-md} cond-prob-two-events # <img src="venn-diagram-two-events.svg" alt="Venn diagram for two generic events, $A$ and $B$." width="400px"> # # Venn diagram of two generic events $A$ and $B$, where the event $B$ is shaded to indicate that it is known to have occurred. # ::: # # # If the original sample space is $S$, then the set of outcomes that can have occurred given that $B$ occurred can be thought of as a “conditional sample space”, # # $$ # S_{|B} = S \cap B = B. # $$ # # ```{note} # The reason that I have put “conditional sample space” in quotation marks is that although this concept is useful to understand where the formula for calculating conditional probabilities comes from, it is also misleading in that we are not restricted to only calculating conditional probabilities for events that lie within $S_{|B}$. In fact, our assumption in drawing the Venn diagrams is that $A$ is an event that is not wholly contained in $B$. Further below, we show that conditioning on an event $B$ induces a new *conditional probability measure* on the **original sample space and event class**. # ``` # # # # Now, given that $B$ occurred, the only possible outcomes in $A$ that could have occurred are those in $A_{|B} = A \cap B$. Then the “conditional sample space” $S_{|B}$ and a corresponding conditional event # $A_{|B}$ are shown in {numref}`cond-sample-space`. # # :::{figure-md} cond-sample-space # <img src="conditional-sample-space.svg" alt="Induced conditional sample space $S_{|B}$ and conditional event $A_{|B}$ from conditioning on event $B$." width="400px"> # # Venn diagram of two generic events $A$ and $B$, where the event $B$ is shaded to indicate that it is known to have occurred. # ::: # # # Based on {numref}`cond-sample-space`, we make the following observations under the condition that $B$ is known to have occurred: # * If $A$ and $B$ are mutually exclusive, then there are no outcomes of $A$ contained in the event $B$. Thus, if $B$ occurs, $A$ cannot have occurred, and thus $P(A|B)=0$ in this case. # * If $B \subset A$, then the intersection region $A \cap B = B$. In other words, every outcome in $B$ is an outcome in $A$. If $B$ occurred, then $A$ must have occurred, so $P(A|B)=1$ in this case. # * Under the condition that $B$ occurred, only the outcomes in $A$ that are also in $B$ are possible. Thus, $P(A|B)$ should be proportional to $P(A \cap B)$ (i.e., the smaller region in {numref}`cond-sample-space`. # # These observations lead to the following definition of conditional probability: # # ````{panels} # DEFINITION # ^^^ # conditional probability # : The conditional probability of an event $A$ given that an event $B$ occurred, where $P(B) \ne 0$, is # # $$ # P(A|B) = \frac{P \left( A \cap B \right)}{P\left(B\right)} # $$ # ```` # Now suppose we have a probability space $S, \mathcal{F}, P\left( \right)$ and an event $B$ with $P(B) \ne 0$. Then we define a new probability space $S, \mathcal{F}, # P\left( ~ \left \vert B \right. \right)$, where $P\left( ~ \left \vert B \right. \right)$ is the conditional probability measure given that $B$ occurred. To be more precise, we define $P\left( ~ \left \vert B \right. \right)$ on the event class $A$ using the original probability measure $P()$ as follows: # * for each $A \in \mathcal{F}$, # $$ # P(A|B) = \frac{P \left( A \cap B \right)}{P\left(B\right)}. # $$ # # To claim that the triple $S, \mathcal{F}, P\left( ~ \left \vert B \right. \right)$ defined as above is a probability space, we need to verify that the conditional probability measure $P\left( ~ \left \vert B \right. \right)$ **satisfies the axioms** in this probability space: # **1.** Axiom 1 is that the probabilities are non-negative. Let's check: # \begin{eqnarray*} # P(A|B)=\frac{P(A \cap B)}{P(B)}. # \end{eqnarray*} # Note that we are already given that $P(B)>0$, and $P() \ge 0$ for all events in $\mathcal{F}$. Since $\mathcal{F}$ is a $\sigma$-algebra, $A \cap B \in \mathcal{F}$ and so $P(A \cap B) \ge 0$. Thus, $P(A|B)$ is a non-negative quantity divided by a positive quantity, and so $P(A|B) \ge 0$. # # # **2.** Axiom 2 is that the probability of $S$ (the sample space) is 1. Let's check: # # \begin{eqnarray*} # P(S|B)= \frac{P(S \cap B)}{P(B)} = \frac{P(B)}{P(B)} # =1 # \end{eqnarray*} # # **3.** Axiom 3 says that if $A$ and $C$ are mutually exclusive events in $\mathcal{F}$, then the probability of $A \cup C$ is the sum of the probability of $A$ and the probability of $C$. Let's check if this still holds for our conditional probability measure: # # \begin{eqnarray*} # P(A \cup C |B) &=& \frac{ P\left[ \left(A \cup C \right) \cap B \right]}{P[B]} \\ # &=& \frac{ P\left[ \left(A \cap B \right) \cup \left(C \cap B \right) \right]}{P[B]}. # \end{eqnarray*} # Note that $A \cap C = \emptyset \Rightarrow (A\cap B) \cap (C \cap B) = (A\cap C) \cap B =\emptyset$, so # \begin{eqnarray*} # P(A \cup C |B) &=& \frac{ P\left[ A \cap B \right]}{P\left[B\right]} # + \frac{P\left[ C \cap B \right]}{P[B]} \\ # &=& P(A|B) + P(C|B) # \end{eqnarray*} # # # # # The important thing to notice here is that the new conditional probability measure $P(~|B)$ satisifies the axioms with the original sample space and event class -- we are not restricted to applying $P(~|B)$ to those events that lie within the smaller “conditional sample space”, $S_{|B}$ # **Exercise** # # Consider again the problem with five computers in a lab, with sample space denoted by # # $$ # S= \left\{AD, AN, BD_1, BD_2, BN\right\} # $$ # # and events # * $E_A$ is the event that the user's computer is from manufacturer $A$ # * $E_B$ is the event that the user's computer is from manufacturer $B$ # * $E_D$ is the event that the user's computer is defective. # # Use the formula for conditional probability, # # $$ # P(A|B) = \frac{ P(A \cap B)}{B} # $$ # to calculate the probabilities in the problems below. (*It is easier to solve these using intuition/counting, but I encourage you to practice using the formula in the definition, which we will need to use in more complicated scenarios soon.*) Submit your answers as a fraction or a decimal with at least two digits of precision. # + [markdown] tags=[] # ## Terminology Review # # Use the flashcards below to help you review the terminology introduced in this section. # + jupyter={"source_hidden": true} tags=["remove-input"] from jupytercards import display_flashcards github='https://raw.githubusercontent.com/jmshea/Foundations-of-Data-Science-with-Python/main/' github+='06-conditional-prob/flashcards/' display_flashcards(github+'definition.json') # -
06-conditional-prob/definition.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 os import yfinance as yf import psycopg2 as pg from sqlalchemy import create_engine conn = pg.connect(dbname="postgres", user="john") cursor = conn.cursor() select_codes = "select issuer_code from asx_database.listed_companies" cursor.execute(select_codes) codes = cursor.fetchall() for code in codes: try: data = yf.Ticker(code[0] + ".AX") history = data.history(period="max") history.insert(0, 'issuer_code', code[0].upper()) history = history.rename(columns = {'Open':'open_price', 'High':'high_price', 'Low':'low_price', 'Close':'close_price', 'Volume':'daily_volume', 'Dividends':'dividends', 'Stock Splits':'stock_splits'}) history.index.names = ['transaction_date'] engine = create_engine(r'postgresql://john:john@localhost/postgres') conn2 = engine.connect() history.to_sql('daily_price_data', engine, schema='asx_database', if_exists='append') conn2.close() print(code[0] + ".AX", "Data Inserted") except Exception: continue
python/DataProcessing.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 # --- # + # http://scikit-learn.org/stable/modules/decomposition.html # http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html # http://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_vs_lda.html # https://stats.stackexchange.com/questions/134282/relationship-between-svd-and-pca-how-to-use-svd-to-perform-pca # https://intoli.com/blog/pca-and-svd/ # https://github.com/jakevdp/sklearn_tutorial/blob/master/notebooks/04.1-Dimensionality-PCA.ipynb # http://sebastianraschka.com/Articles/2014_python_lda.html#a-comparison-of-pca-and-lda # http://sebastianraschka.com/Articles/2014_pca_step_by_step.html # PCA vs SVD https://math.stackexchange.com/questions/3869/what-is-the-intuitive-relationship-between-svd-and-pca # + # import the Iris dataset from scikit-learn from sklearn.datasets import load_iris # import our plotting module import matplotlib.pyplot as plt # %matplotlib inline # load the Iris dataset iris = load_iris() # - # seperate the features and response variable iris_X, iris_y = iris.data, iris.target # the names of the flower we are trying to predict. iris.target_names # Names of the features iris.feature_names # + # for labelling: {0: 'setosa', 1: 'versicolor', 2: 'virginica'} label_dict = {i: k for i, k in enumerate(iris.target_names)} def plot(X, y, title, x_label, y_label): ax = plt.subplot(111) for label,marker,color in zip( range(3),('^', 's', 'o'),('blue', 'red', 'green')): plt.scatter(x=X[:,0].real[y == label], y=X[:,1].real[y == label], color=color, alpha=0.5, label=label_dict[label] ) plt.xlabel(x_label) plt.ylabel(y_label) leg = plt.legend(loc='upper right', fancybox=True) leg.get_frame().set_alpha(0.5) plt.title(title) # - plot(iris_X, iris_y, "Original Iris Data", "sepal length (cm)", "sepal width (cm)") # + # Calculate a PCA manually # import numpy import numpy as np # calculate the mean vector mean_vector = iris_X.mean(axis=0) print mean_vector # calculate the covariance matrix cov_mat = np.cov((iris_X).T) print cov_mat.shape # - cov_mat # + # calculate the eigenvectors and eigenvalues of our covariance matrix of the iris dataset eig_val_cov, eig_vec_cov = np.linalg.eig(cov_mat) # Print the eigen vectors and corresponding eigenvalues # in order of descending eigenvalues for i in range(len(eig_val_cov)): eigvec_cov = eig_vec_cov[:,i] print 'Eigenvector {}: \n{}'.format(i+1, eigvec_cov) print 'Eigenvalue {} from covariance matrix: {}'.format(i+1, eig_val_cov[i]) print 30 * '-' # - # the percentages of the variance captured by each eigenvalue # is equal to the eigenvalue of that components divided by # the sum of all eigen values explained_variance_ratio = eig_val_cov/eig_val_cov.sum() explained_variance_ratio # + # Scree Plot plt.plot(np.cumsum(explained_variance_ratio)) plt.title('Scree Plot') plt.xlabel('Principal Component (k)') plt.ylabel('% of Variance Explained <= k') # + # store the top two eigenvectors in a variable top_2_eigenvectors = eig_vec_cov[:,:2].T # show the transpose so that each row is a principal component, we have two rows == two components top_2_eigenvectors # - # to transform our data from having shape (150, 4) to (150, 2) # we will multiply the matrices of our data and our eigen vectors together # notice how I am centering the data first. I am doing this to replicate how scikit-learn PCA's algorithm functions np.dot(iris_X, top_2_eigenvectors.T)[:5,] # scikit-learn's version of PCA from sklearn.decomposition import PCA # Like any other sklearn module, we first instantiate the class pca = PCA(n_components=2) # fit the PCA to our data pca.fit(iris_X) pca.components_ # note that the second column is the negative of the manual process # this is because eignevectors can be positive or negative # It should have little to no effect on our machine learning pipelines # sklearn PCA centers the data first while transforming, so these numbers won't match our manual process. pca.transform(iris_X)[:5,] # manually centering our data to match scikit-learn's implementation of PCA np.dot(iris_X-mean_vector, top_2_eigenvectors.T)[:5,] # Plot the original and projected data plot(iris_X, iris_y, "Original Iris Data", "sepal length (cm)", "sepal width (cm)") plt.show() plot(pca.transform(iris_X), iris_y, "Iris: Data projected onto first two PCA components", "PCA1", "PCA2") # + # percentage of variance in data explained by each component # same as what we calculated earlier pca.explained_variance_ratio_ # - # + # show how pca attempts to eliminate dependence between columns # capture all four principal components full_pca = PCA(n_components=4) # fit our PCA to the iris dataset full_pca.fit(iris_X) # show the correlation matrix of the original dataset np.corrcoef(iris_X.T) # - # correlation coefficients above the diagonal np.corrcoef(iris_X.T)[[0, 0, 0, 1, 1], [1, 2, 3, 2, 3]] # average correlation of original iris dataset. np.corrcoef(iris_X.T)[[0, 0, 0, 1, 1], [1, 2, 3, 2, 3]].mean() pca_iris = full_pca.transform(iris_X) # average correlation of PCAed iris dataset. np.corrcoef(pca_iris.T)[[0, 0, 0, 1, 1], [1, 2, 3, 2, 3]].mean() # VERY close to 0 because columns are independent from one another # This is an important consequence of performing an eigen value decomposition # + # import our scaling module from sklearn.preprocessing import StandardScaler # center our data, not a full scaling X_centered = StandardScaler(with_std=False).fit_transform(iris_X) X_centered[:5,] # - # Plot our centered data plot(X_centered, iris_y, "Iris: Data Centered", "sepal length (cm)", "sepal width (cm)") # fit our PCA (with n_components still set to 2) on our centered data pca.fit(X_centered) # same components as before pca.components_ # same projection when data are centered because PCA does this automatically pca.transform(X_centered)[:5,] # Plot PCA projection of centered data, same as previous PCA projected data plot(pca.transform(X_centered), iris_y, "Iris: Data projected onto first two PCA components with centered data", "PCA1", "PCA2") # + # percentage of variance in data explained by each component pca.explained_variance_ratio_ # - # doing a normal z score scaling X_scaled = StandardScaler().fit_transform(iris_X) # Plot scaled data plot(X_scaled, iris_y, "Iris: Data Scaled", "sepal length (cm)", "sepal width (cm)") # fit our 2-dimensional PCA on our scaled data pca.fit(X_scaled) # different components as cenetered data pca.components_ # different projection when data are scaled pca.transform(X_scaled)[:5,] # percentage of variance in data explained by each component pca.explained_variance_ratio_ # Plot PCA projection of scaled data plot(pca.transform(X_scaled), iris_y, "Iris: Data projected onto first two PCA components", "PCA1", "PCA2") # how to interpret and use components pca.components_ # a 2 x 4 matrix first_scaled_flower # Multiply original matrix (150 x 4) by components transposed (4 x 2) to get new columns (150 x 2) np.dot(X_scaled, pca.components_.T)[:5,] # + # extract the first row of our scaled data first_scaled_flower = X_scaled[0] # extract the two PC's first_Pc = pca.components_[0] second_Pc = pca.components_[1] first_scaled_flower.shape # (4,) # same result as the first row of our matrix multiplication np.dot(first_scaled_flower, first_Pc), np.dot(first_scaled_flower, second_Pc) # - # This is how the transform method works in pca pca.transform(X_scaled)[:5,] # + # visualize PCA components # + # cut out last two columns of the original iris dataset iris_2_dim = iris_X[:,2:4] # center the data iris_2_dim = iris_2_dim - iris_2_dim.mean(axis=0) # - plot(iris_2_dim, iris_y, "Iris: Only 2 dimensions", "sepal length", "sepal width") # + # instantiate a PCA of 2 components twodim_pca = PCA(n_components=2) # fit and transform our truncated iris data iris_2_dim_transformed = twodim_pca.fit_transform(iris_2_dim) # - plot(iris_2_dim_transformed, iris_y, "Iris: PCA performed on only 2 dimensions", "PCA1", "PCA2") # + # This code is graphing both the original iris data and the projected version of it using PCA. # Moreover, on each graph, the principal components are graphed as vectors on the data themselves # The longer of the arrows is meant to describe the first principal component and # the shorter of the arrows describes the second principal component def draw_vector(v0, v1, ax): arrowprops=dict(arrowstyle='->',linewidth=2, shrinkA=0, shrinkB=0) ax.annotate('', v1, v0, arrowprops=arrowprops) fig, ax = plt.subplots(2, 1, figsize=(10, 10)) fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1) # plot data ax[0].scatter(iris_2_dim[:, 0], iris_2_dim[:, 1], alpha=0.2) for length, vector in zip(twodim_pca.explained_variance_, twodim_pca.components_): v = vector * np.sqrt(length) # elongdate vector to match up to explained_variance draw_vector(twodim_pca.mean_, twodim_pca.mean_ + v, ax=ax[0]) ax[0].set(xlabel='x', ylabel='y', title='Original Iris Dataset', xlim=(-3, 3), ylim=(-2, 2)) ax[1].scatter(iris_2_dim_transformed[:, 0], iris_2_dim_transformed[:, 1], alpha=0.2) for length, vector in zip(twodim_pca.explained_variance_, twodim_pca.components_): transformed_component = twodim_pca.transform([vector])[0] # transform components to new coordinate system v = transformed_component * np.sqrt(length) # elongdate vector to match up to explained_variance draw_vector(iris_2_dim_transformed.mean(axis=0), iris_2_dim_transformed.mean(axis=0) + v, ax=ax[1]) ax[1].set(xlabel='component 1', ylabel='component 2', title='Projected Data', xlim=(-3, 3), ylim=(-1, 1)) # - # + # LDA is better than PCA for classification # - # calculate the mean for each class # to do this we will separate the iris dataset into three dataframes # one for each flower, then we will take one's mean columnwise mean_vectors = [] for cl in [0, 1, 2]: class_mean_vector = np.mean(iris_X[iris_y==cl], axis=0) mean_vectors.append(class_mean_vector) print label_dict[cl], class_mean_vector # + # Calculate within-class scatter matrix S_W = np.zeros((4,4)) # for each flower for cl,mv in zip([0, 1, 2], mean_vectors): # scatter matrix for every class, starts with all 0's class_sc_mat = np.zeros((4,4)) # for each row that describes the specific flower for row in iris_X[iris_y == cl]: # make column vectors row, mv = row.reshape(4,1), mv.reshape(4,1) # this is a 4x4 matrix class_sc_mat += (row-mv).dot((row-mv).T) # sum class scatter matrices S_W += class_sc_mat S_W # + # calculate the between-class scatter matrix # mean of entire dataset overall_mean = np.mean(iris_X, axis=0).reshape(4,1) # will eventually become between class scatter matrix S_B = np.zeros((4,4)) for i,mean_vec in enumerate(mean_vectors): # number of flowers in each species n = iris_X[iris_y==i,:].shape[0] # make column vector for each specied mean_vec = mean_vec.reshape(4,1) S_B += n * (mean_vec - overall_mean).dot((mean_vec - overall_mean).T) S_B # + # calculate eigenvalues and eigenvectors of S−1W x SB eig_vals, eig_vecs = np.linalg.eig(np.dot(np.linalg.inv(S_W), S_B)) eig_vecs = eig_vecs.real eig_vals = eig_vals.real for i in range(len(eig_vals)): eigvec_sc = eig_vecs[:,i] print 'Eigenvector {}: {}'.format(i+1, eigvec_sc) print 'Eigenvalue {:}: {}'.format(i+1, eig_vals[i]) print # + # keep the top two linear discriminants linear_discriminants = eig_vecs.T[:2] linear_discriminants # - #explained variance ratios eig_vals / eig_vals.sum() # + # LDA projected data lda_iris_projection = np.dot(iris_X, linear_discriminants.T) lda_iris_projection[:5,] # - plot(lda_iris_projection, iris_y, "LDA Projection", "LDA1", "LDA2") from sklearn.discriminant_analysis import LinearDiscriminantAnalysis # + # instantiate the LDA module lda = LinearDiscriminantAnalysis(n_components=2) # fit and transform our original iris data X_lda_iris = lda.fit_transform(iris_X, iris_y) # plot the projected data plot(X_lda_iris, iris_y, "LDA Projection", "LDA1", "LDA2") # - # show that the sklearn components are just a scalar multiplication from the manual components we calculateda for manual_component, sklearn_component in zip(eig_vecs.T[:2], lda.scalings_.T): print sklearn_component / manual_component # same as manual calculations lda.explained_variance_ratio_ # essentially the same as pca.components_, but transposed (4x2 instead of 2x4) lda.scalings_ # fit our LDA to scaled data X_lda_iris = lda.fit_transform(X_scaled, iris_y) lda.scalings_ # different scalings when data are scaled # + # LDA1 is the best axis for SEPERATING the classes # - # fit our LDA to our truncated iris dataset iris_2_dim_transformed_lda = lda.fit_transform(iris_2_dim, iris_y) # project data iris_2_dim_transformed_lda[:5,] # + # different notation components = lda.scalings_.T # transposing to get same usage as PCA. I want the rows to be our components print components np.dot(iris_2_dim, components.T)[:5,] # same as transform method # - np.corrcoef(iris_2_dim.T) # original features are highly correllated # new LDA features are highly uncorrellated, like in PCA np.corrcoef(iris_2_dim_transformed_lda.T) # + # This code is graphing both the original iris data and the projected version of it using LDA. # Moreover, on each graph, the scalings of the LDA are graphed as vectors on the data themselves # The longer of the arrows is meant to describe the first scaling vector and # the shorter of the arrows describes the second scaling vector def draw_vector(v0, v1, ax): arrowprops=dict(arrowstyle='->', linewidth=2, shrinkA=0, shrinkB=0) ax.annotate('', v1, v0, arrowprops=arrowprops) fig, ax = plt.subplots(2, 1, figsize=(10, 10)) fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1) # plot data ax[0].scatter(iris_2_dim[:, 0], iris_2_dim[:, 1], alpha=0.2) for length, vector in zip(lda.explained_variance_ratio_, components): v = vector * .5 draw_vector(lda.xbar_, lda.xbar_ + v, ax=ax[0]) # lda.xbar_ is equivalent to pca.mean_ ax[0].axis('equal') ax[0].set(xlabel='x', ylabel='y', title='Original Iris Dataset', xlim=(-3, 3), ylim=(-3, 3)) ax[1].scatter(iris_2_dim_transformed_lda[:, 0], iris_2_dim_transformed_lda[:, 1], alpha=0.2) for length, vector in zip(lda.explained_variance_ratio_, components): transformed_component = lda.transform([vector])[0] v = transformed_component * .1 draw_vector(iris_2_dim_transformed_lda.mean(axis=0), iris_2_dim_transformed_lda.mean(axis=0) + v, ax=ax[1]) ax[1].axis('equal') ax[1].set(xlabel='lda component 1', ylabel='lda component 2', title='Linear Discriminant Analysis Projected Data', xlim=(-10, 10), ylim=(-3, 3)) # + # notice how the component, instead of going with the variance of the data # goes almost perpendicular to it, its following the seperation of the classes instead # note how its almost parallel with the gap between the flowers on the left and right side # LDA is trying to capture the separation between classes # - from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline from sklearn.model_selection import cross_val_score # + # Create a PCA module to keep a single component single_pca = PCA(n_components=1) # Create a LDA module to keep a single component single_lda = LinearDiscriminantAnalysis(n_components=1) # Instantiate a KNN model knn = KNeighborsClassifier(n_neighbors=3) # - # + # run a cross validation on the KNN without any feature transformation knn_average = cross_val_score(knn, iris_X, iris_y).mean() # This is a baseline accuracy. If we did nothing, KNN on its own achieves a 98% accuracy knn_average # - # %%timeit knn_average = cross_val_score(knn, iris_X, iris_y).mean() # + # create a pipeline that performs PCA pca_pipeline = Pipeline([('pca', single_pca), ('knn', knn)]) pca_average = cross_val_score(pca_pipeline, iris_X, iris_y).mean() pca_average # - # %%timeit cross_val_score(pca_pipeline, iris_X, iris_y).mean() # + lda_pipeline = Pipeline([('lda', single_lda), ('knn', knn)]) lda_average = cross_val_score(lda_pipeline, iris_X, iris_y).mean() # better prediction accuracy than PCA by a good amount, but not as good as original lda_average # - # %%timeit cross_val_score(lda_pipeline, iris_X, iris_y).mean() # + # LDA is much better at creating axes for classification purposes # + # try LDA with 2 components lda_pipeline = Pipeline([('lda', LinearDiscriminantAnalysis(n_components=2)), ('knn', knn)]) lda_average = cross_val_score(lda_pipeline, iris_X, iris_y).mean() # Just as good as using original data lda_average # - # %%timeit cross_val_score(lda_pipeline, iris_X, iris_y).mean() # + # compare our feature transformation tools to a feature selection tool from sklearn.feature_selection import SelectKBest # try all possible values for k, excluding keeping all columns for k in [1, 2, 3]: # make the pipeline select_pipeline = Pipeline([('select', SelectKBest(k=k)), ('knn', knn)]) # cross validate the pipeline select_average = cross_val_score(select_pipeline, iris_X, iris_y).mean() print k, "best feature has accuracy:", select_average # LDA is even better than the best selectkbest # - # %%timeit cross_val_score(select_pipeline, iris_X, iris_y).mean() def get_best_model_and_accuracy(model, params, X, y): grid = GridSearchCV(model, # the model to grid search params, # the parameter set to try error_score=0.) # if a parameter set raises an error, continue and set the performance as a big, fat 0 grid.fit(X, y) # fit the model and parameters # our classical metric for performance print "Best Accuracy: {}".format(grid.best_score_) # the best parameters that caused the best accuracy print "Best Parameters: {}".format(grid.best_params_) # the average time it took a model to fit to the data (in seconds) print "Average Time to Fit (s): {}".format(round(grid.cv_results_['mean_fit_time'].mean(), 3)) # the average time it took a model to predict out of sample data (in seconds) # this metric gives us insight into how this model will perform in real-time analysis print "Average Time to Score (s): {}".format(round(grid.cv_results_['mean_score_time'].mean(), 3)) # + from sklearn.model_selection import GridSearchCV iris_params = { 'preprocessing__scale__with_std': [True, False], 'preprocessing__scale__with_mean': [True, False], 'preprocessing__pca__n_components':[1, 2, 3, 4], # according to scikit-learn docs, max allowed n_components for LDA is number of classes - 1 'preprocessing__lda__n_components':[1, 2], 'clf__n_neighbors': range(1, 9) } # make a larger pipeline preprocessing = Pipeline([('scale', StandardScaler()), ('pca', PCA()), ('lda', LinearDiscriminantAnalysis())]) iris_pipeline = Pipeline(steps=[('preprocessing', preprocessing), ('clf', KNeighborsClassifier())]) # - get_best_model_and_accuracy(iris_pipeline, iris_params, iris_X, iris_y) # + # can't use PCA on sparse data.. # + # http://scikit-learn.org/stable/modules/decomposition.html # https://www.kaggle.com/datasf/case-data-from-san-f # - import pandas as pd hotel_reviews = pd.read_csv('../data/7282_1.csv') hotel_reviews.shape hotel_reviews.head() # + # Let's only include reviews from the US to try to only include english reviews # plot the lats and longs of reviews hotel_reviews.plot.scatter(x='longitude', y='latitude') # + #Filter to only include datapoints within the US hotel_reviews = hotel_reviews[((hotel_reviews['latitude']<=50.0) & (hotel_reviews['latitude']>=24.0)) & ((hotel_reviews['longitude']<=-65.0) & (hotel_reviews['longitude']>=-122.0))] # Plot the lats and longs again hotel_reviews.plot.scatter(x='longitude', y='latitude') # Only looking at reviews that are coming from the US # - hotel_reviews.shape texts = hotel_reviews['reviews.text'] # import the sentence tokenizer from nltk from nltk.tokenize import sent_tokenize sent_tokenize("hello! I am Sinan. How are you??? I am fine") sentences = reduce(lambda x, y:x+y, texts.apply(lambda x: sent_tokenize(str(x).decode('utf-8')))) # the number of sentences len(sentences) # + from sklearn.feature_extraction.text import TfidfVectorizer tfidf = TfidfVectorizer(ngram_range=(1, 2), stop_words='english') tfidf_transformed = tfidf.fit_transform(sentences) tfidf_transformed # + # try to fit PCA PCA(n_components=1000).fit(tfidf_transformed) # + # can't work because it has to calculate a covariance matrix and to do that, the matrix needs to be dense # + # we use another method in sklearn called Truncated SVD # Truncated SVD uses a matrix trick to obtain the same components as PCA (when the data are scaled) # and can work with sparse matrices # components are a not exactly equal but they are up to a very precise decimal from sklearn.decomposition import TruncatedSVD svd = TruncatedSVD(n_components=2) pca = PCA(n_components=2) # check if components of PCA and TruncatedSVD are same for a dataset # by substracting the two matricies and seeing if, on average, the elements are very close to 0 print (pca.fit(iris_X).components_ - svd.fit(iris_X).components_).mean() # not close to 0 # matrices are NOT the same # check if components of PCA and TruncatedSVD are same for a centered dataset print (pca.fit(X_centered).components_ - svd.fit(X_centered).components_).mean() # close to 0 # matrices ARE the same # check if components of PCA and TruncatedSVD are same for a scaled dataset print (pca.fit(X_scaled).components_ - svd.fit(X_scaled).components_).mean() # close to 0 # matrices ARE the same # - (pca.fit(X_centered).components_ - svd.fit(X_centered).components_).mean() svd = TruncatedSVD(n_components=1000) svd.fit(tfidf_transformed) # + # Scree Plot plt.plot(np.cumsum(svd.explained_variance_ratio_)) # 1,000 components captures about 30% of the variance # - # + # latent semantic analysis is a name given to the process of doing an SVD on sparse text document-term matricies # It is done to find latent structure in text for the purposes of classification, clustering, etc # - from sklearn.preprocessing import Normalizer from sklearn.cluster import KMeans # + tfidf = TfidfVectorizer(ngram_range=(1, 2), stop_words='english') svd = TruncatedSVD(n_components=10) normalizer = Normalizer() lsa = Pipeline(steps=[('tfidf', tfidf), ('svd', svd), ('normalizer', normalizer)]) # - lsa.fit(sentences) # + lsa_sentences = lsa.transform(sentences) lsa_sentences.shape # - cluster = KMeans(n_clusters=10) cluster.fit(lsa_sentences) # %%timeit # time it takes to cluster on the original document-term matrix of shape (118151, 280901) cluster.fit(tfidf_transformed) # %%timeit # also time the prediction phase of the Kmeans clustering cluster.predict(tfidf_transformed) # %%timeit # time the time to cluster after latent semantic analysis of shape (118151, 10) cluster.fit(lsa_sentences) # over 80 times faster than fitting on the original tfidf dataset # %%timeit # also time the prediction phase of the Kmeans clustering after LSA was performed cluster.predict(lsa_sentences) # over 4 times faster than predicting on the original tfidf dataset # transform texts to a cluster distance space # each row represents an obsercation cluster.transform(lsa_sentences).shape predicted_cluster = cluster.predict(lsa_sentences) predicted_cluster # Distribution of "topics" pd.Series(predicted_cluster).value_counts(normalize=True) # create DataFrame of texts and predicted topics texts_df = pd.DataFrame({'text':sentences, 'topic':predicted_cluster}) texts_df.head() print "Top terms per cluster:" original_space_centroids = svd.inverse_transform(cluster.cluster_centers_) order_centroids = original_space_centroids.argsort()[:, ::-1] terms = lsa.steps[0][1].get_feature_names() for i in range(10): print "Cluster %d:" % i print ', '.join([terms[ind] for ind in order_centroids[i, :5]]) print lsa.steps[0][1] # # PCA with the Labeled Faces in the Wild (LFW) people dataset # + from sklearn.datasets import fetch_lfw_people import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split from sklearn import decomposition from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from time import time from sklearn.pipeline import Pipeline from sklearn.model_selection import cross_val_score # %matplotlib inline # - # load the dataset # the optional parameter: min_faces_per_person: # will only retain pictures of people that have at least min_faces_per_person different pictures. # the optional parameter: resize is the ratio used to resize the each face picture. lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4) # introspect the images arrays to find the shapes (for plotting) n_samples, h, w = lfw_people.images.shape # for machine learning we use the data directly (as relative pixel # positions info is ignored by this model) X = lfw_people.data y = lfw_people.target n_features = X.shape[1] X.shape # plot one of the faces plt.imshow(X[0].reshape((h, w)), cmap=plt.cm.gray) lfw_people.target_names[y[0]] # plot one of the faces plt.imshow(StandardScaler().fit_transform(X)[0].reshape((h, w)), cmap=plt.cm.gray) lfw_people.target_names[y[0]] # let's plot another face plt.imshow(X[100].reshape((h, w)), cmap=plt.cm.gray) lfw_people.target_names[y[100]] # + # the label to predict is the id of the person target_names = lfw_people.target_names n_classes = target_names.shape[0] print("Total dataset size:") print("n_samples: %d" % n_samples) print("n_features: %d" % n_features) print("n_classes: %d" % n_classes) # - # let's split our dataset into training and testing X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1) # + # Compute a PCA (eigenfaces) on the face dataset n_components = 200 """ from sklearn docs: The optional parameter whiten=True makes it possible to project the data onto the singular space while scaling each component to unit variance. This is often useful if the models down-stream make strong assumptions on the isotropy of the signal: this is for example the case for Support Vector Machines with the RBF kernel and the K-Means clustering algorithm. """ # instantiate the PCA module pca = PCA(n_components=n_components, whiten=True) # create a pipeline called preprocessing that will scale data and then apply PCA preprocessing = Pipeline([('scale', StandardScaler()), ('pca', pca)]) print("Extracting the top %d eigenfaces from %d faces" % (n_components, X_train.shape[0])) # fit the pipeline to the training set preprocessing.fit(X_train) # grab the PCA from the pipeline extracted_pca = preprocessing.steps[1][1] # take the components from the PCA ( just like we did with iris ) # and reshape them to have the same height and weight as the original photos eigenfaces = extracted_pca.components_.reshape((n_components, h, w)) # + # Scree Plot plt.plot(np.cumsum(extracted_pca.explained_variance_ratio_)) # starting at 100 components captures over 90% of the variance compared to the 1,850 original features # + # This function is meant to plot several images in a gallery with given titles def plot_gallery(images, titles, h, w, n_row=3, n_col=4): """Helper function to plot a gallery of portraits""" plt.figure(figsize=(1.8 * n_col, 2.4 * n_row)) plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) for i in range(n_row * n_col): plt.subplot(n_row, n_col, i + 1) plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray) plt.title(titles[i], size=12) plt.xticks(()) plt.yticks(()) # plot the result of the prediction on a portion of the test set def title(y_pred, y_test, target_names, i): pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1] true_name = target_names[y_test[i]].rsplit(' ', 1)[-1] return 'predicted: %s\ntrue: %s' % (pred_name, true_name) eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])] plot_gallery(eigenfaces, eigenface_titles, h, w) plt.show() # - # + # Use a pipeline to make this process easier logreg = LogisticRegression() # create the pipeline face_pipeline = Pipeline(steps=[('preprocessing', preprocessing), ('logistic', logreg)]) # + print "fitting preprocessing pipeline to X_train and transforming X" pca.fit(X_train) X_train_pca = pca.transform(X_train) X_test_pca = pca.transform(X_test) # - import itertools def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints a more readable confusion matrix with heat labels and options for noramlization Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') param_grid = {'C': [1e-2, 1e-1,1e0,1e1, 1e2]} # + # fit without using PCA to see what the difference will be t0 = time() clf = GridSearchCV(logreg, param_grid) clf = clf.fit(X_train, y_train) best_clf = clf.best_estimator_ # Predicting people's names on the test set y_pred = best_clf.predict(X_test) print accuracy_score(y_pred, y_test), "Accuracy score for best estimator" print(classification_report(y_test, y_pred, target_names=target_names)) print plot_confusion_matrix(confusion_matrix(y_test, y_pred, labels=range(n_classes)), target_names) print round((time() - t0), 1), "seconds to grid search and predict the test set" # + # now fit with PCA to see if our accuracy improves t0 = time() clf = GridSearchCV(logreg, param_grid) clf = clf.fit(X_train_pca, y_train) best_clf = clf.best_estimator_ # Predicting people's names on the test set y_pred = best_clf.predict(X_test_pca) print accuracy_score(y_pred, y_test), "Accuracy score for best estimator" print(classification_report(y_test, y_pred, target_names=target_names)) print plot_confusion_matrix(confusion_matrix(y_test, y_pred, labels=range(n_classes)), target_names) print round((time() - t0), 1), "seconds to grid search and predict the test set" # - # + # get a list of predicted names and true names to plot with faces in test set prediction_titles = [title(y_pred, y_test, target_names, i) for i in range(y_pred.shape[0])] # splot a sample of the test set with predicted and true names plot_gallery(X_test, prediction_titles, h, w) # - # + # Create a larger pipeline to gridsearch face_params = {'logistic__C':[1e-2, 1e-1, 1e0, 1e1, 1e2], 'preprocessing__pca__n_components':[100, 150, 200, 250, 300], 'preprocessing__pca__whiten':[True, False], 'preprocessing__lda__n_components':range(1, 7) # [1, 2, 3, 4, 5, 6] recall the max allowed is n_classes-1 } pca = PCA() lda = LinearDiscriminantAnalysis() preprocessing = Pipeline([('scale', StandardScaler()), ('pca', pca), ('lda', lda)]) logreg = LogisticRegression() face_pipeline = Pipeline(steps=[('preprocessing', preprocessing), ('logistic', logreg)]) # - get_best_model_and_accuracy(face_pipeline, face_params, X, y) # + # much better than original data and very fast to predict and train! # - # + # talk about how these transformations are dope BUT they are predefined so we could learn new features # based on training data # these predefined transformations might not work for a particular dataset # PCA is PCA no matter what dataset you choose to work with # -
Chapter06/Ch_6.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 # --- # <h2> ======================================================</h2> # <h1>MA477 - Theory and Applications of Data Science</h1> # <h1>Project 2: Classification Models</h1> # # <h4>Dr. <NAME></h4> # <br> # United States Military Academy, West Point, AY20-2 # <h2>=======================================================</h2> # # <h2> Weight: <font color='red'>100pts</font</h2> # # <h2>Due Date: <font color='red'>March 5th by COB</font</h2> # <hr style="height:3.2px;border:none;color:#333;background-color:#333;" /> # # <h3> Cadet Name:</h3> # <br> # <h3>Date: </h3> # # <br> # # <font color='red' size='3'> <b>$\dots \dots$</b> MY DOCUMENTATION IDENTIFIES ALL SOURCES USED AND ASSISTANCE RECEIVED IN THIS ASSIGNMENT # <br> # # <b>$\dots \dots$ </b> I DID NOT USE ANY SOURCES OR ASSISTANCE REQUIRING DOCUMENATION IN COMPLETING THIS ASSIGNMENT</font> # # <h3> Signature/Initials: </h3> # # <hr style="height:3px;border:none;color:#333;background-color:#333;" /> # <h2>Description of Project</h2> # # In this project you will be working with the <i> Airline Passanger Satisfaction</i> dataset contained in the folder. The dataset contains information of customer satisfaction obtained via a survey that the airline conducted with customers. # # Below is a description of all the different types of information that the airline collected from customers: # # # Gender: Gender of the passengers (Female, Male) # # Customer Type: The customer type (Loyal customer, disloyal customer) # # Age: The actual age of the passengers # # Type of Travel: Purpose of the flight of the passengers (Personal Travel, Business Travel) # # Class: Travel class in the plane of the passengers (Business, Eco, Eco Plus) # # Flight distance: The flight distance of this journey # # Inflight wifi service: Satisfaction level of the inflight wifi service (0:Not Applicable;1-5) # # Departure/Arrival time convenient: Satisfaction level of Departure/Arrival time convenient # # Ease of Online booking: Satisfaction level of online booking # # Gate location: Satisfaction level of Gate location # # Food and drink: Satisfaction level of Food and drink # # Online boarding: Satisfaction level of online boarding # # Seat comfort: Satisfaction level of Seat comfort # # Inflight entertainment: Satisfaction level of inflight entertainment # # On-board service: Satisfaction level of On-board service # # Leg room service: Satisfaction level of Leg room service # # Baggage handling: Satisfaction level of baggage handling # # Check-in service: Satisfaction level of Check-in service # # Inflight service: Satisfaction level of inflight service # # Cleanliness: Satisfaction level of Cleanliness # # Departure Delay in Minutes: Minutes delayed when departure # # Arrival Delay in Minutes: Minutes delayed when Arrival # # Satisfaction: Airline satisfaction level(Satisfaction, neutral or dissatisfaction) # # # # You are provided with two separate sets: `airline_train` which you will use to train your model and `airline_test` which you will use to generate the predictions. Once you generate the predictions, you should save the results on an excel file and submit that to me. # # The project will be broken into two main parts: The <b>Analysis</b> and <b> Best Model</b> portions. # # <h3>Analysis</h3> # # The <b>Analysis</b> portion is worth <b>60pts</b>. # # For this portion of the project you will be evaluated on the overall analysis of the dataset. # # The rough point breakdown is as follows: # # <ul> # <li>A one or two pargraph explaining what the project is about, what are the results, and the methodology: <b>10pts</b></li> # # <li>Thoroughly addressing all the questions and completing all the required tasks: <b>30pts </b></li> # # <li> Creativity and quality of Python code and explanation of the step-by-step code/work:<b> 20pts</b></li> # </ul> # # <h4>Tasks</h4> # # <ul> # <li> Data Preprocessing: Explain how you are handling the missing data, are you scaling the data and why?</li> # # <li> Conduct exploratory analysis, and briefly summarize your observations and findings. Exploring your data using a variety of visual tools counts as part of exploratory analysis.</li> # # <li> Explain how you handled each of the qualitative features. </li> # # <li> What model did you pick and why? Use only among KNN Classifier, Logistic Regression, and Naive Bayes Classifier (or a combination of them)</li> # # <li>Identify the factors that have the highest correlation to a satisfied (or dissatisfied) customer. Explain how you reached your conclusions. </li> # # <li> Obtain a measure of your model's variability and prediction power. Explain your method and results.</li> # # # </ul> # # <font color='red' size=4>Important Remark:</font> For consistency purposes use the following conversion for the response variable: # # $0$ = neutral or dissatisfied # # $1$ = satisfied. # # <h3>Best Model</h3> # # The <b>Best Model</b> portion is worth <b>40pts</b>. # # For this portion you will exclusively be evaluated on the predictive power of your model. In this portion you will be competing with the rest of your peers for the top score. You are required to build a model that has the highest overall accuracy and a model that has the highest recall rate for the dissatisfied customers. Each will be worth 20 points. The brakedown, for each, will be roughly as follows # # # <table> # <tr> # <th>Points</th> # <th>Criteria</th> # # </tr> # <tr> # <td>18-20</td> # <td>Highest Accuracy/Recall</td> # # </tr> # <tr> # <td>16-18</td> # <td>.2 StDevs of highest Accuracy/Recall</td> # # </tr> # <tr> # <td>14-16</td> # <td>.5 StDevs of highest Accuracy/Recall</td> # # </tr> # <tr> # <td>12-14</td> # <td>.75 StDevs of highest Accuracy/Recall</td> # # </tr> # <tr> # <td>10-12</td> # <td>1.25 StDevs of highest Accuracy/Recall</td> # # </tr> # <tr> # <td>9</td> # <td>1.75 StDevs of highest Accuracy/Recall</td> # # </tr> # <tr> # <td>7</td> # <td>2 StDevs of highest Accuracy/Recall</td> # # </tr> # <tr> # <td>5</td> # <td> 2+ StDevs of highest R2 score</td> # # </tr> # </table> # # # There are two instances where there may be significant deviations from the above grading scheme: # # <ul> # <li> If a student's model achieves an Accuracy/Recall that is at least as high as the Accuracy/Recall achieved by the model build by the instructor, then you will automatically get a $20/20$ </li> # <li> If the highest Accuracy/Recall by a student is signigicantly smaller than the Accuracy/Recall achieved by the model built by the instructor, the insturctor reserves the right to assign a max score that is significantly lower than what is stated in the grading scheme above. In this situation the rest of the scores will also be adjusted accordingly.</li> # </ul> # # <h3>How to Submit?</h3> # # All of your work should be done in a single JupyterNotebook. You will submit to me via email a total of three files. One will be the JupyterNotebook which contains your whole work. The second and third files should be excel files containing ONLY the predictions of your model on the test set `airline_test` for both accuracy and recall, respectively. import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt df_train=pd.read_csv('airline_train.csv',index_col=[0]) df_test=pd.read_csv('airline_test.csv',index_col=[0]) df_train.drop("Unnamed: 0.1",axis=1,inplace=True) df_test.drop('Unnamed: 0.1',axis=1,inplace=True) df_train.head() plt.figure(figsize=(12,8)) sns.heatmap(df_test.isnull()==True) df_test.head() test_index_drop=df_test[df_test['Arrival Delay in Minutes'].isnull()==True].index len(test_index_drop) df_test.dropna(inplace=True) plt.figure(figsize=(12,8)) sns.heatmap(df_test.isnull()==True) df_test.shape # First thing we will do is replace the qualitatie target variable by the dummy numerical variables 0 and 1, where satisfied = 1 and dissatisfied or neutral = 0. df_train['satisfaction']=df_train['satisfaction'].apply(lambda x: 1 if x=='satisfied' else 0) df_train.head() df_train.shape # <h2> Exploratory Analysis</h2> # # In what follows we will use visual tools to conduct some exploratory analysis with the hope of gaining some useful insight into our data. # # First, we will check the balance of our target variables. In other words, we want to see whether one category (e.g. satisfied or dissatisfied) is significantly larger than the other. This sort of exploratory analysis is very important because in case we were dealing with an imbalanced dataset then we would need to follow a slightly different approach before building our prediction models. sns.countplot(x='satisfaction',data=df_train) df_train['satisfaction'].value_counts() # + #This function will compute the percentage of each category in our target variable def freq_count(data): cat_0=data.value_counts()[0] cat_1=data.value_counts()[1] return {'perc_0':cat_0/(cat_0+cat_1),'perc_1':cat_1/(cat_0+cat_1)} # - freq_count(df_train['satisfaction']) # We can see that our dataset is more or less balanced. In other words, one category does not completely dominate the other. So, there is no need to perform up-sampling/down-sampling or a combination of the two. # # <h3>Missing Values</h3> # # Next, we will check for missing values. We will however, decide how to deal with them after we have performed some more exploratory analysis so that we can gain a better idea how to imput if necessary. plt.figure(figsize=(12,6)) sns.heatmap(df_train.isnull()==True, cbar=False, yticklabels=False) # Since there are missing values, before we decide what to do with them let's do some more data exploration. # # Specifically, we will see whether there is a difference in the level of sattisfaction between different categories such as: Gender, Customer Type, Type of Travel, and Class df_train.columns sns.set_style('whitegrid') sns.countplot(x='satisfaction',hue='Gender',data=df_train) # There doesn't seem to be an apparent difference in satisfaction between the two genders. In other words, the proportion of males to females is similar in both categories (satisfied vs. dissatisfied/neutral) sns.countplot(x='satisfaction',hue='Customer Type',data=df_train) # Loyal Customers seem to be proportionally distributed between the two categories of satisfaction, while the disloyal customers seem to be significantly more dissatisfied/neutral with the airlines than satisfied. sns.countplot(x='satisfaction',hue='Type of Travel',data=df_train) # Looking at the satisfaction based on the type of travel reveals some insightful information. First off, we should point out that there are significantly more Business Travelers rather than Personal Travelers. Despite this fact, there is a significant difference in teh level of satisfaction between these two categories. For example, the people who were categorized as Personal Travelers are mostly dissatisfied or neutral with the airline. On the other hand, the distinction is much smaller between the Business Travelers: approximately 57% satisfied vs. 43% dissatisfied. While for the personal travelers class, the distinction is much larger: roughly 5% satisfied vs. 95% dissatisfied. # # This observation is very important, and it may make sense to a certain degree as well. sns.countplot(x='Type of Travel',data=df_train) sns.countplot(x='satisfaction',hue='Class',data=df_train) sns.countplot(x='Type of Travel',hue='Class',data=df_train) sns.countplot(x='Type of Travel',data=df_train) # Some observations from the last three plots: First off, we should point out that the majority of the people surveyed were Business Travelers; that is, roughly 70% of the people in our data are Business Travelers. This is important, because we may have a skewed viewpoint when interpreting the results. Specifically, when you combine this with our previous observation that around the 95% of the Personal Travelers were dissatisfied, and around 57% of Business Travelers were satisfied. We just need to be aware of this fact and a bit careful when building our classification model, as the model may very well not be great in distinguishing the satisfaction within the Type of Travel customers. In other words, it may misclassify most of the Personal Travelers who actually were sattisfied (because this subcategory is imbalanced). # # Some other observations: The majority of Business Travelers fly on Business Class, while only a small percentage of Personal Travelers fly Business Class. Similarly, people who fly Economy seem to be equally distributed between the two types of travel: Business vs. Personal # # <h3>Correlation Matrix</h3> # # To get an idea of the correlation of each feature with the response variable as well as with each other, we compute the correlation matrix and display it in a heat-map for better visual representation. plt.figure(figsize=(18,14)) sns.heatmap(df_train.corr(), cmap='coolwarm', annot=True) plt.ylim(0,20) plt.xlim(0,20) # The correlation matrix is quite informative. It appears that some of the factors that have a higher correlation with the customers' sattisfaction are: Online Boarding, Inflight Entertainment, Seat Comfort, On-board Service, Cleanliness, Leg-room Service etc. # # Out of curiosity, let's explore just a bit further, using visual tools, the relationship between the level of satisfaction regarding Online Boarding and the overall level of sattisfaction for customers. plt.figure(figsize=(8,6)) sns.countplot(x='satisfaction',hue='Online boarding',data=df_train) # From this graph we learn that the majority of the customers who had a level of satisfaction of 4 or 5 with online boarding were also overal satisfied with the airline, wheras, the majority of people who had a 3 or lower level of satisfaction with online boarding were dissatisfied or had a neutral stance on the overall satisfaction with the airline. So maybe the airline has to invest a bit more on the online boarding portion! # # Finally, let's do the same anlaysis for the Inflight Entertainment (since this was the other feature with the second highest correlation to the overall satisfaction) plt.figure(figsize=(8,6)) sns.countplot(x='satisfaction',hue='Inflight entertainment',data=df_train) # The story here is very simmilar to the one above. # # <h2>Missing Data</h2> # # First let's check how many rows have at least one missing value. # + def total_missing_rows(frame): missing_rows=[] for col in df_train.columns: missing=df_train[df_train[col].isnull()==True].index if len(missing)>0: missing_rows.append(missing) missing_rows=[x for item in missing_rows for x in item] return missing_rows # - len(total_missing_rows(df_train)) # So, in total, 18786 people are missing at least one value. Now, since we have a bit over 100K datapoints, we could just drop all of these rows and build a model using only the subjects that contain no missing values. # # If we were tasked with building a model for the airline, we would definitely need to experiment with different ways of imputation as well, as dropping a little over 18% of the data may negatively impact the performance of the model. However, for us, mainly due to computational reasons, we will simply drop all the rows that have at least one missing value. df_train.dropna(inplace=True) # ## Qualitative Features # # We will next replace the qualitative features with dummy variables. dummy_col=['Gender','Type of Travel','Customer Type','Class'] df_train=pd.get_dummies(data=df_train,columns=dummy_col,drop_first=True) df_train.drop('id',axis=1,inplace=True) df_train.head() # ## Scaling Data from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split scaler=StandardScaler() X=df_train.drop('satisfaction',axis=1) y=df_train['satisfaction'] scaled=scaler.fit_transform(X) X_sc=pd.DataFrame(scaled,columns=X.columns,index=X.index) X_sc.head() y # ## Validation Set # # Since we have a sufficiently large dataset, we will set aside a validation set that our model will not see. After we tune our model using cross-validation we will check its performance on this validation set. X_train,X_valid, y_train,y_valid=train_test_split(X_sc,y,test_size=0.2,random_state=101) X_train.shape X_valid.shape # ## Model Development # # We will build a few models using Logistic Regression and KNN Classifier and tune the parameters to maximize the accuracy and recall. # # <h3> Logistic Regression</h3> # # For virtually any classification problem, one may always want to use Logistic Regression as a baseline for comparing the performance of other models. # # To tune the model parameters we will use cross-validation score. We will build a modified version of the cross_validate that one finds in sklearn. We will do so primarily so that we can compute directly the recall_score for the class 0 (dissatisfied). # # For Logistic Regression, we will look at both l1 and l2 regularizations and tune the C parameter that controls the strength of the regularization. from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score, KFold, cross_validate from collections import defaultdict from sklearn.metrics import classification_report from sklearn.neighbors import KNeighborsClassifier params={'penalty':['l1','l2'],'C':np.linspace(0.01,5,20)} # + """Here we create an object CrossValidate that will perform cross validation and compute both the accuracy and recall for the pre-specified class """ class CrossValidate(): from sklearn.model_selection import RepeatedKFold from sklearn.metrics import accuracy_score,recall_score, precision_score def __init__(self): self.recall_sc=list() self.accuracy_sc=list() def crossValidation(self,estimator,X,y,n_splits=5,n_repeats=1,random_state=42, pos_label=1): self.model=estimator self.X=X self.y=y self.n_repeats=n_repeats self.n_splits=n_splits self.random_state=random_state self.pos_label=pos_label rkf = RepeatedKFold(n_splits=self.n_splits, n_repeats=self.n_repeats, random_state=self.random_state) # X is the feature set and y is the target for train_index, test_index in rkf.split(X): train=train_index # print("Train:", train_index, "Validation:", test_index) # print('Train:',len(train_index),'Test:',len(test_index),'Total:',len(train_index)+len(test_index)) X_train, X_test = self.X.iloc[train_index], self.X.iloc[test_index] y_train, y_test = self.y.iloc[train_index], self.y.iloc[test_index] self.model.fit(X_train,y_train) pred=self.model.predict(X_test) accuracy=accuracy_score(y_test,pred) self.accuracy_sc.append(accuracy) recall=recall_score(y_test,pred, pos_label=self.pos_label) self.recall_sc.append(recall) # - # Next we perform a search for the best parameters: # + csv=CrossValidate() scoring=defaultdict(list) for reg in ['l1','l2']: for c in np.arange(0.01,5,0.2): csv.crossValidation(LogisticRegression(penalty=reg,C=c,solver='liblinear'),X_train,y_train, n_splits=5,n_repeats=5,random_state=42,pos_label=0) scoring[reg+'recall'].append(np.array(csv.recall_sc).mean()) scoring[reg+'accuracy'].append(np.array(csv.accuracy_sc).mean()) # - # Below we plot both the recall and accuracy scores for both regularizations as a function of the parameter C pd.DataFrame(scoring,index=np.arange(0.01,5,0.2)).plot(ls='--',lw=2,figsize=(16,8)) plt.xticks(np.arange(0.01,5,0.13)) plt.yticks(np.arange(.865,.91,0.002)) plt.xlabel("Regularization Parameter C",fontsize=14) plt.ylabel("Score",fontsize=14) plt.title("Logistic Regression",fontsize=22) plt.legend(fontsize=14) plt.show() # It appears that there is little to no difference between the l1 and l2 regularization. So, next we train our model using the l1 regularization and C=1. lg=LogisticRegression(penalty='l1',C=1, solver='liblinear') lg.fit(X_train,y_train) pred_lg=lg.predict(X_valid) accuracy_score(y_valid,pred_lg) recall_score(y_valid,pred_lg,pos_label=0) # The validation results reflect very closely what we obtained during the cross-validation stage. # ## KNN Classifier # # Next, we build and tune a model using the KNN Classifier # + csv=CrossValidate() scoring_knn=defaultdict(list) for k in range(5,200,20): csv.crossValidation(KNeighborsClassifier(n_neighbors=k),X_train,y_train, n_splits=5,n_repeats=1,random_state=42,pos_label=0) scoring_knn[reg+'recall'].append(np.array(csv.recall_sc).mean()) scoring_knn[reg+'accuracy'].append(np.array(csv.accuracy_sc).mean()) # - pd.DataFrame(scoring_knn,index=range(5,200,20)).plot(ls='--',figsize=(16,8)) plt.xticks(range(5,200,20)) plt.yticks(np.arange(.85,.98,0.005)) plt.xlabel("Number of Neighbors K",fontsize=14) plt.ylabel("Score",fontsize=14) plt.title("KNN Classifier",fontsize=22) plt.legend(fontsize=14) plt.show() # It appears that KNN Classifier may perform better than Logistic Regression. Fortunately we have a way to confirm this as we have set aside a validation set, previously unseen by the model.So, we'll go ahead and train a model with K=25 neighbors and compute the accuracy and recall scores on the validation set. knn=KNeighborsClassifier(n_neighbors=25) knn.fit(X_train,y_train) pred_knn=knn.predict(X_valid) print("validation Accuracy = {:.4f}\n Validation Recall = {:.4f}".format(accuracy_score(y_valid,pred_knn), recall_score(y_valid,pred_knn, pos_label=0))) # The results on the validation set match really closely the results we got during the tuning stage. This adds to our confidence that the model is fairly roboust and we can expect similar results when we submit our predictions on the test set, which also has not been seen by the model before. # # Traininng the KNN Classifier took a long time, so before we make predictions on the test set, we will save the model. Saving the model enables us to reuse it anytime we want in the future without having to retrain the model everytime we close the notebook. # # <h3> Saving the Model with Pickle</h3> import pickle from sklearn.externals import joblib joblib.dump(knn, 'my_knn_model.pkl') # Now that we have saved our model, just for sanity check, let's load it and make predictions on the validation set. We should get the <b>exact</b> results as before. my_model=joblib.load('my_knn_model.pkl') saved_pred=my_model.predict(X_valid) print("Saved Model Accuracy = {:.4f}\n Saved Model Recall = {:.4f}".format(accuracy_score(y_valid,saved_pred), recall_score(y_valid,saved_pred, pos_label=0))) # As expected, we get the exact same accuracy and recall scores on the validation set. Now we can use the saved `my_model` to make predictions on the test set. # ## Making Final Predictions on the Test Set from sklearn.metrics import accuracy_score, recall_score, roc_curve, auc df_valid=pd.read_csv('airline_target.csv', index_col=[0]) df_valid df_valid.drop(test_index_drop,inplace=True) df_valid['target']=df_valid['target'].apply(lambda x: 1 if x=='satisfied' else 0) df_valid.head() df_test.drop('id',axis=1,inplace=True) df_test.head() df_test=pd.get_dummies(data=df_test,columns=dummy_col,drop_first=True) df_test.head() test_sc=scaler.fit_transform(df_test) X_test=pd.DataFrame(test_sc,columns=df_test.columns) X_test.head() # <h3> Using the saved model to make predictions</h3> pred=my_model.predict(X_test) print("Test Accuracy = {:.4f}\n Test Recall = {:.4f}".format(accuracy_score(df_valid,pred), recall_score(df_valid,pred, pos_label=0))) # The take-away here is that the KNN model with 25 neighbors seems to be very robust as there is a great consitency between the results we got from tunning, on the validation set, and the actual test scores. # # Out of curiosity, below we print the whole classification report and also plot the ROC Curve. print(classification_report(df_valid,pred)) pred_prob=my_model.predict_proba(X_test) fp,tp,_=roc_curve(df_valid,pred_prob[:,1]) plt.figure(figsize=(10,7)) plt.plot(fp,tp,'r--',label='AUC: {:.3f}'.format(auc(fp,tp))) plt.xlabel("False Positive Rate",fontsize=14) plt.ylabel("True Positive Rate",fontsize=14) plt.title('KNN Classifier',fontsize=18) plt.legend(loc=5, fontsize=13) plt.show() # ## Conclusion # # From our analysis it appears that some of the features with the highest impact on the overall customer satisfaction are Online Boarding, Inflight Entertainment, Seat Comfort, On-board Service, Cleanliness, Leg-room Service. # # There also appears to be a significant difference in the overall satisfaction based on the Type of Travel and Class. # # Finally, we built a prediction model using KNN Classifier with K=25 neighbors. We achieved an accuracy level of 92% and recall score for the dissatisfied class of 97%. So our model does a pretty good job of not missclassifying the dissatisfied customers.
MA477 - Theory and Applications of Data Science/Homework/Project 2 - Classification Models/Project 2 - Classification Models.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernel_info: # name: python38-azureml # kernelspec: # display_name: Python 3.8 - AzureML # language: python # name: python38-azureml # --- # <h1>Guided Webshell Investigation - MDE Sentinel Enrichments</h1> # <p><b>Notebook Version:</b> 1.0<br> # <b>Python Version:</b> Python 3.6<br> # <b>Data Sources Required:</b> MDE SecurityAlert, W3CIIS Log (or similar web logging)</p> # # <p>This notebook investigates Microsoft Defender for Endpoint (MDE) webshell alerts. The notebook will guide you through steps to collect MDE alerts for webshell activity and link them to server access logs to identify potential attackers.</p> # # <p><b>Configuration Required!</b></p> # <p>This Notebook presumes you have Azure Sentinel Workspace settings configured in a config file. If you do not have this in place please <a href ="https://msticpy.readthedocs.io/en/latest/getting_started/msticpyconfig.html#">read the docs</a> and <a href="https://github.com/Azure/Azure-Sentinel-Notebooks/blob/master/ConfiguringNotebookEnvironment.ipynb">use this notebook</a> to test.</p> # <h2>How to use:</h2> # <p>This notebook provides a step-by-step investigation to understand MDE webshell alerts on your server. While our example uses IIS logging this notebook can be converted to support any web log type.</p> # <p>After congiuration you can investigate two scenarios, a webshell file alert or a webshell command execution alert. For each of these we will need to retrieve different data, the notebook contains branching execution at Step 3 to enable this.</p> # <p>Below you'll find a more detailed description of the two types of investigation</p> # <ul> # <h4><u>Shell File Alert</u></h4> # <p>This alert type will fire when a file that is suspected to be a webshell appears on disk. For this investigation we will start with a known filename that is a suspected shell (e.g. Setconfigure.aspx) and we will try to understand how this webshell was placed on the server.</p> # <h4><u>Shell Command Execution Alert</u></h4> # <p>This alert type will fire when a command is executed on your web server that is suspicious. For this investigation we start with the command line that was executed and the time window that execution took place.</p> # </ul> # <p><b>For both of the above alert types this notebook will allow you to find the following information:</b></p> # <ul> # <li>The attacker IP</li> # <li>The attacker User Agent</li> # <li>The website name the attacker interacted with</li> # <li>The location of the shell on your server</li> # </ul> # <p>Once we have that information this notebook will allow you to investigate the attacker IP, User Agent or both to discover: # <ul> # <li>The files the attacker accessed prior to the installation of the shell</li> # <li>The first time the attacker accessed your server</li> # </ul> # # <hr> # <h1>Notebook Initialization</h1> # <p>This cell: # # <ul> # <li>Checks for the correct Python version</li> # <li>Checks versions and optionally installs required packages</li> # <li>Imports the required packages into the notebook</li> # <li>Sets a number of configuration options.</li> # </ul> # This should complete without errors. If you encounter errors or warnings look at the following two notebooks:</p> # # <ul> # <li><a href="https://github.com/Azure/Azure-Sentinel-Notebooks/blob/master/TroubleShootingNotebooks.ipynb">TroubleShootingNotebooks</a></li> # <li><a href="https://github.com/Azure/Azure-Sentinel-Notebooks/blob/master/ConfiguringNotebookEnvironment.ipynb">ConfiguringNotebookEnvironment</a></li> # </ul> # You may also need to do some additional configuration to successfully use functions such as Threat Intelligence service lookup and Geo IP lookup. See the <a href="https://app.reviewnb.com/Azure/Azure-Sentinel-Notebooks/commit/0ba12819a4bf3d9e1c167ca3b1a9738d6df3be35/#Configuration">Configuration</a> section at the end of the notebook and the <a href="https://github.com/Azure/Azure-Sentinel-Notebooks/blob/master/ConfiguringNotebookEnvironment.ipynb">ConfiguringNotebookEnvironment<a>. # + gather={"logged": 1617840098683} from pathlib import Path from IPython.display import display, HTML REQ_PYTHON_VER = "3.6" REQ_MSTICPY_VER = "1.0.0" update_nbcheck = ( "<p style='color: orange; text-align=left'>" "<b>Warning: we needed to update '<i>utils/nb_check.py</i>'</b><br>" "Please restart the kernel and re-run this cell." "</p>" ) display(HTML("<h3>Starting Notebook setup...</h3>")) if Path("./utils/nb_check.py").is_file(): try: from utils.nb_check import check_versions except ImportError as err: # %xmode Minimal # !curl https://raw.githubusercontent.com/Azure/Azure-Sentinel-Notebooks/master/utils/nb_check.py > ./utils/nb_check.py 2>/dev/null display(HTML(update_nbcheck)) if "check_versions" not in globals(): raise ImportError("Old version of nb_check.py detected - see instructions below.") # %xmode Verbose check_versions(REQ_PYTHON_VER, REQ_MSTICPY_VER) # If not using Azure Notebooks, install msticpy with # # !pip install msticpy from msticpy.nbtools import nbinit nbinit.init_notebook( namespace=globals() ); # + gather={"logged": 1617840102896} import ipywidgets as widgets from ipywidgets import HBox try: pick_time_range = widgets.Dropdown( options=['30d', '60d', '90d'], decription="Time range", disabled=False, ) workspaces_available = WorkspaceConfig().list_workspaces() if not workspaces_available: def_config = WorkspaceConfig() workspaces_available = { def_config["workspace_id"]: def_config["workspace_name"] } target_workspace = widgets.Dropdown( options=workspaces_available.keys(), decription="Workspace") display(HBox([pick_time_range, target_workspace])) except RuntimeError: md("""You do not have any Workspaces configured in your config files. Please run the https://github.com/Azure/Azure-Sentinel-Notebooks/blob/master/ConfiguringNotebookEnvironment.ipynb to setup these files before proceeding""" ,'bold') # + gather={"logged": 1617840261679} # This time period is used to determine how far back the analytic looks, e.g. 1h, 3d, 7d, 1w # If you expereince timeout errors or the notebook is returning too much data, try lowering this time_range = pick_time_range.value workspace_name = target_workspace.value # + gather={"logged": 1617840280001} # Collect Azure Sentinel Workspace Details from our config file and use them to connect import warnings try: # Update to WorkspaceConfig(workspace="WORKSPACE_NAME") to get alerts from a Workspace other than your default one. # Run WorkspaceConfig().list_workspaces() to see a list of configured workspaces ws_config = WorkspaceConfig(workspace=workspace_name) ws_id = ws_config['workspace_id'] ten_id = ws_config['tenant_id'] md("Workspace details collected from config file") with warnings.catch_warnings(): warnings.simplefilter(action="ignore") qry_prov = QueryProvider(data_environment='LogAnalytics') qry_prov.connect(connection_str=ws_config.code_connect_str) except RuntimeError: md("""You do not have any Workspaces configured in your config files. Please run the https://github.com/Azure/Azure-Sentinel-Notebooks/blob/master/ConfiguringNotebookEnvironment.ipynb to setup these files before proceeding""" ,'bold') # + gather={"logged": 1617840287011} # This cell will collect an alert summary to help you decide which investigation to launch alert_summary_query = f''' let timeRange = {time_range}; SecurityAlert | where ProviderName =~ "MDATP" | where DisplayName has_any("Possible IIS web shell", "Possible IIS compromise", "Suspicious processes indicative of a web shell", "A suspicious web script was created", "Possible web shell installation") | extend AlertType = iff(DisplayName has_any("Possible IIS web shell", "Possible IIS compromise", "Suspicious processes indicative of a web shell", "A suspicious web script was created"), "Webshell Command Alerts", "Webshell File Alerts") | summarize count(AlertType) by AlertType | project AlertType, NumberOfAlerts=count_AlertType ''' display(HTML('<h2>Alert Summary</h2><p>The following alert types have been found on your server:')) alertout = qry_prov.exec_query(alert_summary_query) display(alertout) if (not isinstance(alertout, pd.DataFrame)) or alertout.empty: print("No MDE Webshell alerts found.") print("If you think that this is not correct, please check the time range you are using.") # - # <div style="border-left: 6px solid #ccc; border-left-width: 6px; border-left-style: solid; padding: 0.01em 16px; border-color: # #0080ff; background-color:#e6f2ff;"> # <h1>Before you continue!</h1> # <p> Now it's time to select which type of investigation you would like to try. Above we have provided a summary of the high-level alert types present on your server, if the above table is blank no alerts were found.</p> # <p><b><i>If the table is empty, this notebook has no alerts to work with and will produce errors in subsequent cells.</i></b></p> # <p>If you have alerts you have a couple of different options.<br> You can <b>click the links</b> to jump to the start of the investigation. </p> # <p><b><a href="#Step-3:-Begin-File-Investigation">Shell file alert Investigation</a>:</b> If you would like to conduct an investigation into an ASPX file that has been detected by Microsoft Defender ATP please run the code block beneath "Begin File Investigation"<p> # <p><b><a href="#Step-3:-Begin-Command-Investigation">Shell command alert Investigation</a>:</b> If you would like to conduct an investigation into suspicious command execution on your web server please run the code block below "Begin Command Investigation"<p> # </div> # <h2>Step 3: Begin File Investigation</h2> # <p>We can now begin our investigation into a webshell file that has been placed on a system in your network. We'll start by collecting relevant events from MDE.<p> # + # First the notebook collects alerts from MDE with the following query display(HTML('<h3>Collecting relevant alerts from MDE</h3>')) mde_events_query = f''' let timeRange = {time_range}; let scriptExtensions = dynamic([".php", ".jsp", ".js", ".aspx", ".asmx", ".asax", ".cfm", ".shtml"]); SecurityAlert | where TimeGenerated > ago(timeRange) | where ProviderName == "MDATP" | where DisplayName =~ "Possible web shell installation" | extend alertData = parse_json(Entities) | mvexpand alertData | where alertData.Type == "file" | where alertData.Name has_any(scriptExtensions) | extend filename = alertData.Name, directory = alertData.Directory | project TimeGenerated, filename, directory ''' aspx_data = qry_prov.exec_query(mde_events_query) if (not isinstance(aspx_data, pd.DataFrame)) or aspx_data.empty: print("No MDE Webshell alerts found. Please try a different time range.") raise ValueError("No MDE Webshell alerts found. Cannot continue") shells = aspx_data['filename'] # Everything below is presentational pick_shell = widgets.Dropdown( options=shells, decription="Webshells", disabled=False, ) if isinstance(aspx_data, pd.DataFrame) and not aspx_data.empty: display(HTML('<p>Below you can see the filename, the directory it was found in, and the time it was found.</p><p>Please select a webshell to investigate before you continue:</p>')) display(aspx_data) display(pick_shell) display(HTML('<hr>')) display(HTML('<h1>Collect Enrichment Events</h1>')) display(HTML('<p>Now we will enrich this webshell event with additional information before continuing to find the attacker.</p>')) else: md_warn('No relevant alerts were found in your MDE logs, try expanding your timeframe in the config.') # + # Now collect enrichments from the W3CIIS log table dfindex = pick_shell.index filename = aspx_data.loc[[dfindex]]['filename'].values[0] directory = aspx_data.loc[[dfindex]]['directory'].values[0] timegenerated = aspx_data.loc[[dfindex]]['TimeGenerated'].values[0] # Check the directory matches directory_split = directory.split("\\") first_directory = directory_split[-1] # This query will collect file accessed on the server within the same time window iis_query = f''' let scriptExtensions = dynamic([".php", ".jsp", ".js", ".aspx", ".asmx", ".asax", ".cfm", ".shtml"]); W3CIISLog | where TimeGenerated >= datetime("{timegenerated}") - 10s | where TimeGenerated <= datetime("{timegenerated}") + 10s | where csUriStem has_any(scriptExtensions) | extend splitUriStem = split(csUriStem, "/") | extend FileName = splitUriStem[-1] | extend firstDir = splitUriStem[-2] | where FileName == "{filename}" and firstDir == "{first_directory}" | summarize StartTime=min(TimeGenerated), EndTime=max(TimeGenerated) by AttackerIP=cIP, AttackerUserAgent=csUserAgent, SiteName=sSiteName, ShellLocation=csUriStem | order by StartTime asc ''' if isinstance(iis_data, pd.DataFrame) and not iis_data.empty: iis_data = qry_prov.exec_query(iis_query) display(HTML('<div style="border-left: 6px solid #ccc; border-left-width: 6px; border-left-style: solid; padding: 0.01em 16px; border-color:#00cc69; background-color:#e6fff3;"><h3>Enrichment complete!<br> Please <a href="#Step-1:-Find-the-Attacker">click here</a> to continue your investigation.</h3><br></div><hr>')) else: if iis_data.empty: md_warn('No events were found in W3CIISLog') else: md_warn('The query failed, it may have timed out') # - # <h2>Step 3: Begin Command Investigation</h2> # <p>To begin the investigation into a command that has been executed by a webshell on your network, we will begin by collecting MDE data.</p> # + command_investigation_query = f''' let timeRange = {time_range}; let alerts = SecurityAlert | where TimeGenerated > ago(timeRange) | extend alertData = parse_json(Entities), recordGuid = new_guid(); let shellAlerts = alerts | where ProviderName =~ "MDATP" | mvexpand alertData | where alertData.Type == "file" and alertData.Name == "w3wp.exe" | distinct SystemAlertId | join kind=inner (alerts) on SystemAlertId; let alldata = shellAlerts | mvexpand alertData | extend Type = alertData.Type; let filedata = alldata | extend id = tostring(alertData.$id) | extend ImageName = alertData.Name | where Type == "file" and ImageName != "w3wp.exe" | extend imagefileref = id; let commanddata = alldata | extend CommandLine = tostring(alertData.CommandLine) | extend creationtime = tostring(alertData.CreationTimeUtc) | where Type =~ "process" | where isnotempty(CommandLine) | extend imagefileref = tostring(alertData.ImageFile.$ref); let hostdata = alldata | where Type =~ "host" | project HostName = tostring(alertData.HostName), DnsDomain = tostring(alertData.DnsDomain), SystemAlertId | distinct HostName, DnsDomain, SystemAlertId; filedata | join kind=inner ( commanddata ) on imagefileref | join kind=inner (hostdata) on SystemAlertId | project DisplayName, recordGuid, TimeGenerated, ImageName, CommandLine, HostName, DnsDomain ''' cmd_data = qry_prov.exec_query(command_investigation_query) if isinstance(cmd_data, pd.DataFrame) and not cmd_data.empty: display(HTML('''<h2>Step 3.1: Select a command to investigate</h2> <p>Below you will find the suspicious commands that were executed. Matching GUIDs indicate that the events were linked and likely executed within seconds of each other, for the purpose of the investigation you can select either as the default time windows are wide enough to encapsulate both events. There's a full breakdown of the fields below.</p> <ul> <li>DisplayName: The MDE alert display name</li> <li>recordGuid: A GUID used to track previoulsy linked events</li> <li>TimeGenerated: The time the log entry was made</li> <li>ImageName: The executing process image name</li> <li>CommandLine: The command line that was executed</li> <li>HostName: The host name of the impacted machine</li> <li>DnsDomain: The domain of the impacted machine</li> </ul> <p>Note: The GUID generated here will change with each execution and is used only by the notebook.</p>''')) command = cmd_data['recordGuid'] pick_cmd = widgets.Dropdown( options=command, decription="Commands", disabled=False, ) display(HTML('<h3>Select the GUID associated with the command you wish to investigate.</h3>')) display(pick_cmd) display(HTML('<hr><h2>Step 3.2: Execute to Collect Events</h2><p>Please select an access threshold, by default the script will look for files on the server that have been accessed by fewer than 3 IP addresses</p>')) access_threshold = widgets.IntSlider( value=3, min=0, max=15, step=1, decription="Access Threshold", disabled=False, orientation='horizontal', readout=True, readout_format='d' ) display(access_threshold) else: if iis_data.empty: md_warn('No events were found in SecurityAlert. Continuing will result in errors.') else: md_warn('The query failed, it may have timed out. Continuing will result in errors.') # + dfindex = pick_cmd.index imagename = cmd_data.loc[[dfindex]]['ImageName'].values[0] commandline = cmd_data.loc[[dfindex]]['CommandLine'].values[0] creationtime = cmd_data.loc[[dfindex]]['TimeGenerated'].values[0] # Retrieves access to script files on the web server using logs stored in W3CIIS. # Checks for how many unique client IP addresses access the file, uses access_threshold script_data_query = f''' let scriptExtensions = dynamic([".php", ".jsp", ".aspx", ".asmx", ".asax", ".cfm", ".shtml"]); let alldata = W3CIISLog | where TimeGenerated >= datetime("{creationtime}") - 30s | where TimeGenerated <= datetime("{creationtime}") + 30s | where csUriStem has_any(scriptExtensions) | extend splitUriStem = split(csUriStem, "/") | extend FileName = splitUriStem[-1] | extend firstDir = splitUriStem[-2] | summarize StartTime=min(TimeGenerated), EndTime=max(TimeGenerated) by AttackerIP=cIP, AttackerUserAgent=csUserAgent, csUriStem, filename=tostring(FileName), tostring(firstDir) | order by StartTime asc; let fileprev = W3CIISLog | summarize accessCount=dcount(cIP) by csUriStem; alldata | join ( fileprev ) on csUriStem | extend ShellLocation = csUriStem | project-away csUriStem, csUriStem1 | where accessCount <= {access_threshold} ''' aspx_data = qry_prov.exec_query(script_data_query) if isinstance(aspx_data, pd.DataFrame) and not aspx_data.empty: display(HTML('<h2>Step 3.3: File to investigate</h2><p>The files in the drop down below were accessed on the web server (and are therefore in W3CIIS Log) within 30 seconds of the command executing.</p><p>By default the notebook will only show files that have been accessed by a single client IP or UA.</p>')) shells = aspx_data['ShellLocation'] pick_shell = widgets.Dropdown( options=shells, decription="Webshells", disabled=False, ) aspx_data_display = aspx_data aspx_data_display = aspx_data_display.drop(['AttackerIP', 'AttackerUserAgent', 'firstDir', 'EndTime'], axis=1) aspx_data_display.rename(columns={'filename':'ShellName', 'StartTime':'AccessTime'}, inplace=True) display(HTML('Please select which file you would like to investigate:')) #display(aspx_data) display(pick_shell) display(HTML('<hr><h2>Step 3.4: Enrich</h2>')) else: if aspx_data.empty: md_warn('No events were found in W3CIISLog. Continuing will result in errors.') else: md_warn('The query failed, it may have timed out. Continuing will result in errors.') # + if isinstance(aspx_data, pd.DataFrame) and not aspx_data.empty: dfindex = pick_shell.index filename = aspx_data.loc[[dfindex]]['filename'].values[0] timegenerated = aspx_data.loc[[dfindex]]['StartTime'].values[0] #Check the directory matches first_directory = aspx_data.loc[[dfindex]]['firstDir'].values[0] iis_query = f''' let scriptExtensions = dynamic([".php", ".jsp", ".js", ".aspx", ".asmx", ".asax", ".cfm", ".shtml"]); W3CIISLog | where TimeGenerated >= datetime("{timegenerated}") - 30s | where TimeGenerated <= datetime("{timegenerated}") + 30s | where csUriStem has_any(scriptExtensions) | extend splitUriStem = split(csUriStem, "/") | extend FileName = splitUriStem[-1] | extend firstDir = splitUriStem[-2] | where FileName == "{filename}" and firstDir == "{first_directory}" | summarize StartTime=min(TimeGenerated), EndTime=max(TimeGenerated) by AttackerIP=cIP, AttackerUserAgent=csUserAgent, SiteName=sSiteName, ShellLocation=csUriStem | order by StartTime asc ''' iis_data = qry_prov.exec_query(iis_query) else: md_warn('There is no data in an object that should have data. A previous step has likely failed, we cannot continue.') if isinstance(iis_data, pd.DataFrame) and not iis_data.empty: display(HTML('<div style="border-left: 6px solid #ccc; border-left-width: 6px; border-left-style: solid; padding: 0.01em 16px; border-color:#00cc69; background-color:#e6fff3;"><h3>Enrichment complete!<br> Please <a href="#Step-4:-Find-the-Attacker">click here</a> to continue your investigation.</h3><br></div><hr>')) else: if iis_data.empty: md_warn('No events were found in W3CIISLog. Continuing will result in errors.') else: md_warn('The query failed, it may have timed out. Continuing will result in errors.') # - # <h2>Step 4: Find the Attacker</h2> # + attackerip = iis_data['AttackerIP'] attackerua = iis_data['AttackerUserAgent'] pick_ip = widgets.Dropdown( options=attackerip, decription="IP Addresses", disabled=False, ) pick_ua = widgets.Dropdown( options=attackerua, decription="User Agents", disabled=False, ) pick_window = widgets.Dropdown( options=['30m','1h','5h','7h', '1d', '3d','7d'], decription="Window", disabled=False, ) pick_investigation = widgets.Dropdown( options=['Investigate Both', 'Investigate IP','Investigate Useragent'], decription="What should we investigatew?", disabled=False, ) display(HTML('<h2>Candidate Attacker IP Addresses</h2>')) md('The following attacker IP addresses accessed the webshell during the alert window, continue to Step 5 to choose which to investigate.') display(iis_data) display(HTML('<hr><br><h2>Step 5: Select Investigation Parameters</h2>')) display(HTML('<h3>Attacker To Investigate</h3><p>Now it is time to hone in on our attacker. If you have multiple attacker indicators you can repeat from this step.</p><p>Select parameters to investigate, the default selection is the earliest access within the alert window:</p>')) display(HBox([pick_ip, pick_ua, pick_investigation])) widgets.jslink((pick_ip, 'index'), (pick_ua, 'index')) display(HTML('<h3>Previous file access window</h3><p>To determine what files were accessed immediately before the shell, please pick the window we\'ll use to look back:</p>')) display(pick_window) display(HTML('<hr><h2>Step 6: Collect Attacker Enrichments</h2><p>Finally execute the below cell to collect additional details about the attacker.</p>')) # + queryWindow = pick_window.value # Lookback window investigation_param = pick_investigation.index # 0 = both, 1 = ip, 2 = ua dfindex = pick_ip.index # contains dataframe index (int) attackerip = str(pick_ip.value) attackerua = iis_data.loc[[dfindex]]['AttackerUserAgent'].values[0] attackertime = iis_data.loc[[dfindex]]['StartTime'].values[0] sitename = iis_data.loc[[dfindex]]['SiteName'].values[0] shell_location = iis_data.loc[[dfindex]]['ShellLocation'].values[0] access_data = ['',''] first_server_access_data = ['',''] def iis_access_ip(): iis_access_ip = f''' let scriptExtensions = dynamic([".php", ".jsp", ".js", ".aspx", ".asmx", ".asax", ".cfm", ".shtml"]); W3CIISLog | where TimeGenerated >= datetime("{attackertime}") - {queryWindow} | where TimeGenerated <= datetime("{attackertime}") | where sSiteName == "{sitename}" | where cIP == "{attackerip}" | order by TimeGenerated desc | project TimeAccessed=TimeGenerated, SiteName=sSiteName, ServerIP=sIP, FilesTouched=csUriStem, AttackerP=cIP | where FilesTouched has_any(scriptExtensions) | order by TimeAccessed asc ''' #Find the first time the attacker accessed the webserver first_server_access_ip = f''' W3CIISLog | where TimeGenerated > ago(30d) | where sSiteName == "{sitename}" | where cIP == "{attackerip}" | order by TimeGenerated asc | take 1 | project TimeAccessed=TimeGenerated, Site=sSiteName, FileAccessed=csUriStem | order by TimeAccessed asc ''' access_data = qry_prov.exec_query(iis_access_ip) first_server_access_data = qry_prov.exec_query(first_server_access_ip) return access_data, first_server_access_data def iis_access_ua(): iis_access_ua = f''' let scriptExtensions = dynamic([".php", ".jsp", ".js", ".aspx", ".asmx", ".asax", ".cfm", ".shtml"]); W3CIISLog | where TimeGenerated >= datetime("{attackertime}") - {queryWindow} | where TimeGenerated <= datetime("{attackertime}") | where sSiteName == "{sitename}" | where csUserAgent == "{attackerua}" | order by TimeGenerated desc | project TimeAccessed=TimeGenerated, SiteName=sSiteName, ServerIP=sIP, FilesTouched=csUriStem, AttackerP=cIP, AttackerUserAgent=csUserAgent | where FilesTouched has_any(scriptExtensions) | order by TimeAccessed asc ''' #Find the first time the attacker accessed the webserver first_server_access_ua = f''' W3CIISLog | where TimeGenerated > ago(30d) | where sSiteName == "{sitename}" | where csUserAgent == "{attackerua}" | order by TimeGenerated asc | take 1 | project TimeAccessed=TimeGenerated, Site=sSiteName, FileAccessed=csUriStem | order by TimeAccessed asc ''' access_data = qry_prov.exec_query(iis_access_ua) first_server_access_data = qry_prov.exec_query(first_server_access_ua) return access_data, first_server_access_data first_shell_index = None if investigation_param == 1: display(HTML('<p>Querying for attacker IP</p>')) result = iis_access_ip() access_data[0] = result[0] first_server_access_data[0] = result[1] first_shell_index = access_data[0][access_data[0].FilesTouched==shell_location].first_valid_index() elif investigation_param == 2: display(HTML('<p>Querying for attacker UA</p>')) result = iis_access_ua() access_data[1] = result[0] first_server_access_data[1] = result[1] first_shell_index = access_data[1][access_data[1].FilesTouched==shell_location].first_valid_index() elif investigation_param == 0: display(HTML('<p>Querying for attacker IP and UA</p>')) result_ip = iis_access_ip() result_ua = iis_access_ua() access_data[0] = result_ip[0] access_data[1] = result_ua[0] first_server_access_data[0] = result_ip[1] first_server_access_data[1] = result_ua[1] first_shell_index = access_data[0][access_data[0].FilesTouched==shell_location].first_valid_index() first_shell_index_ua = access_data[1][access_data[1].FilesTouched==shell_location].first_valid_index() display(HTML('<div style="border-left: 6px solid #ccc; border-left-width: 6px; border-left-style: solid; padding: 0.01em 16px; border-color:#00cc69; background-color:#e6fff3;"><h3>Enrichment complete!</h3><p>Continue to generate your report</p><br></div><hr><h2>Step 7: Generate Report</h2>')) # + attackerua = attackerua.replace("+", " ") display(HTML(f''' <h2> Attack Summary</h2> <div style="border-left: 6px solid #ccc; border-left-width: 6px; border-left-style: solid; padding: 0.01em 16px; border-color:#1aa3ff; background-color: #f2f2f2;"> <p></p> <p><b>Attacker IP: </b>{attackerip}</p> <p><b>Attacker user agent: </b>{attackerua}</p> <p><b>Webshell installed: </b>{shell_location}</p> <p><b>Victim site: </b>{sitename}</p> <br> </div> ''')) look_back = 0 # No results if first_shell_index is None: first_shell_index = 0 # Our default look back is 5 files, if there are not 5 files we take what we can get elif first_shell_index < 5: look_back = first_shell_index else: look_back = 5 if investigation_param == 1: display(HTML('<h2>File history</h2>')) if first_shell_index > 0: print('The files the attacker IP \"'+attackerip+'\" accessed prior to the webshell installation were:') display(access_data[0][first_shell_index-look_back:first_shell_index+1]) else: print(f'No files were access by the attacker prior to webshell install, try expaning the query window (currently:{queryWindow})') display(HTML('<h2>Earliest access</h2><p>In the last 30 days the earliest known access to the server from the attacker IP was:</p>')) display(first_server_access_data[0]) elif investigation_param == 2: display(HTML('<h2>File history</h2>')) if first_shell_index > 0: print('The files the attacker UA \"'+attackerua+'\" accessed prior to the webshell installation were:') display(access_data[1][first_shell_index-look_back:first_shell_index+1]) else: print(f'No files were access by the attacker prior to webshell install, try expaning the query window (currently:{queryWindow})') display(HTML('<h2>Earliest access</h2><p>In the last 30 days the earliest known access to the server from the attacker UA was:</p>')) display(first_server_access_data[1]) elif investigation_param == 0: look_back_ua = 0 if first_shell_index_ua is None: first_shell_index_ua = 0 elif first_shell_index_ua < 5: look_back_ua = first_shell_index_ua else: look_back_ua = 5 display(HTML('<h2>File history</h2>')) if first_shell_index > 0 or first_shell_index_ua > 0: print('The files the attacker IP \"'+attackerip+'\" accessed prior to the webshell installation were:') display(access_data[0][first_shell_index-look_back:first_shell_index+1]) print('The files the attacker UA \"'+attackerua+'\" accessed prior to the webshell installation were:') display(access_data[1][first_shell_index_ua-look_back_ua:first_shell_index_ua+1]) else: print(f'No files were access by the attacker prior to webshell install, try expanding the query window (currently:{queryWindow})') display(HTML('<h2>Earliest access</h2><p>In the last 30 days the earliest known access to the server from the attacker IP was:</p>')) display(first_server_access_data[0]) display(HTML('<p>In the last 30 days the earliest known access to the server from the attacker UA was:</p>')) display(first_server_access_data[1])
Guided Investigation - MDE Webshell Alerts.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 # --- # ![book](https://raw.githubusercontent.com/ageron/tensorflow-safari-course/master/images/intro_to_tf_course.png) # **Try not to peek at the solutions when you go through the exercises. ;-)** # First let's make sure this notebook works well in both Python 2 and Python 3: from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf tf.__version__ # *__From previous notebooks__* learning_rate = 0.01 momentum = 0.8 # # TensorBoard # ## Exercise 6 # ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) # In this exercise, you will learn to use TensorBoard. It is a great visualization tool that comes with TensorFlow. It works by parsing special TensorFlow logs, called _summaries_, and displaying them nicely. # 6.1) Starting the TensorBoard server. Open a Terminal and type the following commands. # Move to the `tensorflow-safari-course` directory: # `~$` **`cd tensorflow-safari-course`** # Create the `tf_logs` directory that will hold the TensorFlow data that we will want TensorBoard to display: # `~/tensorflow-safari-course$` **`mkdir tf_logs`** # Activate the virtual environment: # `~/tensorflow-safari-course$` **`source env/bin/activate`** # Start the TensorBoard server: # `(env) ~/tensorflow-safari-course$` **`tensorboard --logdir=tf_logs`** # # `Starting TensorBoard b'41' on port 6006 # (You can navigate to` http://127.0.1.1:6006 `)` # Now visit the URL given by TensorBoard. You should see the TensorBoard interface. # 6.2) Now create a `tf.summary.FileWriter`, with the parameters: `logdir="tf_logs/run_number_1/"` and `graph=graph` where `graph` is the one we built just before this exercise. This will automatically: # * create the `run_number_1` directory inside the `tf_logs` directory, # * create an `events.out.tfevents.*` file in that subdirectory that will contain the data that TensorBoard will display, # * write the graph's definition to this file. # # Next, try refreshing the TensorBoard page in your browser (you may need to wait a couple minutes for it to detect the change, or else you can just restart the TensorBoard server). Visit the Graph tab: you should be able to visualize the graph. # 6.3) As you can see, the graph looks really messy in TensorBoard. We need to organize it a bit. For this, name scopes come in handy. An operation can be placed inside a name scope in one of two ways: # # * Add the scope as a prefix to the operation's name, for example: # # ```python # a = tf.constant(0.0, name="my_name_scope/a") # ``` # # * Or (generally clearer) use a `tf.name_scope()` block, for example: # # ```python # with tf.name_scope("my_name_scope"): # a = tf.constant(0.0, name="a") # ``` # # Add name scopes to the following graph, then write it to TensorBoard (using a different run number for the log directory name) and see how much better it looks, and how much easier it is to explore. # + filenames = ["data/life_satisfaction.csv"] n_epochs = 500 batch_size = 5 graph = tf.Graph() with graph.as_default(): reader = tf.TextLineReader(skip_header_lines=1) filename_queue = tf.train.string_input_producer(filenames, num_epochs=n_epochs) record_id, record = reader.read(filename_queue) record_defaults = [[''], [0.0], [0.0]] country, gdp_per_capita, life_satisfaction = tf.decode_csv(record, record_defaults=record_defaults) X_batch, y_batch = tf.train.batch([gdp_per_capita, life_satisfaction], batch_size=batch_size) X_batch_reshaped = tf.reshape(X_batch, [-1, 1]) y_batch_reshaped = tf.reshape(y_batch, [-1, 1]) X = tf.placeholder_with_default(X_batch_reshaped, shape=[None, 1], name="X") y = tf.placeholder_with_default(y_batch_reshaped, shape=[None, 1], name="y") b = tf.Variable(0.0, name="b") w = tf.Variable(tf.zeros([1, 1]), name="w") y_pred = tf.add(tf.matmul(X / 10000, w), b, name="y_pred") # X @ w + b mse = tf.reduce_mean(tf.square(y_pred - y), name="mse") global_step = tf.Variable(0, trainable=False, name='global_step') optimizer = tf.train.MomentumOptimizer(learning_rate, momentum) training_op = optimizer.minimize(mse, global_step=global_step) init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) saver = tf.train.Saver() # - # 6.4) Print out the name of a few operations. Notice how the names now have the scope as a prefix. # 6.5) TensorBoard is capable of displaying data from multiple TensorFlow runs (for example multiple training sessions). For this, we need to place the data from each run in a different subdirectory of the `tf_logs` directory. We can name these subdirectories however we want, but a simple option is to name them using a timestamp. The following `logdir()` function returns the path of a subdirectory whose name is based on the current date and time: # + from datetime import datetime def logdir(): root_logdir = "tf_logs" now = datetime.utcnow().strftime("%Y%m%d%H%M%S") return "{}/run_{}/".format(root_logdir, now) # - logdir() # Create a few different graphs and instantiate a different FileWriter for each one, using a different log directory every time (with the help of the `logdir()` function). Refresh TensorBoard and notice that you can browse any graph you want by selecting the appropriate run. # 6.6) Now we will use TensorBoard to visualize the learning curve, that is the evolution of the cost function during training. # # * First add a scalar summary operation in the graph, using `tf.summary.scalar("MSE", mse)`. # * Next, update the training code to evaluate this scalar summary and write the result to the events file using the `FileWriter`'s `add_summary()` method (also specifying the training step). For performance reasons, you probably want to do this only every 10 training iterations or so. # * Next, train the model. # * Refresh TensorBoard, and visit the Scalars tab. Select the appropriate run and visualize the learning curve. Try zooming in and out, and play around with the options, in particular the smoothing option. # Try not to peek at the solution below before you have done the exercise! :) # ![thinking](https://upload.wikimedia.org/wikipedia/commons/0/06/Filos_segundo_logo_%28flipped%29.jpg) # ## Exercise 6 - Solution # 6.1) # # N/A # 6.2) summary_writer = tf.summary.FileWriter("tf_logs/run_number_1_solution/", graph=graph) # 6.3) # + filenames = ["data/life_satisfaction.csv"] n_epochs = 500 batch_size = 5 graph = tf.Graph() with graph.as_default(): with tf.name_scope("reader"): reader = tf.TextLineReader(skip_header_lines=1) filename_queue = tf.train.string_input_producer(filenames, num_epochs=n_epochs) record_id, record = reader.read(filename_queue) record_defaults = [[''], [0.0], [0.0]] country, gdp_per_capita, life_satisfaction = tf.decode_csv(record, record_defaults=record_defaults) X_batch, y_batch = tf.train.batch([gdp_per_capita, life_satisfaction], batch_size=batch_size) X_batch_reshaped = tf.reshape(X_batch, [-1, 1]) y_batch_reshaped = tf.reshape(y_batch, [-1, 1]) with tf.name_scope("linear_model"): X = tf.placeholder_with_default(X_batch_reshaped, shape=[None, 1], name="X") y = tf.placeholder_with_default(y_batch_reshaped, shape=[None, 1], name="y") b = tf.Variable(0.0, name="b") w = tf.Variable(tf.zeros([1, 1]), name="w") y_pred = tf.add(tf.matmul(X / 10000, w), b, name="y_pred") # X @ w + b with tf.name_scope("train"): mse = tf.reduce_mean(tf.square(y_pred - y), name="mse") global_step = tf.Variable(0, trainable=False, name='global_step') optimizer = tf.train.MomentumOptimizer(learning_rate, momentum) training_op = optimizer.minimize(mse, global_step=global_step) init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) saver = tf.train.Saver() # - summary_writer = tf.summary.FileWriter("tf_logs/run_number_2_solution/", graph=graph) # 6.4) country.name, gdp_per_capita.name, X_batch.name, y_batch.name X.name, y.name, b.name, w.name, y_pred.name mse.name, global_step.name, training_op.name # 6.5) graph1 = tf.Graph() with graph1.as_default(): a = tf.constant(1.0) summary_writer = tf.summary.FileWriter(logdir(), graph=graph) graph2 = tf.Graph() with graph2.as_default(): a = tf.constant(1.0, name="a") b = tf.Variable(2.0, name="b") c = a * b # If we run `logdir()` twice within the same second, we will get the same directory name twice. To avoid this, let's wait a bit over 1 second here. In real life, this is quite unlikely to happen since training a model typically takes much longer than 1 second. import time time.sleep(1.1) summary_writer = tf.summary.FileWriter(logdir(), graph=graph) time.sleep(1.1) # 6.6) # + filenames = ["data/life_satisfaction.csv"] n_epochs = 500 batch_size = 5 graph = tf.Graph() with graph.as_default(): with tf.name_scope("reader"): reader = tf.TextLineReader(skip_header_lines=1) filename_queue = tf.train.string_input_producer(filenames, num_epochs=n_epochs) record_id, record = reader.read(filename_queue) record_defaults = [[''], [0.0], [0.0]] country, gdp_per_capita, life_satisfaction = tf.decode_csv(record, record_defaults=record_defaults) X_batch, y_batch = tf.train.batch([gdp_per_capita, life_satisfaction], batch_size=batch_size) X_batch_reshaped = tf.reshape(X_batch, [-1, 1]) y_batch_reshaped = tf.reshape(y_batch, [-1, 1]) with tf.name_scope("linear_model"): X = tf.placeholder_with_default(X_batch_reshaped, shape=[None, 1], name="X") y = tf.placeholder_with_default(y_batch_reshaped, shape=[None, 1], name="y") b = tf.Variable(0.0, name="b") w = tf.Variable(tf.zeros([1, 1]), name="w") y_pred = tf.add(tf.matmul(X / 10000, w), b, name="y_pred") with tf.name_scope("train"): mse = tf.reduce_mean(tf.square(y_pred - y), name="mse") mse_summary = tf.summary.scalar('MSE', mse) # <= ADDED global_step = tf.Variable(0, trainable=False, name='global_step') optimizer = tf.train.MomentumOptimizer(learning_rate, momentum) training_op = optimizer.minimize(mse, global_step=global_step) init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) saver = tf.train.Saver() # - summary_writer = tf.summary.FileWriter(logdir(), graph) with tf.Session(graph=graph) as sess: init.run() coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) try: while not coord.should_stop(): _, mse_summary_val, global_step_val = sess.run([training_op, mse_summary, global_step]) if global_step_val % 10 == 0: summary_writer.add_summary(mse_summary_val, global_step_val) except tf.errors.OutOfRangeError: print("End of training") coord.request_stop() coord.join(threads) saver.save(sess, "./my_life_satisfaction_model")
07_tensorboard_ex6.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.8.0-DEV # language: julia # name: julia-1.8 # --- cd("..") # + import Pkg Pkg.activate(".") # - import Wordle: play, candidate_pool import Statistics: mean import Printf: @printf import ProgressMeter: @showprogress import Plots: histogram function print_stats(weights, step_counts) @printf("Weights = %s\n", weights) @printf("Mean Step Counts = %f\n", mean(step_counts)) for i in 1:10 @printf("P(Step Counts <= %d) = %f\n", i, mean(step_counts .<= i)) end end const ALL_WORDS = candidate_pool(true) const ALL_WEIGHTS = ( [1 / 3, 1 / 3, 1 / 3], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ) # + step_counts = fill(0, length(ALL_WORDS), length(ALL_WEIGHTS)) for (j, weights) in enumerate(ALL_WEIGHTS) @showprogress for (i, word) in enumerate(ALL_WORDS) steps = play(String(word), weights = weights) step_counts[i, j] = steps end print_stats(weights, step_counts[:, j]) println() end # - histogram(step_counts[:, 1]) histogram(step_counts[:, 2]) histogram(step_counts[:, 3]) histogram(step_counts[:, 4])
notebooks/Experiment.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.4 64-bit (''qgl'': conda)' # name: python3 # --- from QGL import * from nist_APS2_converter import convert import json import numpy as np # + #ChannelLibrary setup # cl = ChannelLibrary("NIST") # q1 = cl.new_qubit("q1") # q2 = cl.new_qubit("q2") # aps2_1 = cl.new_APS2("BBNAPS2_1", address="192.168.2.2") # aps2_2 = cl.new_APS2("BBNAPS2_2", address="192.168.2.3") # aps2_3 = cl.new_APS2("BBNAPS2_3", address="192.168.2.4") # aps2_4 = cl.new_APS2("BBNAPS2_4", address="192.168.2.5") # aps2_5 = cl.new_APS2("BBNAPS2_5", address="192.168.2.6") # aps2_6 = cl.new_APS2("BBNAPS2_6", address="192.168.2.7") # dig = cl.new_Alazar("Alazar", address=0) # TDM = cl.new_TDM("TDM", address="192.168.2.11") # cl.set_control(q1, aps2_1) # cl.set_control(q2, aps2_2) # cl.commit() # + #ChannelLibrary load cl = ChannelLibrary("NIST") q1 = cl["q1"] q2 = cl["q2"] # - seq1 = [[Utheta(q1, length=l, amp=1, frequency=15e6, shape_fun='constant')*Id(q2)] for l in np.linspace(10e-6, 20e-6, 11)] mf = compile_to_hardware(seq1, 'Test1') plot_pulse_files(mf) # + with open(mf) as f: seqFile = json.load(f) for seq in list(seqFile['instruments'].values()): convert(seq)
pulseShaping/aps2Test.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 # --- # # "50 startups." # ### _"Predict which companies to invest for maximizing profit" (Regression task)._ # ## Table of Contents # # # ## Part 0: Introduction # # ### Overview # The dataset that's we see here contains data about 50 startups. It has 7 columns: “ID”, “R&D Spend”, “Administration”, “Marketing Spend”, “State”, “Category” “Profit”. # # # **Метаданные:** # # * **ID** - startup ID # # * **R&D Spend** - how much each startup spends on Research and Development # # * **Administration** - how much they spend on Administration cost # # * **Marketing Spend** - how much they spend on Marketing # # * **State** - which state the startup is based in # # * **Category** - which business category the startup belong to # # * **Profit** - the profit made by the startup # # # ### Questions: # # # * #### Predict which companies to invest for maximizing profit (choose model with the best score; create predictions; choose companies) # # # ## [Part 1: Import, Load Data](#Part-1:-Import,-Load-Data.) # * ### Import libraries, Read data from ‘.csv’ file # # ## [Part 2: Exploratory Data Analysis](#Part-2:-Exploratory-Data-Analysis.) # * ### Info, Head # * ### Observation of target variable (describe + visualisation:distplot) # * ### Numerical and Categorical features # * #### List of Numerical and Categorical features # * ### Missing Data # * #### List of data features with missing values # * #### Filling missing values # * ### Numerical and Categorical features # * #### Visualisation of Numerical and categorical features (regplot + barplot) # # ## [Part 3: Data Wrangling and Transformation](#Part-3:-Data-Wrangling-and-Transformation.) # * ### One-Hot Encoding # * ### Standard Scaler (optional) # * ### Creating datasets for ML part # * ### 'Train\Test' splitting method # # ## [Part 4: Machine Learning](#Part-4:-Machine-Learning.) # * ### ML Models (Linear regression, Gradient Boosting Regression) # * ### Build, train, evaluate and visualise models # * ### Creating final predictions with Test set # * ### Model comparison # # # ## [Conclusion](#Conclusion.) # * ### Submission of ‘.csv’ file with predictions # ## Part 1: Import, Load Data. # * ### Import # + # import standard libraries import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import pylab as pl from scipy import stats # import models and metrics from sklearn import metrics, linear_model, model_selection from sklearn.metrics import r2_score, mean_squared_error, mean_squared_log_error, mean_absolute_error from sklearn.model_selection import cross_val_score from sklearn.linear_model import LinearRegression from sklearn.ensemble import GradientBoostingRegressor # - # * ### Load Data # + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" # read data from '.csv' files train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") # identify target target = train['Profit'] # - # ## Part 2: Exploratory Data Analysis. # * ### Info # print the full summary of the Train dataset train.info() # print the full summary of the Test dataset test.info() # * ### Head # preview of the first 5 lines of the loaded Train data train.head() # preview of the first 5 lines of the loaded Test data test.head() # * ### Observation of target variable # target variable train['Profit'].describe() # visualisation of 'Profit' distribution sns.distplot(train['Profit'], color='b') # set 'ID' to index train = train.set_index('ID') test = test.set_index('ID') # * ### Numerical and Categorical features # #### List of Numerical and Categorical features # check for Numerical and Categorical features in Train numerical_feats_train = train.dtypes[train.dtypes != 'object'].index print ('Quantity of Numerical features: ', len(numerical_feats_train)) print () print (train[numerical_feats_train].columns) print () categorical_feats_train = train.dtypes[train.dtypes == 'object'].index print ('Quantity of Categorical features: ', len(categorical_feats_train)) print () print (train[categorical_feats_train].columns) # * ### Missing values # #### List of data features with missing values # check the Train features with missing values nan_columns = [i for i in train.columns if train[i].isnull().any()] print(train.isnull().sum()) print() print("There are " + str(len(nan_columns)) +" columns with NAN values for 50 rows.") nan_columns # check the Test features with missing values nan_columns = [i for i in test.columns if test[i].isnull().any()] print(test.isnull().sum()) print() print("There are " + str(len(nan_columns)) +" columns with NAN values for 50 rows.") nan_columns # #### Filling missing values # Fields where NAN values have meaning. # # Explaining in further depth: # # * 'R&D Spend': Numerical - replacement of NAN by 'mean'; # * 'Administration': Numerical - replacement of NAN by 'mean'; # * 'Marketing Spend': Numerical - replacement of NAN by 'mean'; # * 'State': Categorical - replacement of NAN by 'None'; # * 'Category': Categorical - replacement of NAN by 'None'. # + # Numerical NAN columns to fill in Train and Test datasets nan_columns_fill = [ 'R&D Spend', 'Administration', 'Marketing Spend' ] # replace 'NAN' with 'mean' in these columns train.fillna(train.mean(), inplace = True) test.fillna(test.mean(), inplace = True) # Categorical NAN columns to fill in Train and Test datasets na_columns_fill = [ 'State', 'Category' ] # replace 'NAN' with 'None' in these columns for col in na_columns_fill: train[col].fillna('None', inplace=True) test[col].fillna('None', inplace=True) # - # check is there any mising values left in Train train.isnull().sum().sum() # check is there any mising values left in Test test.isnull().sum().sum() # #### Visualisation of Numerical features (regplot) # + # numerical features visualisation nr_rows = 2 nr_cols = 2 fig, axs = plt.subplots(nr_rows, nr_cols, figsize=(nr_cols*3.5,nr_rows*3)) num_feats = list(numerical_feats_train) not_plot = ['Id', 'Profit'] plot_num_feats = [c for c in list(numerical_feats_train) if c not in not_plot] for r in range(0,nr_rows): for c in range(0,nr_cols): i = r*nr_cols + c if i < len(plot_num_feats): sns.regplot(train[plot_num_feats[i]], train['Profit'], ax = axs[r][c], color = "#5081ac" ) stp = stats.pearsonr(train[plot_num_feats[i]], train['Profit']) str_title = "r = " + "{0:.2f}".format(stp[0]) + " " "p = " + "{0:.2f}".format(stp[1]) axs[r][c].set_title(str_title, fontsize=11) plt.tight_layout() plt.show() # - # categorical features visualisation # 'Profit' split in 'State' level sns.barplot(x = 'State', y = 'Profit', data = train, palette = "Blues_d") # categorical features visualisation # 'Profit' split in 'Category' level sns.barplot(x = 'Category', y = 'Profit', data = train, palette = "Blues_d") plt.xticks(rotation=90) # ## Part 3: Data Wrangling and Transformation. # * ### One-Hot Encoding # + # One-Hot Encoding Train dataset train = pd.get_dummies(train,columns=['State', 'Category']) # Drop target variable train = train.drop(columns=['Profit']) # - # preview of the first 5 lines of the loaded Train data train.head() # Train data shape train.shape # One Hot-Encoding Test dataset test = pd.get_dummies(test,columns=['State', 'Category']) # preview of the first 5 lines of the loaded Test data test.head() # Test data shape test.shape # Drop unnecessary variables train = train.drop(columns=['Category_None']) test = test.drop(columns=['State_None']) # * ### StandardScaler # + #from sklearn.preprocessing import StandardScaler #sc = StandardScaler() #sc_train = sc.fit_transform(train) #sc_test = sc.transform(test) #sc_train = pd.DataFrame(sc_train) #sc_train.head() #sc_test = pd.DataFrame(sc_test) #sc_test.head() # - # * ### Creating datasets for ML part # + # set 'X' for features of scaled Train dataset 'sc_train' #X = sc_train # set 'y' for the target 'Profit' #y = target # 'X_Test' for features of scaled Test dataset 'sc_test' #X_Test = sc_test # set 'X' for features of scaled Train dataset 'sc_train' X = train # set 'y' for the target 'Profit' y = target # 'X_Test' for features of scaled Test dataset 'sc_test' X_Test = test # - # * ### 'Train\Test' split from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0) X_train.shape X_test.shape # ## Part 4: Machine Learning. # * ### Build, train, evaluate and visualise models # * #### Linear Regression # + # Linear Regression model LR = LinearRegression() # Model Training LR.fit(X_train,y_train) # Model Prediction LR_pred = LR.predict(X_test) LR_pred # - # Model R2 score LRscore = LR.score(X_test, y_test) # + # Model Metrics LRMetrics = pd.DataFrame({'Model': 'Linear Regression', 'r2score':r2_score(y_test,LR_pred), 'MAE': metrics.mean_absolute_error (y_test,LR_pred), 'MSE': metrics.mean_squared_error(y_test,LR_pred), 'RMSE': np.sqrt(metrics.mean_squared_error(y_test,LR_pred)), 'MSLE': metrics.mean_squared_log_error(y_test,LR_pred), 'RMSLE':np.sqrt(metrics.mean_squared_log_error(y_test,LR_pred)) },index=[1]) LRMetrics # + # visualisation of Train dataset predictions # Plot outputs plt.figure(figsize=(8,5)) pl.plot(y_test, LR_pred,'ro') pl.plot([0,200000],[0,200000],'b-') pl.xlabel('Predicted Profit') pl.ylabel('Profit') pl.show() # - # Test final predictions LR_pred1 = LR.predict(X_Test) LR_pred1 # + # Model Metrics LRMetrics1 = pd.DataFrame({'Model': 'Linear Regression', 'r2score':r2_score(y,LR_pred1), 'MAE': metrics.mean_absolute_error (y,LR_pred1), 'MSE': metrics.mean_squared_error(y,LR_pred1), 'RMSE': np.sqrt(metrics.mean_squared_error(y,LR_pred1)), 'MSLE': metrics.mean_squared_log_error(y,LR_pred1), 'RMSLE':np.sqrt(metrics.mean_squared_log_error(y,LR_pred1)) },index=[1]) LRMetrics1 # + # visualisation of Test dataset predictions # Plot outputs plt.figure(figsize=(8,5)) pl.plot(y, LR_pred1,'ro') pl.plot([0,200000],[0,200000],'b-') pl.xlabel('Predicted Profit') pl.ylabel('Profit') pl.show() # - # comparison between Actual 'Profit' from Train dataset abd Predicted 'Profit' from Test dataset actualvspredicted = pd.DataFrame({"Actual Profit":y,"LR Predicted Profit":LR_pred1 }) actualvspredicted.head(10).style.background_gradient(cmap='Blues') # * #### Gradient Boosting Regressor # + # Gradient Boosting Regressor model GB=GradientBoostingRegressor(random_state=0) # Model Training GB.fit(X_train,y_train) # Model Prediction GB_pred = GB.predict(X_test) # Model R2 score GBscore =GB.score(X_test, y_test) # + # Model Metrics GBMetrics = pd.DataFrame({'Model': 'Gradient Boosting Regressor', 'r2score':r2_score(y_test,GB_pred), 'MAE': metrics.mean_absolute_error (y_test,GB_pred), 'MSE': metrics.mean_squared_error(y_test,GB_pred), 'RMSE': np.sqrt(metrics.mean_squared_error(y_test,GB_pred)), 'MSLE': metrics.mean_squared_log_error(y_test,GB_pred), 'RMSLE':np.sqrt(metrics.mean_squared_log_error(y_test,GB_pred)) },index=[2]) GBMetrics # - # Test final predictions GB_pred1 = GB.predict(X_Test) # + # Model Metrics GBMetrics1 = pd.DataFrame({'Model': 'GradientBoostingRegressor', 'r2score':r2_score(y,GB_pred1), 'MAE': metrics.mean_absolute_error (y,GB_pred1), 'MSE': metrics.mean_squared_error(y,GB_pred1), 'RMSE': np.sqrt(metrics.mean_squared_error(y,GB_pred1)), 'MSLE': metrics.mean_squared_log_error(y,GB_pred1), 'RMSLE':np.sqrt(metrics.mean_squared_log_error(y,GB_pred1)) },index=[1]) GBMetrics1 # + # visualisation of Test dataset predictions # Plot outputs plt.figure(figsize=(8,5)) pl.plot(y, GB_pred1,'ro') pl.plot([0,200000],[0,200000], 'b-') pl.xlabel('Predicted Profit') pl.ylabel('Profit') pl.show() # - # ### Model comparison # score comparison of models frames = [LRMetrics1,GBMetrics1] TrainingResult = pd.concat(frames) TrainingResult # comparison between Actual 'Profit' from Train dataset abd Predicted 'Profit' from Test dataset actualvspredicted = pd.DataFrame({"Actual Profit":y,"LR Predicted Profit":LR_pred1, "GB Predicted Profit":GB_pred1}) actualvspredicted.head(10).style.background_gradient(cmap='Blues') # **Result**: The best model is **Gradient Boosting Regressor** with **R2 score = 0.972002**. # ## Conclusion. # submission of .csv file with final predictions sub = pd.DataFrame() sub['ID'] = test.index sub['Profit'] = GB_pred1 sub.to_csv('StartupPredictions.csv', index=False)
ML-101 Modules/Module 02/Lesson 02/startup-profit-prediction - Practice.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: MyPy397 # language: python # name: mypy397 # --- # # Lo que ve el SERVICIO -> Servicio!? # + import pandas as pd import numpy as np import glob from subprocess import Popen, PIPE, TimeoutExpired import os import re # + plfiles = "../results/results_SMALL_OSMOTIC_SEED_vNew_X/models_9/" pl = "model_B60_n9_DES60_0_10700.pl" pl = "model_B1_n0_DES2_0_1100.pl" pl = "model_B1_n0_DES3_0_1100.pl" rRequest = re.compile("requests\(s\d+,\[(n\d+)|self],\d+,\d+\).\n") rNode = re.compile("node\(self,\d+") rServiceInstance = re.compile("serviceInstance\(s") neigRequest = set() totalRequests = [] latencyOfRequests = [] nodeAvailHW= [] nodeNeigh = [] services = {} map_services = {"s":1,"m":2,"l":3} services[1]=[1,1,10,2,2,20,3,5,50,10] services[2]=[1,1,10,2,2,20,3,5,50,10] services[3]=[1,0,0,2,4,20,3,0,0,10] with open(plfiles+pl) as f: for line in f: #requests result = rRequest.search(line) if result: print(line) line = line.replace("requests(s","").replace(").\n","").split(",") totalRequests.append(int(line[2])) latencyOfRequests.append(int(line[3])) print(line[1]) if "self" in line[1]: neigRequest.add(1) else: neigRequest.add(int(line[1].replace("[n","").replace("]",""))) else: #current node result = rNode.search(line) if result: line = line.replace("node(self","").replace(").\n","").split(",") nodeAvailHW = int(line[1]) nodeNeigh = line[2].replace("n","").strip('][').split(', ') else: #service fact result = rServiceInstance.search(line) if result: print(line) line = line.replace("serviceInstance(s","").replace(").\n","").split(",") app = int(line[1].replace("app","")) fl = line[2].replace("(","")[0] current_flavour = map_services[fl] print("STATS___") print("Number of requests ",totalRequests) print("Latency of the request:" ,latencyOfRequests) print("number of vecinos en requests ", len(neigRequest)) print("Node available HW", nodeAvailHW) print("Vecinos:",nodeNeigh) print("Numero de vecinos: ",len(nodeNeigh)) print(app) print(current_flavour) # - l = np.array(latencyOfRequests) l.mean()
notebooks/ParsingPlFile.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 # --- # + # #!pip install gym-jsbsim # #!pip install gym # #!pip install folium # - import jsbsim import folium import random from os import environ environ.get('CONDA_PREFIX') class Aircraft: fpath = environ.get('CONDA_PREFIX') + '/lib/python3.7/site-packages/andy_gym_jsbsim/jsbsim' def __init__(self): self.exec = jsbsim.FGFDMExec(self.fpath) self.exec.set_debug_level(1) self.exec.load_model("A320") self.exec.set_dt(1.0/60.) self.path = [] def initialize(self, psi=323): self.exec.set_property_value('ic/h-sl-ft', 8.42) self.exec.set_property_value('ic/terrain-elevation-ft', 8.42) self.exec.set_property_value('ic/h-agl-ft', 8.42) self.exec.set_property_value('ic/long-gc-deg', 1.37211666700005708) # geocentrique (angle depuis le centre de la terre) self.exec.set_property_value('ic/lat-gc-deg', 43.6189638890000424) # geodesique #self.exec.set_property_value('ic/lat-geod-deg', 43.6189638890000424) self.exec.set_property_value('ic/u-fps', 11.8147) self.exec.set_property_value('ic/v-fps', 0) self.exec.set_property_value('ic/w-fps', 0) self.exec.set_property_value('ic/p-rad_sec', 0) self.exec.set_property_value('ic/q-rad_sec', 0) self.exec.set_property_value('ic/r-rad_sec', 0) self.exec.set_property_value('ic/roc-fpm', 0) self.exec.set_property_value('ic/psi-true-deg', psi) self.exec.run_ic() def setGears(self, status='down'): if status == 'down': self.exec.set_property_value('gear/gear-pos-norm', 1) self.exec.set_property_value('gear/unit[1]/pos-norm', 1) self.exec.set_property_value('gear/unit[2]/pos-norm', 1) # Set gear down self.exec.set_property_value('gear/gear-cmd-norm', 1) else: self.exec.set_property_value('gear/gear-pos-norm', 0) self.exec.set_property_value('gear/unit[1]/pos-norm', 0) self.exec.set_property_value('gear/unit[2]/pos-norm', 0) # Set gear up self.exec.set_property_value('gear/gear-cmd-norm', 0) def setEngines(self, status='on'): propulsion = self.exec.get_propulsion() for j in range(propulsion.get_num_engines()): propulsion.get_engine(j).init_running() propulsion.get_steady_state() self.exec.set_property_value('fcs/mixture-cmd-norm', 1) def getProperties(self, filter='ic'): properties = self.exec.query_property_catalog('') filtered = [] for p in properties: if filter in p: filtered.append(p) return filtered def getPath(self): return self.path def saveFullState(self): props = self.exec.get_property_catalog('') for p in self.state_trajectory.keys(): self.state_trajectory[p].append(props[p]) def step(self, throttle=0.5, steer=0): self.exec.set_property_value('fcs/throttle-cmd-norm', throttle) self.exec.set_property_value('fcs/steer-cmd-norm', steer) for _ in range(5): result = self.exec.run() lat = self.exec.get_property_value('position/lat-gc-deg') lon = self.exec.get_property_value('position/long-gc-deg') speed = self.exec.get_property_value('velocities/vc-fps') self.path.append([lat, lon]) return { 'speed':speed } class Bomber: fpath = os.environ.get(')'/lib/python3.7/site-packages/andy_gym_jsbsim/jsbsim' def __init__(self): self.index = -1 self.paths = [] self.exec = None def reset(self): # Create the simulation otherwise close it if self.exec != None: self.exec = None del self.exec # This one is removing the crash self.exec = jsbsim.FGFDMExec(self.fpath) self.exec.set_debug_level(1) self.exec.load_model("A320") self.exec.set_dt(1.0/60.) self.index = self.index + 1 self.paths.append([]) def initialize(self, psi=323): self.exec.set_property_value('ic/h-sl-ft', 8.42) self.exec.set_property_value('ic/terrain-elevation-ft', 8.42) self.exec.set_property_value('ic/h-agl-ft', 8.42) self.exec.set_property_value('ic/long-gc-deg', 1.37211666700005708) # geocentrique (angle depuis le centre de la terre) self.exec.set_property_value('ic/lat-gc-deg', 43.6189638890000424) # geodesique #self.exec.set_property_value('ic/lat-geod-deg', 43.6189638890000424) self.exec.set_property_value('ic/u-fps', 11.8147) self.exec.set_property_value('ic/v-fps', 0) self.exec.set_property_value('ic/w-fps', 0) self.exec.set_property_value('ic/p-rad_sec', 0) self.exec.set_property_value('ic/q-rad_sec', 0) self.exec.set_property_value('ic/r-rad_sec', 0) self.exec.set_property_value('ic/roc-fpm', 0) self.exec.set_property_value('ic/psi-true-deg', psi) self.exec.run_ic() def setGears(self, status='down'): if status == 'down': self.exec.set_property_value('gear/gear-pos-norm', 1) self.exec.set_property_value('gear/unit[1]/pos-norm', 1) self.exec.set_property_value('gear/unit[2]/pos-norm', 1) # Set gear down self.exec.set_property_value('gear/gear-cmd-norm', 1) else: self.exec.set_property_value('gear/gear-pos-norm', 0) self.exec.set_property_value('gear/unit[1]/pos-norm', 0) self.exec.set_property_value('gear/unit[2]/pos-norm', 0) # Set gear up self.exec.set_property_value('gear/gear-cmd-norm', 0) def setEngines(self, status='on'): propulsion = self.exec.get_propulsion() for j in range(propulsion.get_num_engines()): propulsion.get_engine(j).init_running() propulsion.get_steady_state() self.exec.set_property_value('fcs/mixture-cmd-norm', 1) def getProperties(self, filter='ic'): properties = self.exec.query_property_catalog('') filtered = [] for p in properties: if filter in p: filtered.append(p) return filtered def getPath(self, index): return self.paths[index] def saveFullState(self): props = self.exec.get_property_catalog('') for p in self.state_trajectory.keys(): self.state_trajectory[p].append(props[p]) def step(self, throttle=0.5, steer=0): self.exec.set_property_value('fcs/throttle-cmd-norm', throttle) self.exec.set_property_value('fcs/steer-cmd-norm', steer) for _ in range(5): result = self.exec.run() lat = self.exec.get_property_value('position/lat-gc-deg') lon = self.exec.get_property_value('position/long-gc-deg') speed = self.exec.get_property_value('velocities/vc-fps') self.paths[self.index].append([lat, lon]) return { 'speed':speed } # + plane = [] color = ['red', 'blue', 'green', 'purple', 'orange', 'white', 'gray', 'black', 'black'] nbiterations = 1000 # Generate steer command between -1 & +1 steering = [] for i in range(nbiterations): steering.append(2.0*random.random() - 1.0) steering = list(sorted(steering)) speed = [] for i in range(len(color)): plane.append(Aircraft()) plane[i].initialize(psi=i*36) plane[i].setGears('down') plane[i].setEngines('on') for j in range(nbiterations): plane[i].step(throttle=0.5, steer=steering[j]) # + map = None map = folium.Map(location=[43.6189638890000424, 1.37211666700005708], zoom_start=15) folium.Marker((43.6189638890000424, 1.37211666700005708), marker_icon='plane').add_to(map) for i in range(len(color)): folium.PolyLine(plane[i].getPath(), color=color[i], weight=2.5, opacity=1).add_to(map) # - map # + bombers = [] #color = ['red', 'blue', 'green', 'purple', 'orange', 'white', 'gray', 'black', 'black'] color = ['grey'] nbiterations = 1000 # Generate steer command between -1 & +1 steering = [] for i in range(nbiterations): steering.append(2.0*random.random() - 1.0) steering = list(sorted(steering)) # + speed = [] bombers.append(Bomber()) bombers[0].reset() bombers[0].initialize(psi=45) bombers[0].setGears('down') bombers[0].setEngines('on') for j in range(nbiterations): bombers[0].step(throttle=0.5, steer=steering[j]) # + for i in range(10): bombers[0].reset() bombers[0].initialize(psi=90 + 5*i) bombers[0].setGears('down') bombers[0].setEngines('on') for j in range(nbiterations): bombers[0].step(throttle=0.5, steer=steering[j]) bombers[0].reset() bombers[0].initialize(psi=45) bombers[0].setGears('down') bombers[0].setEngines('on') for j in range(nbiterations): bombers[0].step(throttle=0.5, steer=steering[j]) # + bmap = folium.Map(location=[43.6189638890000424, 1.37211666700005708], zoom_start=15) folium.Marker((43.6189638890000424, 1.37211666700005708), marker_icon='plane').add_to(bmap) folium.PolyLine(bombers[0].getPath(0), color='grey', weight=2.5, opacity=1).add_to(bmap) bmap # + folium.PolyLine(bombers[0].getPath(bombers[0].index), color='black', weight=2.5, opacity=1).add_to(bmap) bmap # -
notebooks/Tests_jsbsim.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/tatianabarbone/stellar-classification/blob/master/stellar_classification.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="LxWxIErvjejq" colab_type="text" # # Stellar Classification with Scikit-Learn # + [markdown] id="o1ALuKe8HKBJ" colab_type="text" # **Inspiration** # # # # > I've always been fascinated by outer space-- especially stars, constellations and galaxies. # # # + [markdown] id="5DAR8fVYFZGR" colab_type="text" # ![picture](https://images-assets.nasa.gov/image/PIA13459/PIA13459~orig.jpg) # # This is a picture of a nebula surrounding the **supergiant star** CE-Camelopardalis. # # Source: images.nasa.gov # + [markdown] id="ZiWfmuSoLpac" colab_type="text" # # # # > After doing some research online, I learned that stars can be classified into different categories depending on their quantitative measurements such as absolute magnitude and luminosity. Then I discovered the Hertzsprung–Russell diagram, which shows the relationships between these measures: # # > Source: wikipedia.org # # # ![picture](https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/HRDiagram.png/620px-HRDiagram.png) # + [markdown] id="-HhnGX7ihqzS" colab_type="text" # > So, using [this star dataset](https://www.kaggle.com/deepu1109/star-dataset) from kaggle and different classification algorithms, I put python's scikit-learn library to the test to predict star type (Hypergiant, Supergiant, etc.) based on temperature, luminosity, radius and absolute magnitude. # # + [markdown] id="NicdnwIbjWIb" colab_type="text" # ## Exploring the Data # + id="_NnPc3tt1xdv" colab_type="code" colab={} #Imports from google.colab import files import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline import seaborn as sns from matplotlib import cm from pandas.plotting import scatter_matrix #Sklearn imports from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn import tree from sklearn.neighbors import KNeighborsClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC from sklearn.metrics import classification_report, confusion_matrix # + [markdown] id="6yUwM1kwiEVs" colab_type="text" # I downloaded the csv file from kaggle and uploaded it directly into this notebook. # + id="InomByw18R_B" colab_type="code" colab={"resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY>", "ok": true, "headers": [["content-type", "application/javascript"]], "status": 200, "status_text": ""}}, "base_uri": "https://localhost:8080/", "height": 72} outputId="72e63162-c23b-4d5b-c718-59c6c00e641a" uploaded = files.upload() stars = pd.read_csv('6_class_csv.csv') # + id="EwUpt7Z08YEJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="c39d2e86-9070-4872-bb74-2d4451a3cd6d" stars.head() # + id="SpzqwHsw81gf" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="b8d2eeb9-dc49-4663-cae8-2ccdd049882c" stars.shape # + [markdown] id="hK_OjgKVBMD8" colab_type="text" # We have 240 different stars and 7 features we are dealing with. # + id="qRfrcLM2BgLI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="d09abc61-1ec1-4450-95fd-4a1bbfa98d42" print(stars['Star type'].unique()) # + [markdown] id="WMiy_WLB5NJz" colab_type="text" # We will create a correlation heatmap, which will show us which variables are correlated to each other. # # * 1 = the most correlated # * -1 = not correlated at all. # # # + id="skvAT3cG89wL" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="2baba959-4d0f-4b8f-9136-e1562f7c809b" corr = stars.corr() corr # + id="_MZ4eV6M-qhp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 399} outputId="ec0f5271-789b-4788-be25-ecf1c44a323d" sns.heatmap(corr) # + [markdown] id="847N56flAJ9_" colab_type="text" # From the heatmap we can see that temperature, luminosity and radius have a strong correlation with star type. # # Our features will be temperate, luminosity, radius and absolute magnitude. Star type will be the label. # + id="rCSrs8GsDJ30" colab_type="code" colab={} feature_names = ['Temperature (K)', 'Luminosity(L/Lo)', 'Radius(R/Ro)', 'Absolute magnitude(Mv)'] X = stars[feature_names] y = stars['Star type'] # + [markdown] id="4yTDY08YAuCQ" colab_type="text" # For each feature, we'll make a scatter plot. # + id="lWxuQJ3uCkI3" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 518} outputId="f56fe2ef-ad62-4125-83cc-07cbd2d0c45b" cmap = cm.get_cmap('gist_ncar') scatter = pd.plotting.scatter_matrix(X, c = y, marker = '*', s=80, figsize=(8,8), cmap = cmap) # + [markdown] id="PK9EXoBgCGQY" colab_type="text" # ## Cross Validation # + id="ijoPhen-_F18" colab_type="code" colab={} # Create training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) # + id="cfkc6lI5FPE3" colab_type="code" colab={} # Scale the data to improve modeling performance scaler = MinMaxScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # + [markdown] id="D5fEpI8jM_g6" colab_type="text" # ## Building the Models # + [markdown] id="-Eiqh1H4pQL9" colab_type="text" # # # ### Logistic Regression # # # + id="Ikx1tI4ICkVn" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="cdd6939f-9222-43f2-9fa6-2ba25fc14562" logreg = LogisticRegression() logreg.fit(X_train, y_train) print('Accuracy of Logistic regression classifier on training set: {:.2f}' .format(logreg.score(X_train, y_train))) print('Accuracy of Logistic regression classifier on test set: {:.2f}' .format(logreg.score(X_test, y_test))) # + [markdown] id="BaA65QfRpfwF" colab_type="text" # ### K-Nearest Neighbors # + id="1-IubH6qFWZS" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="33bcc42d-c764-44f5-8635-bee4fbcfeaf0" knn = KNeighborsClassifier() knn.fit(X_train, y_train) print('Accuracy of K-NN classifier on training set: {:.2f}' .format(knn.score(X_train, y_train))) print('Accuracy of K-NN classifier on test set: {:.2f}' .format(knn.score(X_test, y_test))) # + [markdown] id="AMHWjXS8pabM" colab_type="text" # ### Decision Tree # + id="9_kvgcAPCj93" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="1c77be89-c3e8-4b3c-b8a7-c64e1d948ee3" clf = DecisionTreeClassifier().fit(X_train, y_train) print('Accuracy of Decision Tree classifier on training set: {:.2f}' .format(clf.score(X_train, y_train))) print('Accuracy of Decision Tree classifier on test set: {:.2f}' .format(clf.score(X_test, y_test))) # + id="wBTj9x11M-Rk" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="3affa824-7c37-4364-c1fe-b546f123ef2b" print('Max depth:', clf.tree_.max_depth) # + [markdown] id="YDxh2ehSWUqz" colab_type="text" # The ideal max_depth of our tree avoids overfitting the training data while giving it just the right amount of flexibility to capture the patterns in the training data. Ultimately we are aiming for the lowest error on our test set. # + [markdown] id="Uco5kZEcp64H" colab_type="text" # #### Visualizing the Decision Tree # + id="T1N1ewTNU_Xb" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 306} outputId="92a732ac-1428-4904-db73-ffbfa1d40006" text_representation = tree.export_text(clf) print(text_representation) # + [markdown] id="Br_mF4El8y-m" colab_type="text" # The text representation is cool, but a colorful diagram with arrows would be much cooler! # + id="MP3vgmgjzRMF" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 575} outputId="a94ec8d7-9c8c-4137-c808-f4a544608098" class_names = ['Brown Dwarf', 'Red Dwarf', 'White Dwarf', 'Main Sequence', 'Supergiant', 'Hypergiant'] #indices correspond to star type fig = plt.figure(figsize=(10,10)) _ = tree.plot_tree(clf, feature_names=feature_names, class_names=class_names, filled=True) # + [markdown] id="gW8iu0kypnfT" colab_type="text" # ### Linear Discriminant Analysis # + id="Tf0RHr0RFZlT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="ee71d5ed-48dd-4654-c1a6-fb3414fb430f" lda = LinearDiscriminantAnalysis() lda.fit(X_train, y_train) print('Accuracy of LDA classifier on training set: {:.2f}' .format(lda.score(X_train, y_train))) print('Accuracy of LDA classifier on test set: {:.2f}' .format(lda.score(X_test, y_test))) # + [markdown] id="6hP9QzI2V4g4" colab_type="text" # #### Visualizing LDA # The goal of LDA is to find a linear combination of features that best separates two classes. # # Our dataset has four features, so it would be difficult to visualize the decision boundary (a line) in a 4D plane. # # To visualize the data, we'll need to reduce the features to two, then use LDA to classify the features. # # This code was used and modified from the [sklearn docs](https://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_vs_lda.html#sphx-glr-auto-examples-decomposition-plot-pca-vs-lda-py): # + id="C3R23kJIWKm1" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="8dede3aa-cb3d-4987-98f9-f8cd4b3ecc1a" lda = LinearDiscriminantAnalysis(n_components=2) X_r2 = lda.fit(X, y).transform(X) colors = ['#ff92a5', '#8a9747','#4bc4d5', '#0180b5','#ffd35c','#954567'] for color, i, name in zip(colors, [0,1,2,3,4,5], class_names): plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], alpha=.8, color=color, label=name) plt.legend(loc='best', shadow=False, scatterpoints=1) plt.show() # + [markdown] id="a2UsK729pzuX" colab_type="text" # ### Support Vector Machine # + id="CXl2oEKYFgUd" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="71252414-010e-44c0-d115-56c01eb2274f" svm = SVC() svm.fit(X_train, y_train) print('Accuracy of SVM classifier on training set: {:.2f}' .format(svm.score(X_train, y_train))) print('Accuracy of SVM classifier on test set: {:.2f}' .format(svm.score(X_test, y_test))) # + [markdown] id="dZbzxOtopwD9" colab_type="text" # ### Gaussian Naive Bayes # + id="PkkuIeHjFcuI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="ca55d196-fcb8-4e04-9fa1-2f26dbe391bd" gnb = GaussianNB() gnb.fit(X_train, y_train) print('Accuracy of GNB classifier on training set: {:.2f}' .format(gnb.score(X_train, y_train))) print('Accuracy of GNB classifier on test set: {:.2f}' .format(gnb.score(X_test, y_test))) # + [markdown] id="GMG1xt4IDkTx" colab_type="text" # ## Classification Report and Final Comments # + [markdown] id="xnxxfx9oDwTC" colab_type="text" # The Decision Tree algorithm was the most accurate, but KNN and LDA were not far behind. **In fact, most of the algorithms were very accurate due to the small dataset size.** # # Using the classification report and confusion matrix, we can visualize the performance of the decision tree model. # + id="LAmz8TvjDj2z" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 119} outputId="bb45141c-43d7-4786-9335-86bdad407fec" pred = clf.predict(X_test) print(confusion_matrix(y_test, pred)) # + [markdown] id="LGWugqbOFUNr" colab_type="text" # The confusion matrix shows that we made one error (3rd row, 2nd column), incorrectly classifying a Main Sequence star as a Red Dwarf. # + id="p5JR2xn9EE6i" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 238} outputId="acde0368-d10e-4b6e-d9ab-9d05d75df533" print(classification_report(y_test, pred)) # + [markdown] id="WK85ShNrGQvs" colab_type="text" # The classification report tells us about True Positives, False Positives, True Negatives and False Negatives. # # * Precision: the ratio of true positives to the sum of true and false positives. # * Recall: the ratio of true positives to the sum of true positives and false negatives. # * F1 Score: 2*(Recall * Precision) / (Recall + Precision) #
stellar_classification.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 # --- #dictionary is a key value pair a = {1: "one", "class": "Python"} print a print a[1] print a['class'] # + #dictionaries/keys also uses hashing concept in store data # - b = {1:"one", [3,4]: "yahoo"} b = {1:"one", (3,4): "yahoo"} a = {"institute": "IT Trends", 'classes': ['automation', 'web developments'], 'language': 'Python'} print a print a['classes'] print a['classes'][0] faculty = {'Nag': a} print faculty print faculty['Nag'] print faculty['Nag']['language'] c = {1:"one", 2: "two"} print c c[3] = "three" print c c[3] = 'threeeee' print c print faculty faculty['Nag']['language'] = 'Python3.6' print faculty faculty['Nag']['classes'][1] = 'Django' print faculty print c print c[4] print c.get(3) print c.get(4) print c.get(4, 'No key exists') print c.get(3, 'No key exists') faculty.update(c) print faculty print dir(faculty) print faculty print faculty.keys() print faculty.values() print faculty.items() print faculty.iterkeys() for x in faculty.iterkeys(): print x range(10) xrange(10)
dictionaries.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 # --- # Presented Below are two plots in subplot configuration. The upper plot is a sum of the cusp crossings. The lower plot is a plot of the cusp latitude and the spacecraft latitude/longitude plotted against time. Also included is the process of thoughts that led to that conclusion. # # I used the Tsyganenko model of the cusp position. This model describes the cusp position in the noon-midnight meridian using a cylindrical coordinate system. The $r$ and $\theta$ components are occuring in the xz plane. The neutral axis is therefore the $y$ axis. # # Tsyganenko provides the following equation for a simplified cusp model # \begin{equation} # \phi_{c} = arcsin(\frac{\sqrt{\rho}}{\sqrt{\rho + \sin^{-2}(\phi_{1}) -1}}) + \psi(t) # \end{equation} # # Here, $\rho$ is the radial of the satellite from the center of the earth. $\phi_{c}$ is the colatitude of the cusp position. $\psi$ is the dipole tilt of the cusp. $\phi_{1}$ is provided by the equation $\phi_{c0} - (\alpha_{1} \psi + \alpha_{2}\psi^{2})$. As in (Tsyganenko) the values of $\phi_{c}$, $\alpha_{1}$, and $\alpha_{2}$ are 0.24, 0.1287, and 0.0314 respectively. ((note that that last sentence is almost a literal copy paste of the Tsyg paper)). Note that $\psi (t)$ is my own addition and that the original notation is $\psi$. I want to make it extremely clear that $\psi$ varies with time, requiring that the tsyganenko library be a function of time as well. # # The dataset used here depicts the path of a satellite on a single day of its orbit 01-Jan-2019, at a $65^{\circ}$ inclined orbit. # + import tsyganenko as tsyg import pandas as pd import numpy as np import matplotlib.pyplot as plt from spacepy import coordinates as coord import spacepy.time as spt from spacepy.time import Ticktock import datetime as dt from mpl_toolkits.mplot3d import Axes3D import sys #adding the year data here so I don't have to crush my github repo pathname = '../../data-se3-path-planner/yearData/cuspCrossings2019/' sys.path.append(pathname) # find phi for a stationary cusp r = np.linspace(0,10, 1000) phi_c = tsyg.getPhi_c(r) plt.plot(r,phi_c) plt.ylabel('phi_c (radians)') plt.xlabel('earth radii ($R_{e}$)') plt.title('Tsyganenko Cusp Position') plt.show() # - # Note that below, there are many ways that we could set up the subplot, but I just chose (programattically) to do it a certain way provided in http://matplotlib.org/examples/pylab_examples/subplots_demo.html # # Note: The units for this system is solar magnetic degrees. Some plots I did gave me that kind of bias to think that SM would be the best coordinate system for this. (That's probably not true but there are many ways to solve this problem). # + # the orbit is fairly easy to get df = pd.read_csv('singleday.csv') # df = pd.read_csv('5day.csv') t = df['DefaultSC.A1ModJulian'] + 29999.5 x = df['DefaultSC.gse.X'] y = df['DefaultSC.gse.Y'] z = df['DefaultSC.gse.Z'] # set the "ticks" cvals = coord.Coords([[i,j,k] for i,j,k in zip(x,y,z)], 'GSE', 'car') cvals.ticks = Ticktock(t,'MJD') # originally SM sm = cvals.convert('SM', 'sph') # t = np.asarray(t) # plotting stuff f, axarr = plt.subplots(2, sharex=True) # axarr[0].plot(t, y) axarr[0].set_title('Spacecraft Latitude') axarr[0].set_ylabel('latitude (sm deg)') axarr[0].plot(sm.ticks.MJD, sm.lati) axarr[1].set_title('Spacecraft Longitude') axarr[1].set_ylabel('longitude (sm deg)') axarr[1].plot(sm.ticks.MJD, sm.long) plt.xlabel('time (unit)') plt.show() # - # The next thing to do is compute the cusp latitude and longitude using tsyganenko. The cusp angular position is a function of radial distance from the earth as given in the Tsyganenko equation. This means that different "tracks" will be given as we vary $R_{e}$. Since I am using a very circular orbit, with $e \sim 0.02$, I will plot the cusp latitude and longitude below as a function of the spacecraft altitude in my GMAT file. The semi major axis is given as $7191 km$, $\sim 1.127 R_{e}$. # + rs = 1.127 # average of the radius of the orbit # rs = np.array([1,2,3]) phic = tsyg.getPhi_c(rs) x,y,z= tsyg.tsygCyl2Car(phic,rs) # print("x,y,z",xt,yt,zt) print("x",x) print("y",y) print("z",z) # next lets put these three coordinates into a spacepy coordinates object singletrack = coord.Coords([[x,y,z]]*len(t), 'SM', 'car') singletrack.ticks = Ticktock(t,'MJD') singletrack = singletrack.convert('GEI','sph') f, axarr2 = plt.subplots(2, sharex=True) # axarr[0].plot(t, y) axarr2[0].set_title('Cusp Longitude and Latitude') axarr2[0].set_ylabel('latitude (sm deg)') axarr2[0].scatter(singletrack.ticks.MJD, singletrack.lati) axarr2[1].set_title('Cusp and Spacecraft Latitude') axarr2[1].set_ylabel('longitude (sm deg)') axarr2[1].scatter(singletrack.ticks.MJD, singletrack.long) plt.xlabel('time (unit)') f,axarr3 = plt.subplots(1) axarr3.set_title('Lat vs Lon') axarr3.set_ylabel('latitude') axarr3.set_xlabel('longitude') axarr3.plot(singletrack.long,singletrack.lati, label='r = 1.127 Re') axarr3.scatter(sm.long,sm.lati,label='spacecraft orbit actual') axarr3.legend(loc='lower left') plt.show() # - # So I suppose this does show that for a region of the stationary cusp, that the satellite potentially crosses it. However, the cusp location moves throughout the day so it's conceivable that the cusp avoids the orbit of the satellite, and I need a way to test for that. The other big question is how do I integrate dipole tilt into this at the same time. The first question I need to answer is whether or not the dipole tilt matters in SM. # # One other approach I could take is to come up with the cusp position as $f(\rho,t)$, then compare that latitude and longitude to the spacecraft latitude and longitude. That's really what I need to do. # # Step by Step what I will attempt to do: # # 1. Move the cusp and prove that it is moving. I'll use the r = 1.127Re track to do this and one years worth of data. x # # 2. Once I have the cusp latitude and longitude, compare the satellite latitude and longitude. # # 3. Do the cusp crossings count. # # 4. Plot the lat/lon of the cusp/spacecraft and the cusp crossings subplots together. # # From here one we will be using the data from a year's flight around the earth, because these trends are periodic over a year. # # + # the orbit is fairly easy to get #df = pd.read_csv(pathname+'zero.csv') df = pd.read_csv('5day.csv') t = df['DefaultSC.A1ModJulian'] + 29999.5 x = df['DefaultSC.gse.X'] y = df['DefaultSC.gse.Y'] z = df['DefaultSC.gse.Z'] # set the "ticks" cvals = coord.Coords([[i,j,k] for i,j,k in zip(x,y,z)], 'GSM', 'car') cvals.ticks = Ticktock(t,'MJD') sm = cvals.convert('SM','sph') gsm = cvals.convert('GEI', 'sph') # t = np.asarray(t) # plotting stuff f, axarr = plt.subplots(2, sharex=True) # axarr[0].plot(t, y) axarr[0].set_title('Spacecraft Latitude') axarr[0].set_ylabel('latitude (sm deg)') axarr[0].plot(sm.ticks.MJD, sm.lati) axarr[1].set_title('Spacecraft Longitude') axarr[1].set_ylabel('longitude (sm deg)') axarr[1].plot(sm.ticks.MJD, sm.long) plt.xlabel('time (unit)') plt.show() f, a = plt.subplots(1) plt.title('Solar Magnetic Orbit') plt.xlabel('Solar Magnetic Longitude') plt.ylabel('Solar Magnetic Latitude') a.plot(sm.long,sm.lati) plt.show() # - psi = tsyg.getTilt(t) plt.plot(t,psi) plt.title('Dipole Tilt') plt.xlabel('MJD') plt.ylabel('Dipole Tilt (gsm deg)') plt.show() # here the OUTPUT, psi is in degrees # output cusp position with the dipole tilt r = 1.127 psi = np.deg2rad(psi) phi_c = tsyg.getPhi_c(r,psi) phi_c = np.rad2deg(phi_c) plt.figure() plt.plot(t,phi_c) plt.title('Cusp location over time for $r = 1.127R_{e}$') plt.xlabel('MJD') plt.ylabel('Cusp Location (gsm deg)') plt.show() # + # next lets get the spherical coordinates and plot the latitude and longitudes, which SHOULD # allow us to get the cusp crossings. xc,yc,zc = tsyg.tsygCyl2Car(phi_c,r) #originally it was GSM cusp_location = coord.Coords([[i,j,k] for i,j,k in zip(xc,yc,zc)], 'GSM', 'car') cusp_location.ticks = Ticktock(t,'MJD') cusp_location = cusp_location.convert('GEI','sph') plt.scatter(cusp_location.long, cusp_location.lati) plt.scatter(gsm.long,gsm.lati,color='green') plt.xlabel('gei longitude (deg)') plt.ylabel('gei latitude (deg)') plt.title('Cusp Latitude vs. Longitude (gei)') plt.show() # - # The biggest issues of this plot are that we aren't able to see where the cusp is at a certain time, it's just a ground track. Therefore, we need to also put in the plots of lat/lon vs. time. # # Close to solving this. I think my cusp actually behaves somewhat correctly. The above plot was actually really promising, but for some reason my Now I need to use the Tsyganenko equation as an function of the satellite's location. It really don't make much sense to me why the cusp wouldn't seem to change in latitude. My guess is that there's tiny circles there if you look closely at the data. # # I'll deal with what I suspect are innacuracies later I feel like I've done okay thus far. Like I "feel" like the equations are wrong. # Open Questions at this point: # 1. should the latitude go so low? # 2. # plot of the latitude and the longitude of the spacecraft at each timestep, f,ax = plt.subplots(2) # i can probably use a list comprehension here for the cusp location # just feel really unmotivated rn # xk,yk,zk = tsyg.tsygCyl2Car() # longitude vs. time ax[0].set_title('Cusp and Satellite Longitude') ax[1].set_title('Cusp and Satellite Latitude') ax[0].plot(gsm.ticks.MJD, gsm.long) ax[1].plot(gsm.ticks.MJD, gsm.lati) plt.show() # + # testing the function for x,y,z = tsyg.orbitalCuspLocation(cvals,t) fig = plt.figure() ax.plot(phi_c,r) plt.show()
modularPlanner/.ipynb_checkpoints/Cusp Plots (Daily)-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 (ipykernel) # language: python # name: python3 # --- # default_exp main from nbdev import * from utilities.ipynb_docgen import * import pandas as pd import matplotlib.pyplot as plt # !date # # wtlike interface # > Top-level interface to the rest of the package # + # export import numpy as np from wtlike.bayesian import get_bb_partition from wtlike.lightcurve import fit_cells, LightCurve, flux_plot from wtlike.cell_data import partition_cells from wtlike.config import * class WtLike(LightCurve): """ Summary --------- There are three layers of initialization, implemented in superclasses, each with parameters. The classnames, associated parameters and data members set: SourceData -- load photons and exposure parameters: - source : name, a PointSource object, or a Simulation object - config [Config()] : basic configuration - week_range [None] : range of weeks to load - key [''] : the cache key: '' means construct one with the source name, None to disable - clear [False] : if using cache, clear the contents first sets: - photons - exposure CellData -- create cells parameters: - time_bins [Config().time_bins] : binning: start, stop, binsize sets: - cells LightCurve -- likelihood analysis of the cells parameters: - e_min [10] -- threshold for exposure (cm^2 units) - n_min [2] -- likelihood has trouble with this few - lc_key [None] -- possible cache for light curve sets: - fits, fluxes WtLike (this class) -- no parameters (may add BB-specific ones) Implements: bb_view, plot_BB sets: - bb_flux (only if bb_view invoked) """ def bb_view(self, p0=0.05, key=None, clear=False): """Return a view with the BB analysis applied - p0 -- false positive probability parameter Its `plot` function will by default show an overplot on the parent's data points. """ # a new instance r = self.view() # bb analysis on this to make new set of cells and poisson fits bb_edges = get_bb_partition(self.config, self.fits, p0=p0, key=key, clear=clear) r.cells = partition_cells(self.config, self.cells, bb_edges) r.fits = fit_cells(self.config, r.cells, ) r.isBB = True r.bayes_p0 = p0 return r def plot(self, *pars, **kwargs): # which view type is this? if getattr(self, 'isBB', False): return self.plot_bb(*pars, **kwargs) elif getattr(self, 'is_phase', False): return self.plot_phase(*pars, **kwargs) else: return super().plot(*pars, **kwargs) def plot_bb(self, ax=None, **kwargs): """Plot the light curve with BB overplot """ import matplotlib.pyplot as plt self.check_plot_kwargs(kwargs) figsize = kwargs.pop('figsize', (12,4)) fignum = kwargs.pop('fignum', 1) ts_min = kwargs.pop('ts_min',-1) source_name =kwargs.pop('source_name', self.source_name) fig, ax = plt.subplots(figsize=figsize, num=fignum) if ax is None else (ax.figure, ax) colors = kwargs.pop('colors', ('lightblue', 'wheat', 'blue') ) flux_plot(self.parent.fits, ax=ax, colors=colors, source_name=source_name, label=self.step_name+' bins', **kwargs) flux_plot(self.fits, ax=ax, step=True, label=f'BB (p0={100*self.bayes_p0:.0f}%)', zorder=10,**kwargs) ax.grid(alpha=0.5) fig.set_facecolor('white') return fig def phase_view(self, period, nbins=25, reference='2008'): """ Return a "phase" view, in which the cell time binning is according to phase. * reference -- a UTC date for aligning the bins. """ ref = 0 if not reference else MJD(reference) # helper function that returns the bin number as a float in [0,period) binner = lambda t: np.mod(t-ref,period)/period * nbins # adjust start to correspond to edge of bin # create a view with nbins per period and get the cells st = self.start # the start of data taking self.reference_bin =strefbin = binner(st) stnew = st +np.mod(-strefbin,1)*period/nbins view = self.view(stnew, 0, period/nbins) cells = view.cells bw = 1/nbins def concat(pcells, t): newcell = dict(t=t, tw=bw) for col in 'n e S B'.split(): newcell[col] = pcells[col].sum() newcell['w'] = np.concatenate(list(pcells.w.values)) return newcell # concatenate all in the same phase bin--note cyclic rotation k = int(strefbin) fcells = [concat(cells.iloc[((ibin-k)%nbins):-1:nbins], (ibin+0.5)*bw) for ibin in range(nbins) ] view.cells = pd.DataFrame(fcells) view.update() view.is_phase = True view.period = period return view def plot_phase(self, ax=None, **kwargs): """Plot a phase lightcurve """ kw = dict(ylim=(0.975, 1.025), xlim=(0,1) ) kw.update(kwargs) fig, ax = plt.subplots(figsize=(10,5)) if ax is None else (ax.figure, ax) fig = super().plot(ax=ax, xlabel=f'phase for {self.period}-day period'); ax.set(**kwargs ); ax.axhline(1.0, color='grey'); return fig # + #collapse_input def phase_tests(): """ ### Test phase_view {out1} {fig1} {out2} {fig2} """ plt.rc('font', size=16) year = 365.25; ref_date='2008'; precess=53.05 with capture(f'Vela setup, {precess}-day period') as out1: vela = WtLike('Vela pulsar') pv = vela.phase_view( period=precess, nbins=25); fig1 = figure(pv.plot(), width=500); with capture(f'Geminga setup: period={year} days, relative to {ref_date}') as out2: geminga = WtLike('Geminga') gv = geminga.phase_view(year, nbins=50, reference=ref_date) fig2 = figure(gv.plot(), width=500) # #gv.fluxes.query('flux>1.07') # with capture(f'Geminga with yearly bins') as out3: # gt = geminga.view(54685.15, 0, 7.305) # fig3= figure(gt.plot(UTC=True)); # fq = gt.fluxes.query('flux>1.1')['t flux'.split()]; return locals() if Config().valid: nbdoc(phase_tests) # - show_doc(WtLike) show_doc(WtLike.bb_view) show_doc(WtLike.phase_view) #hide from wtlike.config import * config = Config() if config.valid: wtl = WtLike('Geminga', week_range=(9,108) ) wtl.bb_view().plot(); # + #collapse_input full = None # code for the demo--this shouid be collapsed def demo(clear=False): """ ## Test/Demonstration with 3C 279 > Note that this also demonstrates using `nbdoc` to have a single Jupyterlab cell generate a document First, the weekly light curve: {out1} {fig1} Replot the figure with an expanded scale to see position of a flare: {fig2} {out3} {fig3} {out4} {fig4} Table of BB fits {bb_table} This can be compared with Figure 4 from the [Kerr paper](https://arxiv.org/pdf/1910.00140.pdf) {kerr_fig4} """ global full #with capture_print('Create full weekly light curve') as out1: full = WtLike('3C 279', clear=clear) fig1 = figure( full.plot(yscale='log', ylim=(0.2,20), figsize=(15,5), xlabel='MJD', fmt='.', fignum=1), caption='Full scale', width=600) fig2 = figure( full.plot( figsize=(15,5), xlabel='MJD', fmt='o', fignum=2, xlim=(57100, 57300),), width=600) with capture_print('Define orbit-based subset around large flare at MJD 57189') as out3: orbit = full.view((57186, 57191, 0)) fig3 = figure( orbit.plot(fmt='o', tzero=57186, fignum=3 ), width=600) with capture_print('Apply BB and overplot it with the cells on which it is based') as out4: bborbit = orbit.bb_view() fig4 = figure( bborbit.plot(fmt='o', tzero=57186, fignum=4), width=600) bb_table = orbit.fluxes kerr_fig4 = image('kerr_fig4.png', width=600, caption=None) return locals() if config.valid: nbdoc(demo, False) # - #hide from nbdev.export import notebook2script notebook2script() # !date
nbs/90_main.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 pyaudio import numpy as np import wave import os import datetime import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library import matplotlib.pyplot as plt import tkinter as tk from tkinter import messagebox # - ''' GPIO.setwarnings(False) # Ignore warning for now GPIO.setmode(GPIO.BOARD) # Use physical pin numbering GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input pin and set initial value to be pulled low (off) ''' # + #The following code comes from markjay4k as referenced below chunk = 512 samp_rate = 44100 form_1 = pyaudio.paInt16 chans = 1 record_secs = 30 #record time dev_index = 2 # - def about(): about_root=tk.Tk() w = 370 # width for the Tk root h = 270 # height for the Tk root # get screen width and height ws = about_root.winfo_screenwidth() # width of the screen hs = about_root.winfo_screenheight() # height of the screen # calculate x and y coordinates for the Tk root window x = (ws/2) - (w/2) y = (hs/2) - (h/2) # set the dimensions of the screen # and where it is placed about_root.geometry('%dx%d+%d+%d' % (w, h, x, y)) about_root.title('About Auscul Pi Console') label_version=tk.Label(about_root,text='Auscul Pi Console Version 1.0', font=('tahoma', 9)) label_version.place(x=90,y=30) label_copyright=tk.Label(about_root,text='Copyright (C) 2020', font=('tahoma', 9)) label_copyright.place(x=125,y=60) label_author=tk.Label(about_root,text='Author: <NAME>', font=('tahoma', 9)) label_author.place(x=125,y=90) label_institution=tk.Label(about_root,text='Shengjing Hospital of China Medical University', font=('tahoma', 9)) label_institution.place(x=65,y=120) label_author=tk.Label(about_root,text='License: The MIT License (MIT)', font=('tahoma', 9)) label_author.place(x=90,y=150) button_refresh=tk.Button(about_root, width=15, text='OK', command=about_root.destroy) button_refresh.place(x=135, y=210) about_root.mainloop() def replay(): #plays the audio file os.system("aplay " + filename_wav) def button_callback(): global frames, frames_numpy, filename_wav, filename_png, filename_np now = datetime.datetime.now() filename_wav = 'Wave_File_' + str(now)[:10] + now.strftime("_%H_%M_%S.wav") filename_png = 'Chart_File_' + str(now)[:10] + now.strftime("_%H_%M_%S.png") filename_np = 'Numpy_Array_File_' + str(now)[:10] + now.strftime("_%H_%M_%S") wav_output_filename = filename_wav png_output_filename = filename_png np_output_filename = filename_np p = pyaudio.PyAudio() #setup audio input stream stream = p.open(format = form_1, rate=samp_rate, channels=chans, input_device_index = dev_index, input=True, frames_per_buffer=chunk) # the code below is from the pyAudio library documentation referenced below #output stream setup player = p.open(format = form_1, rate=samp_rate, channels=chans, output=True, frames_per_buffer=chunk) text_status.delete('1.0', tk.END) text_status.insert('1.0', "Broadcasting & Recording") print("Broadcasting & Recording") frames = [] frames_numpy = [] for ii in range(0,int((samp_rate/chunk)*record_secs)): data = stream.read(chunk,exception_on_overflow = False) frames.append(data) data_numpy = np.fromstring(data, dtype=np.int16) player.write(data_numpy, chunk) frames_numpy.append(data_numpy) text_status.delete('1.0', tk.END) text_status.insert('1.0', "Finished recording") print("Finished recording") stream.stop_stream() stream.close() p.terminate() #creates wave file with audio read in #Code is from the wave file audio tutorial as referenced below wavefile = wave.open(wav_output_filename,'wb') wavefile.setnchannels(chans) wavefile.setsampwidth(p.get_sample_size(form_1)) wavefile.setframerate(samp_rate) wavefile.writeframes(b''.join(frames)) wavefile.close() #plays the audio file #os.system("aplay " + filename_wav) # Export the plot: ''' fig = plt.figure() s = fig.add_subplot(111) s.plot(frames_numpy) fig.savefig(png_output_filename, dpi=200) ''' np.save(np_output_filename, frames_numpy) ''' GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback) # Setup event on pin 10 rising edge message = input("Press enter to quit\n\n") # Run until someone presses enter GPIO.cleanup() # Clean up ''' # + root = tk.Tk() root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight())) #root.attributes('-fullscreen', True) root.title('Auscul Pi -- A ear-contactless stethoscope') # Text Editor text_status = tk.Text(root, width=20, height=1, font=('tahoma', 26), bd=2, wrap='none') text_status.place(x=10, y=20) # Buttons button_auscultate = tk.Button(root, text="Auscultate", width=10, font=('tahoma', 30), command=button_callback) button_auscultate.place(x=10, y=100) button_replay = tk.Button(root, text="Replay", width=10, font=('tahoma', 30), command=replay) button_replay.place(x=10, y=180) button_about = tk.Button(root, text="About...", width=6, font=('tahoma', 20), command=about) button_about.place(x=300, y=100) button_exit = tk.Button(root, text="Exit", width=6, font=('tahoma', 20), command=root.destroy) button_exit.place(x=300, y=180) root.mainloop()
.ipynb_checkpoints/AusculPi_main-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 # --- # brew install graphviz # pip install graphviz from graphviz import Digraph from micrograd.engine import Value # + def trace(root): nodes, edges = set(), set() def build(v): if v not in nodes: nodes.add(v) for child in v._prev: edges.add((child, v)) build(child) build(root) return nodes, edges def draw_dot(root, format='svg', rankdir='LR'): """ format: png | svg | ... rankdir: TB (top to bottom graph) | LR (left to right) """ assert rankdir in ['LR', 'TB'] nodes, edges = trace(root) dot = Digraph(format=format, graph_attr={'rankdir': rankdir}) #, node_attr={'rankdir': 'TB'}) for n in nodes: dot.node(name=str(id(n)), label = "{ data %.4f | grad %.4f }" % (n.data, n.grad), shape='record') if n._op: dot.node(name=str(id(n)) + n._op, label=n._op) dot.edge(str(id(n)) + n._op, str(id(n))) for n1, n2 in edges: dot.edge(str(id(n1)), str(id(n2)) + n2._op) return dot # - # a very simple example x = Value(1.0) y = (x * 2 + 1).relu() y.backward() draw_dot(y) # + # a simple 2D neuron import random from micrograd import nn random.seed(1337) n = nn.Neuron(2) x = [Value(1.0), Value(-2.0)] y = n(x) y.backward() dot = draw_dot(y) dot # - dot.render('gout')
trace_graph.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 # --- # # Serialising the Stars # # Noodles lets you run jobs remotely and store/retrieve results in case of duplicate jobs or reruns. These features rely on the *serialisation* (and not unimportant, reconstruction) of all objects that are passed between scheduled functions. Serialisation refers to the process of turning any object into a stream of bytes from which we can reconstruct a functionally identical object. "Easy enough!" you might think, just use `pickle`. # + from noodles.tutorial import display_text import pickle function = pickle.dumps(str.upper) message = pickle.dumps("Hello, Wold!") display_text("function: " + str(function)) display_text("message: " + str(message)) # - pickle.loads(function)(pickle.loads(message)) # However `pickle` cannot serialise all objects ... "Use `dill`!" you say; still the pickle/dill method of serializing is rather indiscriminate. Some of our objects may contain runtime data we can't or don't want to store, coroutines, threads, locks, open files, you name it. We work with a Sqlite3 database to store our data. An application might store gigabytes of numerical data. We don't want those binary blobs in our database, rather to store them externally in a HDF5 file. # There are many cases where a more fine-grained control of serialisation is in order. The bottom line being, that there is *no silver bullet solution*. Here we show some examples on how to customize the Noodles serialisation mechanism. # # ## The registry # # Noodles keeps a registry of `Serialiser` objects that know exactly how to serialise and reconstruct objects. This registry is specified to the backend when we call the one of the `run` functions. To make the serialisation registry visible to remote parties it is important that the registry can be imported. This is why it has to be a function of zero arguments (a *thunk*) returning the actual registry object. # # ```python # def registry(): # return Registry(...) # # run(workflow, # db_file='project-cache.db', # registry=registry) # ``` # The registry that should always be included is `noodles.serial.base`. This registry knows how to serialise basic Python dictionaries, lists, tuples, sets, strings, bytes, slices and all objects that are internal to Noodles. Special care is taken with objects that have a `__name__` attached and can be imported using the `__module__.__name__` combination. # # Registries can be composed using the `+` operator. For instance, suppose we want to use `pickle` as a default option for objects that are not in `noodles.serial.base`: # + import noodles def registry(): return noodles.serial.pickle() \ + noodles.serial.base() reg = registry() # - # Let's see what is made of our objects! display_text(reg.to_json([ "These data are JSON compatible!", 0, 1.3, None, {"dictionaries": "too!"}], indent=2)) # Great! JSON compatible data stays the same. Now try an object that JSON doesn't know about. display_text(reg.to_json({1, 2, 3}, indent=2), [1]) # Objects are encoded as a dictionary containing a `'_noodles'` key. So what will happen if we serialise an object the registry cannot possibly know about? Next we define a little astronomical class describing a star in the [Morgan-Keenan classification scheme](https://en.wikipedia.org/wiki/Stellar_classification). # + class Star(object): """Morgan-Keenan stellar classification.""" def __init__(self, spectral_type, number, luminocity_class): assert spectral_type in "OBAFGKM" assert number in range(10) self.spectral_type = spectral_type self.number = number self.luminocity_class = luminocity_class rigel = Star('B', 8, 'Ia') display_text(reg.to_json(rigel, indent=2), [4], max_width=60) # - # The registry obviously doesn't know about `Star`s, so it falls back to serialisation using `pickle`. The pickled data is further encoded using `base64`. This solution won't work if some of your data cannot be pickled. Also, if you're sensitive to aesthetics, the pickled output doesn't look very nice. # # ## *serialize* and *construct* # # One way to take control of the serialisation of your objects is to add the `__serialize__` and `__construct__` methods. class Star(object): """Morgan-Keenan stellar classification.""" def __init__(self, spectral_type, number, luminocity_class): assert spectral_type in "OBAFGKM" assert number in range(10) self.spectral_type = spectral_type self.number = number self.luminocity_class = luminocity_class def __str__(self): return f'{self.spectral_type}{self.number}{self.luminocity_class}' def __repr__(self): return f'Star.from_string(\'{str(self)}\')' @staticmethod def from_string(string): """Construct a new Star from a string describing the stellar type.""" return Star(string[0], int(string[1]), string[2:]) def __serialize__(self, pack): return pack(str(self)) @classmethod def __construct__(cls, data): return Star.from_string(data) # The class became quite a bit bigger. However, the `__str__`, `__repr__` and `from_string` methods are part of an interface you'd normally implement to make your class more useful. sun = Star('G', 2, 'V') print("The Sun is a", sun, "type star.") encoded_star = reg.to_json(sun, indent=2) display_text(encoded_star, [4]) # The `__serialize__` method takes one argument (besides `self`). The argument `pack` is a function that creates the data record with all handles attached. The reason for this construct is that it takes keyword arguments for special cases. # # ```python # def pack(data, ref=None, files=None): # pass # ``` # # * The `ref` argument, if given as `True`, will make sure that this object will not get reconstructed unnecessarily. One instance where this is incredibly useful, is if the object is a gigabytes large Numpy array. # * The `files` argument, when given, should be a list of filenames. This makes sure Noodles knows about the involvement of external files. # # The data passed to `pack` maybe of any type, as long as the serialisation registry knows how to serialise it. # # The `__construct__` method must be a *class method*. The `data` argument it is given can be expected to be identical to the data passed to the `pack` function at serialisation. decoded_star = reg.from_json(encoded_star) display_text(repr(decoded_star)) # ## Data classes # # Since Python 3.7, it is possible to define classes that are meant to contain "just data" as a `dataclass`. We'll forgo any data validation at this point. # + from dataclasses import dataclass, is_dataclass @dataclass class Star: """Morgan-Keenan stellar classification.""" spectral_type: str number: int luminocity_class: str def __str__(self): return f'{self.spectral_type}{self.number}{self.luminocity_class}' @staticmethod def from_string(string): """Construct a new Star from a string describing the stellar type.""" return Star(string[0], int(string[1]), string[2:]) # - # Data classes are recognised by Noodles and will be automatically serialised. altair = Star.from_string("A7V") encoded_star = reg.to_json(altair, indent=2) display_text(encoded_star, [2]) # ## Writing a Serialiser class (example with large data) # # Often, the class that needs serialising is not from your own package. In that case we need to write a specialised `Serialiser` class. For this purpose it may be nice to see how to serialise a Numpy array. This code is [already in Noodles](https://github.com/NLeSC/noodles/blob/master/noodles/serial/numpy.py); we will look at a trimmed down version. # # Given a NumPy array, we need to do two things: # # * Generate a token by which to identify the array; we will use a SHA-256 hash to do this. # * Store the array effeciently; the HDF5 fileformat is perfectly suited. # # ### SHA-256 # We need to hash the combination of datatype, array shape and the binary data: # + import numpy import hashlib import base64 def array_sha256(a): """Create a SHA256 hash from a Numpy array.""" dtype = str(a.dtype).encode() shape = numpy.array(a.shape) sha = hashlib.sha256() sha.update(dtype) sha.update(shape) sha.update(a.tobytes()) return base64.urlsafe_b64encode(sha.digest()).decode() # - # Is this useable for large data? Let's see how this scales (code to generate this plot is below): # # ![SHA-256 performance plot](./sha256-performance.svg) # So on my laptop, hashing an array of ~1 GB takes a little over three seconds, and it scales almost perfectly linear. Next we define the storage routine (and a loading routine, but that's a oneliner). # + import h5py def save_array_to_hdf5(filename, lock, array): """Save an array to a HDF5 file, using the SHA-256 of the array data as path within the HDF5. The `lock` is needed to prevent simultaneous access from multiple threads.""" hdf5_path = array_sha256(array) with lock, h5py.File(filename) as hdf5_file: if not hdf5_path in hdf5_file: dataset = hdf5_file.create_dataset( hdf5_path, shape=array.shape, dtype=array.dtype) dataset[...] = array hdf5_file.close() return hdf5_path # - # And put it all together in a class derived from `SerArray`. # + import filelock from noodles.serial import Serialiser, Registry class SerArray(Serialiser): """Serialises Numpy array to HDF5 file.""" def __init__(self, filename, lockfile): super().__init__(numpy.ndarray) self.filename = filename self.lock = filelock.FileLock(lockfile) def encode(self, obj, pack): key = save_array_to_hdf5(self.filename, self.lock, obj) return pack({ "filename": self.filename, "hdf5_path": key, }, files=[self.filename], ref=True) def decode(self, cls, data): with self.lock, h5py.File(self.filename) as hdf5_file: return hdf5_file[data["hdf5_path"]].value # - # We have to insert the serialiser into a new registry. # !rm -f tutorial.h5 # remove from previous run # + import noodles from noodles.tutorial import display_text def registry(): return Registry( parent=noodles.serial.base(), types={ numpy.ndarray: SerArray('tutorial.h5', 'tutorial.lock') }) reg = registry() # - # Now we can serialise our first Numpy array! encoded_array = reg.to_json(numpy.arange(10), host='localhost', indent=2) display_text(encoded_array, [6]) # Now, we should be able to read back the data directly from the HDF5. with h5py.File('tutorial.h5') as f: result = f['4Z8kdMg-CbjgTKKYlz6b-_-Tsda5VAJL44OheRB10mU='][()] print(result) # We have set the `ref` property to `True`, we can now read back the serialised object without dereferencing. This will result in a placeholder object containing only the encoded data: ref = reg.from_json(encoded_array) display_text(ref) display_text(vars(ref), max_width=60) # If we want to retrieve the data we should run `from_json` with `deref=True`: display_text(reg.from_json(encoded_array, deref=True)) # ## Appendix A: better parsing # If you're interested in doing a bit better in parsing generic expressions into objects, take a look at `pyparsing`. # !pip install pyparsing # The following code will parse the stellar types we used before: # + from pyparsing import Literal, replaceWith, OneOrMore, Word, nums, oneOf def roman_numeral_literal(string, value): return Literal(string).setParseAction(replaceWith(value)) one = roman_numeral_literal("I", 1) four = roman_numeral_literal("IV", 4) five = roman_numeral_literal("V", 5) roman_numeral = OneOrMore( (five | four | one).leaveWhitespace()) \ .setName("roman") \ .setParseAction(lambda s, l, t: sum(t)) integer = Word(nums) \ .setName("integer") \ .setParseAction(lambda t:int(t[0])) mkStar = oneOf(list("OBAFGKM")) + integer + roman_numeral # - list(mkStar.parseString('B2IV')) roman_class = { 'I': 'supergiant', 'II': 'bright giant', 'III': 'regular giant', 'IV': 'sub-giants', 'V': 'main-sequence', 'VI': 'sub-dwarfs', 'VII': 'white dwarfs' } # ## Appendix B: measuring SHA-256 performance # + import timeit import matplotlib.pyplot as plt plt.rcParams['font.family'] = "serif" from scipy import stats def benchmark(size, number=10): """Measure performance of SHA-256 hashing large arrays.""" data = numpy.random.uniform(size=size) return timeit.timeit( stmt=lambda: array_sha256(data), number=number) / number sizes = numpy.logspace(10, 25, 16, base=2, dtype=int) timings = numpy.array([[benchmark(size, 1) for size in sizes] for i in range(10)]) sizes_MB = sizes * 8 / 1e6 timings_ms = timings.mean(axis=0) * 1000 timings_err = timings.std(axis=0) * 1000 slope, intercept, _, _, _ = stats.linregress( numpy.log(sizes_MB[5:]), numpy.log(timings_ms[5:])) print("scaling:", slope, "(should be ~1)") print("speed:", numpy.exp(-intercept), "GB/s") ax = plt.subplot(111) ax.set_xscale('log', nonposx='clip') ax.set_yscale('log', nonposy='clip') ax.plot(sizes_MB, numpy.exp(intercept) * sizes_MB, label='{:.03} GB/s'.format(numpy.exp(-intercept))) ax.errorbar(sizes_MB, timings_ms, yerr=timings_err, marker='.', ls=':', c='k', label='data') ax.set_xlabel('size ($MB$)') ax.set_ylabel('time ($ms$)') ax.set_title('SHA-256 performance', fontsize=10) ax.legend() plt.savefig('sha256-performance.svg') plt.show() # - # ## Implementation # # A `Registry` object roughly consists of three parts. It works like a dictionary searching for `Serialiser`s based on the class or baseclass of an object. If an object cannot be identified through its class or baseclasses the `Registry` has a function hook that may use any test to determine the proper `Serialiser`. When neither the hook nor the dictionary give a result, there is a default fall-back option.
doc/source/serialisation.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 # --- # # Visualization import subprocess modelName="yolo2" # + # subprocess.call? # - subprocess.call("python net_drawer.py --input onnx/{}.onnx --output dot/{}.dot --embed_docstring".format(modelName,modelName), shell=True) subprocess.call("dot -Tsvg dot/{}.dot -o svg/{}.svg".format(modelName,modelName), shell=True) # # back up # ! mkdir dot svg # ! python net_drawer.py --input "onnx/squeezenet.onnx" --output "dot/squeezenet.dot" --embed_docstring --marked 1 --marked_list 2_3_4 # ! dot -Tsvg "dot/squeezenet.dot" -o "svg/squeezenet.svg" # ! python net_drawer.py --input "onnx/squeezenet.onnx" --output "dot/squeezenet.dot" --embed_docstring # ! dot -Tsvg "dot/squeezenet.dot" -o "svg/squeezenet.svg" # open .svg with Web # ! python net_drawer.py --input "onnx/vgg19.onnx" --output "dot/vgg19.dot" --embed_docstring # ! dot -Tsvg "dot/vgg19.dot" -o "svg/vgg19.svg"
5.Visualization.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 (''_dataInterpretation'': pipenv)' # language: python # name: python39064bitdatainterpretationpipenv7d89860b0d4449b6a38409f1c866e0d7 # --- # Checking the rater agreement (pct viewing time) for all frames import glob import pandas as pd import os import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import scipy.misc from tabulate import tabulate from sklearn.metrics import cohen_kappa_score import krippendorff # Load the ratings of the algorithm and the raters # + tags=[] # Load data from algorithmic tracking raterFiles = glob.glob("data/P*.txt") df_algoFiles = (pd.read_csv(f, header = None) for f in raterFiles) df_algo = pd.concat(df_algoFiles, ignore_index=True, axis = 0) # Load data from manual ratings raterFiles = glob.glob("data/data_Rater*.csv") df_raterFiles = (pd.read_csv(f, header = 0) for f in raterFiles) df_rater = pd.concat(df_raterFiles, ignore_index=True) # - # Prepare the data to get it into long format # + # Only take the last judgement of each rater df_rater.drop_duplicates(subset=['Rater', 'Frame', 'Trial'], keep='last', inplace = True) # Rename columns df_algo.columns = ["Trial", "Label", "1", "2", "3", "4", "5", "6", "VisiblePoints", "7", "8" ] # Add frame number column df_algo["Frame"] = df_algo.groupby(['Trial']).cumcount() # Add column for rater df_algo['Rater'] = 'Algorithm' # Set datatypes df_algo["Trial"] = df_algo["Trial"].astype("string") df_algo["Frame"] = df_algo["Frame"].astype("string") df_algo["Label"] = df_algo["Label"].astype("string") df_rater["Frame"] = df_rater["Frame"].astype("string") df_rater["Trial"] = df_rater["Trial"].astype("string") df_rater["Label"] = df_rater["Label"].astype("string") # Rename the labels to match the AOI from the algorithmic approach df_algo['Label'] = df_algo['Label'].str.replace("Nose","Head") df_algo['Label'] = df_algo['Label'].str.replace("Neck","Chest") df_algo['Label'] = df_algo['Label'].str.replace("LElbow","Left arm") df_algo['Label'] = df_algo['Label'].str.replace("RElbow","Right arm") df_algo['Label'] = df_algo['Label'].str.replace("RKnee","Right leg") df_algo['Label'] = df_algo['Label'].str.replace("LKnee","Left leg") df_algo['Label'] = df_algo['Label'].str.replace("MidHip","Pelvis") # Check the unique values # df_algo['Label'].unique() # - # Merge the data into Long format # + # Merge data frames df = pd.concat([df_algo, df_rater], join='outer', keys=['Trial', 'Frame', 'Rater', 'Label']).reset_index(drop=True) # only keep rows where all ratings are available def filterRows(group): if group.shape[0] > 1: return group df = df.groupby(['Trial', 'Frame']).apply(filterRows).reset_index(drop=True) df.ffill(inplace=True) df = df[['Trial', 'Label', 'VisiblePoints', 'Frame', 'Rater']] df.drop(columns=['VisiblePoints'], inplace=True) df.to_csv("results/DataLong.csv", index=False) # - # Descriptive statistics # + df.Trial.value_counts() # print(df.columns) df.groupby(['Trial', 'Frame']).count() df.groupby('Trial').count() # - # What happens when gaze is on "Other". For the human raters, take the mode (most chosen answer) # # + tags=[] def mode_of_frame(group): group['Mode'] = group.Label.mode()[0] group['isAnyOther'] = (group.Label == "Other").any() group['Algorithm_Label'] = group.loc[group.Rater == "Algorithm", 'Label'] return group df = df.groupby(['Trial', 'Frame']).apply(mode_of_frame) # - # Plot what happens when gaze is on "Other" # + # Other plot # %matplotlib inline mpl.style.use('default') # The data pct_algorithm = df.loc[(df.Rater == "Algorithm") & (df.Label == "Other"), 'Mode'].value_counts() pct_rater1 = df.loc[df.isAnyOther == 1, 'Algorithm_Label'].value_counts() # Plot settings # Requires probably on linux: sudo apt-get install dvipng texlive-latex-extra texlive-fonts-recommended cm-super mpl.rcParams.update( { 'font.family': 'serif', 'text.usetex': True, } ) # Figure settings for export pts_document_with = 600. # How wide is the page pts_per_inch = 1. / 72.27 figure_width = pts_document_with * pts_per_inch # Plot fig, axes = plt.subplots(nrows=1, ncols=2, figsize = (figure_width,4), sharey = True) axes[0].set_axisbelow(True) axes[1].set_axisbelow(True) pct_algorithm.plot(kind = 'bar', ax = axes[0], color = '#909090') pct_rater1.plot(kind = 'bar', ax = axes[1], color = '#909090') axes[0].grid(linestyle='dashed') axes[1].grid(linestyle='dashed') # fig.suptitle("AOI classification when subsetting on $Other$") axes[0].set_ylabel("Frames [N]") axes[0].set_title("Manual rating when algorithm judges $Other$") axes[1].set_title("Algorithmic rating when rater judge $Other$") # Save plt.savefig("plots/RaterOtherSubset.svg", bbox_inches='tight') # - # Calculate the agreement betweeen each rater and the algorithm # + # Create rating agreements between raters and algorithm, and among raters. Need data in wide format for this df = df.pivot(index=['Trial', 'Frame'], columns='Rater', values='Label') # Columns with comparison values df['Rater1_Algorithm'] = df.Rater1 == df.Algorithm df['Rater2_Algorithm'] = df.Rater2 == df.Algorithm df['Rater3_Algorithm'] = df.Rater3 == df.Algorithm df['Rater1_Rater2'] = df.Rater1 == df.Rater2 df['Rater1_Rater3'] = df.Rater1 == df.Rater3 df['Rater2_Rater3'] = df.Rater2 == df.Rater3 df['ManualRaters'] = ( (df.Rater1 == df.Rater2) & (df.Rater1 == df.Rater3) & (df.Rater2 == df.Rater3)) # Drop Na's because they can't be converted to int df.dropna(inplace=True) # Calculate the rating agreement rater1_algorithm_pct = ((df.Rater1_Algorithm.astype(int).sum() / df.shape[0]) * 100) rater2_algorithm_pct = ((df.Rater2_Algorithm.astype(int).sum() / df.shape[0]) * 100) rater3_algorithm_pct = ((df.Rater3_Algorithm.astype(int).sum() / df.shape[0]) * 100) rater1_rater2_pct = ((df.Rater1_Rater2.astype(int).sum() / df.shape[0]) * 100) rater1_rater3_pct = ((df.Rater1_Rater3.astype(int).sum() / df.shape[0]) * 100) rater2_rater3_pct = ((df.Rater2_Rater3.astype(int).sum() / df.shape[0]) * 100) rater_all_pct = ((df.ManualRaters.astype(int).sum() / df.shape[0]) * 100) # Back to long format df = df.stack().rename('Label').reset_index(['Frame', 'Trial', 'Rater']) # - # Inter rater reliability # + # Create an index variable for the labels [0 .. n] df['Label_ID'], _ = pd.factorize(df.Label) algorithm = df.loc[df.Rater == "Algorithm", 'Label_ID'] rater1 = df.loc[df.Rater == "Rater1", 'Label_ID'] rater2 = df.loc[df.Rater == "Rater2", 'Label_ID'] rater3 = df.loc[df.Rater == "Rater3", 'Label_ID'] rater1_rater2_kappa = cohen_kappa_score(rater1, rater2) rater1_rater3_kappa = cohen_kappa_score(rater1, rater3) rater2_rater3_kappa = cohen_kappa_score(rater2, rater3) rater1_algorithm_kappa = cohen_kappa_score(algorithm, rater1) rater2_algorithm_kappa = cohen_kappa_score(algorithm, rater2) rater3_algorithm_kappa = cohen_kappa_score(algorithm, rater3) # - # Inter rater reliability among manual raters and among all raters # + tags=[] # Initiate lists and rater tags manualList = [] manualRaters = ['Rater1', 'Rater2', 'Rater3'] def append_to_list(group, compareRaters, outList): subset = group[group.Rater.isin(compareRaters)] outList.append(subset.Label_ID.to_list()) # Run for both groups df.groupby(['Trial', 'Frame']).apply(append_to_list, manualRaters, manualList) # Run Krippendorffs kappa kappa_manualRaters = krippendorff.alpha(np.array(manualList).T) # - # Visualize and save the results and the data # + # Create table table = [ ["Comparison all AOI", "Percent agreement [%]", "Reliability [Cohens Kappa]"], ["Rater 1 vs. Algorithm", rater1_algorithm_pct, rater1_algorithm_kappa], ["Rater 2 vs. Algorithm", rater2_algorithm_pct, rater2_algorithm_kappa], ["Rater 3 vs. Algorithm", rater3_algorithm_pct, rater3_algorithm_kappa], ["Rater 1 vs. Rater 2", rater1_rater2_pct, rater1_rater2_kappa], ["Rater 1 vs. Rater 3", rater1_rater3_pct, rater1_rater3_kappa], ["Rater 2 vs. Rater 3", rater2_rater3_pct, rater2_rater3_kappa], ["Among manual raters", rater_all_pct , kappa_manualRaters], ] tabulate_table = tabulate( table, headers="firstrow", floatfmt=".2f", tablefmt="github") print(tabulate_table) # Save table with open('results/Reliability_AllAOI.txt', 'w') as f: f.write(tabulate_table) # Save data df.to_csv("results/data_all.csv") # + # %matplotlib inline mpl.style.use('default') # The data pct_algorithm = (df.loc[df.Rater == "Algorithm", 'Label'].value_counts() / df.loc[df.Rater == "Algorithm"].shape[0]) * 100 pct_rater1 = (df.loc[df.Rater == "Rater1", 'Label'].value_counts() / df.loc[df.Rater == "Rater1"].shape[0]) * 100 pct_rater2 = (df.loc[df.Rater == "Rater2", 'Label'].value_counts() / df.loc[df.Rater == "Rater2"].shape[0]) * 100 pct_rater3 = (df.loc[df.Rater == "Rater3", 'Label'].value_counts() / df.loc[df.Rater == "Rater3"].shape[0]) * 100 # Plot settings # Requires probably on linux: sudo apt-get install dvipng texlive-latex-extra texlive-fonts-recommended cm-super mpl.rcParams.update( { 'font.family': 'serif', 'text.usetex': True, } ) # Figure settings for export pts_document_with = 600. # How wide is the page pts_per_inch = 1. / 72.27 figure_width = pts_document_with * pts_per_inch # Plot fig, axes = plt.subplots(nrows=1, ncols=4, figsize = (figure_width,4), sharey = True) axes[0].set_axisbelow(True) axes[1].set_axisbelow(True) axes[2].set_axisbelow(True) axes[3].set_axisbelow(True) pct_algorithm.plot(kind = 'bar', ax = axes[0], color = '#909090') pct_rater1.plot(kind = 'bar', ax = axes[1], color = '#909090') pct_rater2.plot(kind = 'bar', ax = axes[2], color = '#909090') pct_rater3.plot(kind = 'bar', ax = axes[3], color = '#909090') axes[0].grid(linestyle='dashed') axes[1].grid(linestyle='dashed') axes[2].grid(linestyle='dashed') axes[3].grid(linestyle='dashed') # fig.suptitle("AOI classification") axes[0].set_ylabel("Viewing time [pct]") axes[0].set_title("Algorithmic Labeling") axes[1].set_title("Rater 1") axes[2].set_title("Rater 2") axes[3].set_title("Rater 3") # Save plt.savefig("plots/RaterComparison_All.svg", bbox_inches='tight') # + # How many percent were classified as Other by either party? rater_other = (pct_rater1['Other'] + pct_rater2['Other'] + pct_rater3['Other']) / 3 rater_other_std = np.std([pct_rater1['Other'], pct_rater2['Other'], pct_rater3['Other']]) print(f"Algorithm judged {pct_algorithm['Other']:.2f}% as Other with std {rater_other_std:2f}") print(f"Rater judged {rater_other:.1f}% as Other") table = [ ["Comparison semantic segmentation", "Frames with gaze located on human shape [%]"], ["Algorithm", 100-pct_algorithm['Other']], ["Rater 1", 100-pct_rater1['Other']], ["Rater 2", 100-pct_rater2['Other']], ["Rater 3", 100-pct_rater3['Other']] ] tabulate_table = tabulate( table, headers="firstrow", floatfmt=".2f", tablefmt="latex") print(tabulate_table) df.to_csv("results/data_HumanClassified.csv") # + # F-1 scores # Create rating agreements between raters and algorithm, and among raters. Need data in wide format for this df = df.pivot(index=['Trial', 'Frame'], columns='Rater', values='Label') # Columns with comparison values df['Rater1_Algorithm'] = df.Rater1 == df.Algorithm df['Rater2_Algorithm'] = df.Rater2 == df.Algorithm df['Rater3_Algorithm'] = df.Rater3 == df.Algorithm df['Rater1_Rater2'] = df.Rater1 == df.Rater2 df['Rater1_Rater3'] = df.Rater1 == df.Rater3 df['Rater2_Rater3'] = df.Rater2 == df.Rater3 df['ManualRaters'] = ( (df.Rater1 == df.Rater2) & (df.Rater1 == df.Rater3) & (df.Rater2 == df.Rater3)) print(f"Unanimous agreement in {df.ManualRaters.sum()} frames) # + # Take data where unanimous agreement between raters df_unanimous = df.loc[df['ManualRaters'] == True, :] print(df_unanimous.Rater1) # -
_dataInterpretation/rating_agreement_all.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 # --- # + [markdown] tags=[] # Inaugural Project (Note: untoggle auto-numbering in table of contents) # ================= # - # We start by importing **magics** to autoreload modules and the **packages** we use for solutions. # + # Importing of relevant packages. import numpy as np from scipy import optimize import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm # for colormaps import random as random # autoreload modules when code is run. Otherwise, python will not see recent changes. # %load_ext autoreload # %autoreload 2 # %matplotlib inline # - # ## Question 1 # All the functions for solving the problem are written in the `opgave1.py` file and **imported**: # $$ u(z) = \frac{z^{1+\vartheta}}{1+\vartheta} $$ # # $$ \pi(p,q) = pq $$ # # $$ V_{0} = pu(y-x) + (1-p)u(x) $$ # # $$ V(q;\pi) = pu(y-x+q-\pi(p,q))+(1-p)u(y-\pi(p,q)) $$ # # $$ q^*=\arg\max_{q\in[0;x]}V(q;\pi) $$ # Import the functions to solve question 1 problems. import opgave1 as opg1 # *i)* The function `solve_insured(p,x,y,theta)` is the **constructed function** that takes *(x,y,p)* as arguments and returns the agents' optimal insurance coverage. # We define the **parameters** given from the assignment text: $$ y=1, p=0.2 \quad \text{and} \quad \vartheta=-2 $$ y = 1 p = 0.2 theta = -2.0 # *ii)* We **allocate** the arrays used for the solution. `grid_x` makes a grid of x in the range *\[0.01;0.9\]* num_x = 90 grid_x = np.linspace(0.01,0.9,num_x) grid_q = np.zeros(num_x) # *iii)* We call the **solver** that calculates *q** for each *x* for i,x in enumerate(grid_x): grid_q[i] = opg1.solve_insured(p,x,y,theta) print(f'x = {x:.2f} -> q* = {grid_q[i]:.2f}') # *iv)* We **plot** the optimal insurance coverage *q*s for given monetary losses *xs*: plt.plot(grid_x, grid_q, color = "black") plt.title("Figure 1: Optimal insurance coverage given monetary loss") plt.xlabel("Monetary loss") plt.ylabel("Optimal insurance coverage") plt.show() # *iv continued)* The graph indicates that the agents' should buy insurance for all of their expected monetary loss. # # Question 2 # All the functions for solving the problem are written in the `opgave2.py` file and **imported**: # $$ u(z) = \frac{z^{1+\vartheta}}{1+\vartheta} $$ # # $$ V_{0} = pu(y-x) + (1-p)u(x) $$ # # $$ V(q;\pi) = pu(y-x+q-\pi(p,q))+(1-p)u(y-\pi(p,q)) $$ # # $$ V(q;\tilde{\pi}) = V_{0} $$ # Import the functions to solve question 2 problems. import opgave2 as opg2 # *i)* We define the **parameter** *x* to 0.6 like in the assignment. $$ x=0.6 $$ # We construct a grid over insurance coverages over *\[0.01;0.6\]* which we call `q_grid`. x=0.6 q_num = 60 q_grid = np.linspace(0.01,0.60,q_num) v_grid = np.zeros(q_num) v0_grid = np.zeros(q_num) pi_1_grid = np.zeros(q_num) # *ii)* We loop over each element in the grid of insurance coverages and find the corresponding # premium policy such that: $$ V (q; \tilde{\pi}) = V_0$$ # Looping over all the q's to find corresponding pi's such that insured utility equal uninsured utility for i,q in enumerate(q_grid): v0_grid[i] = opg2.expected_uninsured(p,y,x,theta) pi_1_grid[i] = opg2.solve_for_pi_1(q,p,y,x,theta) v_grid[i] = opg2.expected_insured(q, pi_1_grid[i],p,x,y,theta) print(f'q = {q:.2f} -> tilde(pi) = {pi_1_grid[i]:.5f} -> v0 = {v0_grid[i]:.2f} -> v = {v_grid[i]:.2f}') # *iii)* We **plot** the maximum **acceptable premiums** where the the agents is willing to buy, i.e., where there expected utility from having bought the insurance is equal to the expected utility from not being insured, and the **minimum premiums** that the insurance company wants to charge for given insurance coverages, i.e. where the expected costs for the company insuring the agents is equal to the expected revenues the agents is paying the company. # + #Calculating the minimum premium pi_old_grid = p*q_grid # Defining the plot layout # Graphing the acceptable premiums, and defining graph name and color. plt.plot(q_grid, pi_1_grid, color='r', label='$\pi_{tilde}$: Maximum acceptable premiums for agents') # Graphing the minimum premiums, and defining graph name and color plt.plot(q_grid, pi_old_grid, color='b', label='$\pi$: Minimum acceptable premiums for company') # Defining the label name of the x-axis. plt.xlabel("Coverage ammount") # Defining the label name of the y-axis. plt.ylabel("Premium policy") # Defining the name of the figure title. plt.title("Figure 2: The minimum and acceptable premiums") # Adding legend, which helps us recognize the curve according to it's color plt.legend() # To load the display window plt.show() # - # *iv continued)* The area between the two curves is the **feasible premium policies**. In this area the firm has weakly positive profits and the agents have weakly higher expected utility from buying the insurance than not buying insurance. This means that in this area is is better for both agents and company to be in the market than not. # # Question 3 # All the functions for solving the problem are written in the `opgave3.py` file and **imported**: # $$ u(z) = \frac{z^{1+\vartheta}}{1+\vartheta} $$ # # $$ V(\gamma, \pi) = \int_{0}^{1}u(y-(1-\gamma)x-\pi)f(x)dx $$ # # *i)* The function `V_utility(gamma,pi,theta,x,y,beta,alpha):` is a function that **computes the agents' expected utility by monte carlo integration** # Import the functions to solve question 3 problems. import opgave3 as opg3 # *i continued)* Defining **parameters** for the random draw of a random x. Setting **10,000 draws**. # Sets number of draws N = 10000 # Defining parameters and variables. alpha = 2 beta = 7 gamma = np.nan pi = np.nan x = np.random.beta(alpha, beta, size=N) # *ii)* We consider the in assignment given insurance policies: # $$ (\gamma,\pi) = (0.9,0.2) $$ # $$ (\gamma,\pi) = (0.45,0.1) $$ # We calculate which insurance policy is **preferable for the agent**: # + #Defining insurence policies policy1 = opg3.V_utility(0.9,0.2,theta,x,y,beta,alpha) policy2 = opg3.V_utility(0.45,0.1,theta,x,y,beta,alpha) print(f'For insurance policy 1, agent\'s value is {policy1:.3f}. For insurance policy 2, agent\'s value is {policy2:.3f}') if policy1 > policy2: print(f'Insurance policy 1 is preferable to the agent') else: print(f'Insurance policy 2 is preferable to the agent') # - # We find that insurance policy 1 is **preferable** to the agent in this case. # # Question 4 # All the functions for solving the problem are written in the `opgave4.py` file and **imported**: # $$ u(z) = \frac{z^{1+\vartheta}}{1+\vartheta} $$ # # $$ V(\gamma, \pi) = \int_{0}^{1}u(y-(1-\gamma)x-\pi)f(x)dx $$ import opgave4 as opg4 # Defining **parameters** gamma = 0.95 pi = np.nan x = np.random.beta(alpha, beta) # *i)* We calculate the profit maximizing premium policy given a customer wanting an insurance coverage og 0.95 print(f'The profit maximizing premium policy pi* = {opg4.solve_for_pi_rand(gamma,pi,theta,x,y,beta,alpha):.3f}')
inauguralproject/inauguralproject.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="gtuicEyI9znr" # # Bias # + [markdown] colab_type="text" id="CzKJcDsE93Ko" # ### Goals # In this notebook, you're going to explore a way to identify some biases of a GAN using a classifier, in a way that's well-suited for attempting to make a model independent of an input. Note that not all biases are as obvious as the ones you will see here. # # ### Learning Objectives # 1. Be able to distinguish a few different kinds of bias in terms of demographic parity, equality of odds, and equality of opportunity (as proposed [here](http://m-mitchell.com/papers/Adversarial_Bias_Mitigation.pdf)). # 2. Be able to use a classifier to try and detect biases in a GAN. # + [markdown] colab_type="text" id="a5Qyl-AnEww0" # # ## Challenges # # One major challenge in assessing bias in GANs is that you still want your generator to be able to generate examples of different values of a protected class—the class you would like to mitigate bias against. While a classifier can be optimized to have its output be independent of a protected class, a generator which generates faces should be able to generate examples of various protected class values. # # When you generate examples with various values of a protected class, you don’t want those examples to correspond to any properties that aren’t strictly a function of that protected class. This is made especially difficult since many protected classes (e.g. gender or ethnicity) are social constructs, and what properties count as “a function of that protected class” will vary depending on who you ask. It’s certainly a hard balance to strike. # # Moreover, a protected class is rarely used to condition a GAN explicitly, so it is often necessary to resort to somewhat post-hoc methods (e.g. using a classifier trained on relevant features, which might be biased itself). # # In this assignment, you will learn one approach to detect potential bias, by analyzing correlations in feature classifications on the generated images. # + [markdown] colab_type="text" id="wEX6YjIbYLFC" # ## Getting Started # # As you have done previously, you will start by importing some useful libraries and defining a visualization function for your images. You will also use the same generator and basic classifier from previous weeks. # + [markdown] colab_type="text" id="_xe0xOhIQswC" # #### Packages and Visualization # + colab={} colab_type="code" id="7_10LYXRsrWo" import torch import numpy as np from torch import nn from tqdm.auto import tqdm from torchvision import transforms from torchvision.utils import make_grid from torchvision.datasets import CelebA from torch.utils.data import DataLoader import matplotlib.pyplot as plt torch.manual_seed(0) # Set for our testing purposes, please do not change! def show_tensor_images(image_tensor, num_images=16, size=(3, 64, 64), nrow=3): ''' Function for visualizing images: Given a tensor of images, number of images, size per image, and images per row, plots and prints the images in an uniform grid. ''' image_tensor = (image_tensor + 1) / 2 image_unflat = image_tensor.detach().cpu() image_grid = make_grid(image_unflat[:num_images], nrow=nrow) plt.imshow(image_grid.permute(1, 2, 0).squeeze()) plt.show() # + [markdown] colab_type="text" id="zv9hWdknQziZ" # #### Generator and Noise # + colab={} colab_type="code" id="3zYUIaz6Qz9_" class Generator(nn.Module): ''' Generator Class Values: z_dim: the dimension of the noise vector, a scalar im_chan: the number of channels of the output image, a scalar (CelebA is rgb, so 3 is your default) hidden_dim: the inner dimension, a scalar ''' def __init__(self, z_dim=10, im_chan=3, hidden_dim=64): super(Generator, self).__init__() self.z_dim = z_dim # Build the neural network self.gen = nn.Sequential( self.make_gen_block(z_dim, hidden_dim * 8), self.make_gen_block(hidden_dim * 8, hidden_dim * 4), self.make_gen_block(hidden_dim * 4, hidden_dim * 2), self.make_gen_block(hidden_dim * 2, hidden_dim), self.make_gen_block(hidden_dim, im_chan, kernel_size=4, final_layer=True), ) def make_gen_block(self, input_channels, output_channels, kernel_size=3, stride=2, final_layer=False): ''' Function to return a sequence of operations corresponding to a generator block of DCGAN; a transposed convolution, a batchnorm (except in the final layer), and an activation. Parameters: input_channels: how many channels the input feature representation has output_channels: how many channels the output feature representation should have kernel_size: the size of each convolutional filter, equivalent to (kernel_size, kernel_size) stride: the stride of the convolution final_layer: a boolean, true if it is the final layer and false otherwise (affects activation and batchnorm) ''' if not final_layer: return nn.Sequential( nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride), nn.BatchNorm2d(output_channels), nn.ReLU(inplace=True), ) else: return nn.Sequential( nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride), nn.Tanh(), ) def forward(self, noise): ''' Function for completing a forward pass of the generator: Given a noise tensor, returns generated images. Parameters: noise: a noise tensor with dimensions (n_samples, z_dim) ''' x = noise.view(len(noise), self.z_dim, 1, 1) return self.gen(x) def get_noise(n_samples, z_dim, device='cpu'): ''' Function for creating noise vectors: Given the dimensions (n_samples, z_dim) creates a tensor of that shape filled with random numbers from the normal distribution. Parameters: n_samples: the number of samples to generate, a scalar z_dim: the dimension of the noise vector, a scalar device: the device type ''' return torch.randn(n_samples, z_dim, device=device) # + [markdown] colab_type="text" id="KeSVrnG1RAy4" # #### Classifier # + colab={} colab_type="code" id="VqF54g4qRD-X" class Classifier(nn.Module): ''' Classifier Class Values: im_chan: the number of channels of the output image, a scalar (CelebA is rgb, so 3 is your default) n_classes: the total number of classes in the dataset, an integer scalar hidden_dim: the inner dimension, a scalar ''' def __init__(self, im_chan=3, n_classes=2, hidden_dim=64): super(Classifier, self).__init__() self.classifier = nn.Sequential( self.make_classifier_block(im_chan, hidden_dim), self.make_classifier_block(hidden_dim, hidden_dim * 2), self.make_classifier_block(hidden_dim * 2, hidden_dim * 4, stride=3), self.make_classifier_block(hidden_dim * 4, n_classes, final_layer=True), ) def make_classifier_block(self, input_channels, output_channels, kernel_size=4, stride=2, final_layer=False): ''' Function to return a sequence of operations corresponding to a classifier block; a convolution, a batchnorm (except in the final layer), and an activation (except in the final layer). Parameters: input_channels: how many channels the input feature representation has output_channels: how many channels the output feature representation should have kernel_size: the size of each convolutional filter, equivalent to (kernel_size, kernel_size) stride: the stride of the convolution final_layer: a boolean, true if it is the final layer and false otherwise (affects activation and batchnorm) ''' if not final_layer: return nn.Sequential( nn.Conv2d(input_channels, output_channels, kernel_size, stride), nn.BatchNorm2d(output_channels), nn.LeakyReLU(0.2, inplace=True), ) else: return nn.Sequential( nn.Conv2d(input_channels, output_channels, kernel_size, stride), ) def forward(self, image): ''' Function for completing a forward pass of the classifier: Given an image tensor, returns an n_classes-dimension tensor representing classes. Parameters: image: a flattened image tensor with im_chan channels ''' class_pred = self.classifier(image) return class_pred.view(len(class_pred), -1) # + [markdown] colab_type="text" id="ZKyIEkWnYZ6J" # ## Specifying Parameters # You will also need to specify a few parameters before you begin training: # * z_dim: the dimension of the noise vector # * batch_size: the number of images per forward/backward pass # * device: the device type # + colab={} colab_type="code" id="-GLwMw2v8Vat" z_dim = 64 batch_size = 128 device = 'cuda' # + [markdown] colab_type="text" id="HSNXcCTfYVzY" # ## Train a Classifier (Optional) # # You're welcome to train your own classifier with this code, but you are provide a pre-trained one based on this architecture here which you can load and use in the next section. # + colab={} colab_type="code" id="HwBG8BGq64OJ" # You can run this code to train your own classifier, but there is a provided pre-trained one # If you'd like to use this, just run "train_classifier(filename)" # To train and save a classifier on the label indices to that filename def train_classifier(filename): import seaborn as sns import matplotlib.pyplot as plt # You're going to target all the classes, so that's how many the classifier will learn label_indices = range(40) n_epochs = 3 display_step = 500 lr = 0.001 beta_1 = 0.5 beta_2 = 0.999 image_size = 64 transform = transforms.Compose([ transforms.Resize(image_size), transforms.CenterCrop(image_size), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ]) dataloader = DataLoader( CelebA(".", split='train', download=True, transform=transform), batch_size=batch_size, shuffle=True) classifier = Classifier(n_classes=len(label_indices)).to(device) class_opt = torch.optim.Adam(classifier.parameters(), lr=lr, betas=(beta_1, beta_2)) criterion = nn.BCEWithLogitsLoss() cur_step = 0 classifier_losses = [] # classifier_val_losses = [] for epoch in range(n_epochs): # Dataloader returns the batches for real, labels in tqdm(dataloader): real = real.to(device) labels = labels[:, label_indices].to(device).float() class_opt.zero_grad() class_pred = classifier(real) class_loss = criterion(class_pred, labels) class_loss.backward() # Calculate the gradients class_opt.step() # Update the weights classifier_losses += [class_loss.item()] # Keep track of the average classifier loss ### Visualization code ### if cur_step % display_step == 0 and cur_step > 0: class_mean = sum(classifier_losses[-display_step:]) / display_step print(f"Step {cur_step}: Classifier loss: {class_mean}") step_bins = 20 x_axis = sorted([i * step_bins for i in range(len(classifier_losses) // step_bins)] * step_bins) sns.lineplot(x_axis, classifier_losses[:len(x_axis)], label="Classifier Loss") plt.legend() plt.show() torch.save({"classifier": classifier.state_dict()}, filename) cur_step += 1 # Uncomment the last line to train your own classfier - this line will not work in Coursera. # If you'd like to do this, you'll have to download it and run it, ideally using a GPU. # train_classifier("filename") # + [markdown] colab_type="text" id="Iu1TcEA3aSSI" # ## Loading the Pre-trained Models # # You can now load the pre-trained generator (trained on CelebA) and classifier using the following code. If you trained your own classifier, you can load that one here instead. However, it is suggested that you first go through the assignment using the pre-trained one. # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="OgrLujk_tYDu" outputId="d6ba10d8-1579-44ee-a26a-a224b32a47c5" import torch gen = Generator(z_dim).to(device) gen_dict = torch.load("pretrained_celeba.pth", map_location=torch.device(device))["gen"] gen.load_state_dict(gen_dict) gen.eval() n_classes = 40 classifier = Classifier(n_classes=n_classes).to(device) class_dict = torch.load("pretrained_classifier.pth", map_location=torch.device(device))["classifier"] classifier.load_state_dict(class_dict) classifier.eval() print("Loaded the models!") opt = torch.optim.Adam(classifier.parameters(), lr=0.01) # + [markdown] colab_type="text" id="AspUMgXOMS1b" # ## Feature Correlation # Now you can generate images using the generator. By also using the classifier, you will be generating images with different amounts of the "male" feature. # # You are welcome to experiment with other features as the target feature, but it is encouraged that you initially go through the notebook as is before exploring. # + colab={} colab_type="code" id="kASNj6nLz7kh" # First you generate a bunch of fake images with the generator n_images = 256 fake_image_history = [] classification_history = [] grad_steps = 30 # How many gradient steps to take skip = 2 # How many gradient steps to skip in the visualization feature_names = ["5oClockShadow", "ArchedEyebrows", "Attractive", "BagsUnderEyes", "Bald", "Bangs", "BigLips", "BigNose", "BlackHair", "BlondHair", "Blurry", "BrownHair", "BushyEyebrows", "Chubby", "DoubleChin", "Eyeglasses", "Goatee", "GrayHair", "HeavyMakeup", "HighCheekbones", "Male", "MouthSlightlyOpen", "Mustache", "NarrowEyes", "NoBeard", "OvalFace", "PaleSkin", "PointyNose", "RecedingHairline", "RosyCheeks", "Sideburn", "Smiling", "StraightHair", "WavyHair", "WearingEarrings", "WearingHat", "WearingLipstick", "WearingNecklace", "WearingNecktie", "Young"] n_features = len(feature_names) # Set the target feature target_feature = "Male" target_indices = feature_names.index(target_feature) noise = get_noise(n_images, z_dim).to(device) new_noise = noise.clone().requires_grad_() starting_classifications = classifier(gen(new_noise)).cpu().detach() # Additive direction (more of a feature) for i in range(grad_steps): opt.zero_grad() fake = gen(new_noise) fake_image_history += [fake] classifications = classifier(fake) classification_history += [classifications.cpu().detach()] fake_classes = classifications[:, target_indices].mean() fake_classes.backward() new_noise.data += new_noise.grad / grad_steps # Subtractive direction (less of a feature) new_noise = noise.clone().requires_grad_() for i in range(grad_steps): opt.zero_grad() fake = gen(new_noise) fake_image_history += [fake] classifications = classifier(fake) classification_history += [classifications.cpu().detach()] fake_classes = classifications[:, target_indices].mean() fake_classes.backward() new_noise.data -= new_noise.grad / grad_steps classification_history = torch.stack(classification_history) # - print(classification_history.shape) print(starting_classifications[None, :, :].shape) # + [markdown] colab_type="text" id="z7sGUfJlDZst" # You've now generated image samples, which have increasing or decreasing amounts of the target feature. You can visualize the way in which that affects other classified features. The x-axis will show you the amount of change in your target feature and the y-axis shows how much the other features change, as detected in those images by the classifier. Together, you will be able to see the covariance of "male-ness" and other features. # # You are started off with a set of features that have interesting associations with "male-ness", but you are welcome to change the features in `other_features` with others from `feature_names`. # + colab={"base_uri": "https://localhost:8080/", "height": 349} colab_type="code" id="5Q0b24CHDX8A" outputId="e325ebc5-9f2e-44a5-ee7c-70d391880350" import seaborn as sns # Set the other features other_features = ["Smiling", "Bald", "Young", "HeavyMakeup", "Attractive"] classification_changes = (classification_history - starting_classifications[None, :, :]).numpy() for other_feature in other_features: other_indices = feature_names.index(other_feature) with sns.axes_style("darkgrid"): sns.regplot( classification_changes[:, :, target_indices].reshape(-1), classification_changes[:, :, other_indices].reshape(-1), fit_reg=True, truncate=True, ci=99, x_ci=99, x_bins=len(classification_history), label=other_feature ) plt.xlabel(target_feature) plt.ylabel("Other Feature") plt.title(f"Generator Biases: Features vs {target_feature}-ness") plt.legend(loc=1) plt.show() # + [markdown] colab_type="text" id="6QOuJWDfZzpK" # This correlation detection can be used to reduce bias by penalizing this type of correlation in the loss during the training of the generator. However, currently there is no rigorous and accepted solution for debiasing GANs. A first step that you can take in the right direction comes before training the model: make sure that your dataset is inclusive and representative, and consider how you can mitigate the biases resulting from whatever data collection method you used—for example, getting a representative labelers for your task. # # It is important to note that, as highlighted in the lecture and by many researchers including [<NAME> and <NAME>](https://sites.google.com/view/fatecv-tutorial/schedule), a diverse dataset alone is not enough to eliminate bias. Even diverse datasets can reinforce existing structural biases by simply capturing common social biases. Mitigating these biases is an important and active area of research. # # #### Note on CelebA # You may have noticed that there are obvious correlations between the feature you are using, "male", and other seemingly unrelates features, "smiling" and "young" for example. This is because the CelebA dataset labels had no serious consideration for diversity. The data represents the biases their labelers, the dataset creators, the social biases as a result of using a dataset based on American celebrities, and many others. Equipped with knowledge about bias, we trust that you will do better in the future datasets you create. # + [markdown] colab_type="text" id="yHXjgqehz4vn" # ## Quantification # Finally, you can also quantitatively evaluate the degree to which these factors covary. # # <details> # # <summary> # <font size="3" color="green"> # <b>Optional hints for <code><font size="4">get_top_covariances</font></code></b> # </font> # </summary> # # 1. You will likely find the following function useful: [np.cov](https://numpy.org/doc/stable/reference/generated/numpy.cov.html). # 2. You will probably find it useful to [reshape](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html) the input. # 3. The target feature should not be included in the outputs. # 4. Feel free to use any reasonable method to get the top-n elements. # </details> # + colab={} colab_type="code" id="ZqoowVhFGzOH" # UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED CELL: get_top_covariances def get_top_covariances(classification_changes, target_index, top_n=10): ''' Function for getting the top n covariances: Given a list of classification changes and the index of the target feature, returns (1) a list or tensor (numpy or torch) of the indices corresponding to the n most covarying factors in terms of absolute covariance and (2) a list or tensor (numpy or torch) of the degrees to which they covary. Parameters: classification_changes: relative changes in classifications of each generated image resulting from optimizing the target feature (see above for a visualization) target_index: the index of the target feature, a scalar top_n: the top most number of elements to return, default is 10 ''' #### START CODE HERE #### flattened_changes = classification_changes.reshape(-1, classification_changes.shape[-1]).T covariances = np.cov(flattened_changes) relevant_indices = torch.topk(torch.Tensor(np.abs(covariances[target_index])), top_n + 1)[1][1:].numpy() highest_covariances = covariances[target_index, relevant_indices] #### END CODE HERE #### return relevant_indices, highest_covariances # + # UNIT TEST from torch.distributions import MultivariateNormal mean = torch.Tensor([0, 0, 0, 0]) covariance = torch.Tensor( [[10, 2, -0.5, 5], [2, 11, 5, 4], [-0.5, 5, 10, 2], [5, 4, 2, 11]] ) independent_dist = MultivariateNormal(mean, covariance) samples = independent_dist.sample((60 * 128,)) foo = samples.reshape(60, 128, samples.shape[-1]) relevant_indices, highest_covariances = get_top_covariances(foo, 0, top_n=3) assert (tuple(relevant_indices) == (3, 1, 2)) assert np.all(np.abs(highest_covariances - [5, 2, -0.5]) < 0.5 ) relevant_indices, highest_covariances = get_top_covariances(foo, 1, top_n=3) assert (tuple(relevant_indices) == (2, 3, 0)) assert np.all(np.abs(highest_covariances - [5, 4, 2]) < 0.5 ) relevant_indices, highest_covariances = get_top_covariances(foo, 2, top_n=2) assert (tuple(relevant_indices) == (1, 3)) assert np.all(np.abs(highest_covariances - [5, 2]) < 0.5 ) relevant_indices, highest_covariances = get_top_covariances(foo, 3, top_n=2) assert (tuple(relevant_indices) == (0, 1)) assert np.all(np.abs(highest_covariances - [5, 4]) < 0.5 ) print("All tests passed") # + colab={} colab_type="code" id="cRdY3D3Yndwr" relevant_indices, highest_covariances = get_top_covariances(classification_changes, target_indices, top_n=10) print(relevant_indices) assert relevant_indices[9] == 34 assert len(relevant_indices) == 10 assert highest_covariances[8] - (-1.2418) < 1e-3 for index, covariance in zip(relevant_indices, highest_covariances): print(f"{feature_names[index]} {covariance:f}") # + [markdown] colab_type="text" id="TYKG365iKCNR" # One of the major sources of difficulty with identifying bias and fairness, as discussed in the lectures, is that there are many ways you might reasonably define these terms. Here are three ways that are computationally useful and [widely referenced](http://m-mitchell.com/papers/Adversarial_Bias_Mitigation.pdf). They are, by no means, the only definitions of fairness (see more details [here](https://developers.google.com/machine-learning/glossary/fairness)): # # # 1. Demographic parity: the overall distribution of the predictions made by a predictor is the same for different values of a protected class. # 2. Equality of odds: all else being equal, the probability that you predict correctly or incorrectly is the same for different values of a protected class. # 2. Equality of opportunity: all else being equal, the probability that you predict correctly is the same for different valus of a protected class (weaker than equality of odds). # # With GANs also being used to help downstream classifiers (you will see this firsthand in future assignments), these definitions of fairness will impact, as well as depend on, your downstream task. It is important to work towards creating a fair GAN according to the definition you choose. Pursuing any of them is virtually always better than blindly labelling data, creating a GAN, and sampling its generations. # -
2 - Build Better Generative Adversarial Networks/Week 2/C2W2_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 # name: python3 # --- # + [markdown] id="PZBWcFtBZXd5" # # #Linear Regression # + [markdown] id="uegblV7M8OxO" # ##(0) Load the data -> Standardize data -> Split the dataset # + id="rIyxjzSsZI--" colab={"base_uri": "https://localhost:8080/"} outputId="fc80c94e-e5ed-46bd-f984-c2425de4f5cb" import numpy as np import pandas as pd data_x_df = pd.read_csv('data_X.csv') data_t_df = pd.read_csv('data_T.csv') X = np.array(data_x_df) T = np.array(data_t_df) # standardize X = (X-X.mean(axis=0))/X.std(axis=0) #T = (T-T.mean(axis=0))/T.std(axis=0) # 80% training dataset and 20% test dataset X_SIZE = X.shape[0] ratio = 8/10 trainRange = int(X_SIZE*ratio) #num of training data x_train = X[:trainRange] x_test = X[trainRange:] y_train = T[:trainRange] y_test = T[trainRange:] print("x_train shape {} and size {}".format(x_train.shape,x_train.size)) print("y_train shape {} and size {}".format(y_train.shape,y_train.size)) print("x_test shape {} and size {}".format(x_test.shape,x_test.size)) print("y_test shape {} and size {}".format(y_test.shape,y_test.size)) # + [markdown] id="CFdoxBiIzwup" # ##(1) Feature selection # # # # + [markdown] id="J1yGEzL7gMAr" # ### Define model # + id="G1r8NZLUeM1N" class LinearRegression: def __init__(self,x,M): self.M = M self.size = x.shape[0] self.feature_num = x.shape[1] self.weight = None def closed_form(self, x, y, _lambda=0, regularize = False): if not regularize: # Using Normal Equation to find w = (xT x)^(-1) xT y xTx = np.dot(x.T, x) inv = np.linalg.inv(np.matrix(xTx)) w = np.dot(np.dot(inv, x.T), y) self.weight = w else: # w = (lambdaI + xT x)^(-1) xT y xTx = np.dot(x.T, x) inv = np.linalg.inv(np.eye(xTx.shape[0]) * _lambda + xTx) w = np.dot(np.dot(inv, x.T), y) self.weight = w def predict(self, x): pre = np.dot(x, self.weight) return pre def poly_features(self,x): #PolynomialFeatures # find the phi matrix # array_new = [[1 x1 x1^2 ...] # [1 x2 x1^2 ...] # . # . # [1 xn xn^2 ...]] if(self.M == 1): temp_matrix1 = np.ones([x.shape[0],1]) temp_matrix2 = x[:x.shape[0],:] phi_matrix = np.hstack((temp_matrix1,temp_matrix2)) return phi_matrix if(self.M == 2): temp_matrix1 = np.ones([x.shape[0],1]) temp_matrix2 = x[:x.shape[0],:] phi_matrix = np.hstack((temp_matrix1,temp_matrix2)) position = 1 + self.feature_num for i in range(x.shape[1]): for j in range(i,x.shape[1]): if i <= j: phi_matrix = np.insert(phi_matrix, position, (x[:,i]*x[:,j]), axis=1) position+=1 return phi_matrix def RMSE(y_predict,y_test): y_predict = np.squeeze(np.asarray(y_predict)) # numpy.matrix to numpy.ndarray y_test = np.squeeze(np.asarray(y_test)) return np.sqrt(np.mean((y_predict - y_test)**2)) # + [markdown] id="3Dp6lF51aric" # ####(a) In the feature selection stage, please apply polynomials of order M = 1 and M = 2 over the dimension D = 8 input data. Please evaluate the corresponding RMS error on the training set and valid set. (15%) Code Result # + colab={"base_uri": "https://localhost:8080/"} id="bcl2lJ0yfluJ" outputId="0e749224-3a37-4681-b8be-3f752464b484" print("M = ",1) model_1 = LinearRegression(x_train,1) x_new = model_1.poly_features(x_train) model_1.closed_form(x_new,y_train) #find weight # RMSE error y_predict = model_1.predict(x_new) train_rmse = RMSE(y_predict,y_train) print("training RMSE: {}".format(train_rmse)) x_new = model_1.poly_features(x_test) y_predict = model_1.predict(x_new) test_rmse = RMSE(y_predict,y_test) print("testing RMSE: {}".format(test_rmse)) print("M = ",2) model_2 = LinearRegression(x_train,2) x_new = model_2.poly_features(x_train) model_2.closed_form(x_new,y_train) #find weight # RMSE error y_predict = model_2.predict(x_new) train_rmse = RMSE(y_predict,y_train) print("training RMSE: {}".format(train_rmse)) x_new = model_2.poly_features(x_test) y_predict = model_2.predict(x_new) test_rmse = RMSE(y_predict,y_test) print("testing RMSE: {}\n".format(test_rmse)) # + [markdown] id="6500dPAsKq6t" # ####(b)How will you analysis the weights of polynomial model M = 1 and select the most contributive feature? Code Result, Explain (10%) # # + [markdown] id="Th-6Frbdz6Xn" # **The most contributive feature is median income** # + id="HoRO9Iv3eNAB" colab={"base_uri": "https://localhost:8080/"} outputId="59349af5-3405-48df-ece4-0245527fc591" for i in range(len(features)): x = x_train print("【Without ",features[i],"】") x = np.delete(x, i, 1) model = LinearRegression(x,1) x_new = model_1.poly_features(x) model.closed_form(x_new,y_train) #find weight # RMSE error y_predict = model.predict(x_new) train_rmse = RMSE(y_predict,y_train) print("training RMSE: {}".format(train_rmse)) x = x_test x = np.delete(x, i, 1) x_new = model.poly_features(x) y_predict = model.predict(x_new) test_rmse = RMSE(y_predict,y_test) print("testing RMSE: {}\n".format(test_rmse)) # + [markdown] id="kw1COLkpKKGp" # ##(2) Maximum likelihood approach # + [markdown] id="ey_7tiFo734O" # ####(b) Introduce the basis function you just decided in (a) to linear regression model and analyze the result you get. # + [markdown] id="uZx8fHaX1eOs" # 使用 **sigmoid basis function** 做轉換,再進行linear regression分析 # + id="cGIXyxag5xSH" colab={"base_uri": "https://localhost:8080/"} outputId="98fe702c-4a54-467f-bc32-c15e103d60fe" def sigmoid(x): return 1 / (1 + np.exp(-x)) X_sigmoid = X T_sigmoid = T # sigmoid X_sigmoid = sigmoid(X_sigmoid) # 80% training dataset and 20% test dataset X_SIZE = X.shape[0] ratio = 8/10 trainRange = int(X_SIZE*ratio) #num of training data x_train = X_sigmoid[:trainRange] x_test = X_sigmoid[trainRange:] y_train = T[:trainRange] y_test = T[trainRange:] print("【Using sigmoid function】") M=2 for i in range(1,M+1): print("M = ",i) model = LinearRegression(x_train,i) x_new = model.poly_features(x_train) model.closed_form(x_new,y_train) #find weight # RMSE error x_new = model.poly_features(x_train) y_predict = model.predict(x_new) train_rmse = RMSE(y_predict,y_train) print("training RMSE: {}".format(train_rmse)) x_new = model.poly_features(x_test) y_predict = model.predict(x_new) test_rmse = RMSE(y_predict,y_test) print("testing RMSE: {}".format(test_rmse)) # + [markdown] id="YWxtZrEVC8PV" # #### (c)**N-fold cross-validation** in your training stage to select at least one hyperparameter for model # # + id="-clqz3TnC7y0" colab={"base_uri": "https://localhost:8080/"} outputId="90e6b20e-68d8-474e-e0a6-a3eec1d3e727" X_sigmoid = X T_sigmoid = T # sigmoid X_sigmoid = sigmoid(X_sigmoid) X_SIZE = X_sigmoid.shape[0] N = 10 ratio = 1/N testRange = int(X_SIZE*ratio) M=2 print("【N-fold cross-validation】") for i in range(1,M+1): train_rmse = [] test_rmse = [] for r in range(N): # data split into 1 set(test) and N-1 sets(train) x_test = X_sigmoid[range((testRange*r),(testRange*(r+1))),:] y_test = T_sigmoid[range((testRange*r),(testRange*(r+1))),:] x_train = np.delete(X_sigmoid, [range((testRange*r),(testRange*(r+1)))], axis=0) y_train = np.delete(T_sigmoid, [range((testRange*r),(testRange*(r+1)))], axis=0) model = LinearRegression(x_train,i) x_new = model.poly_features(x_train) model.closed_form(x_new,y_train) #find weight # train RMSE error x_new = model.poly_features(x_train) y_predict = model.predict(x_new) train_rmse.append(RMSE(y_predict,y_train)) # test RMSE error x_new = model.poly_features(x_test) y_predict = model.predict(x_new) test_rmse.append(RMSE(y_predict,y_test)) average_train_rmse = sum(train_rmse) / N average_test_rmse = sum(test_rmse) / N print(f'M = {i}, Average_train_rmse = {average_train_rmse}, Average_test_rmse = {average_test_rmse}') # + [markdown] id="4MNGks0QGujx" # ## (3) Maximum a *posteriori* approach # + [markdown] id="mRlj-2ZDHCCH" # ####(b) Use maximum a posteriori approach method to retest the model in 2 you designed. You could choose Gaussian distribution as a prior. # + [markdown] id="fDmBnLb-OYTg" # 使用 Maximum a posteriori 做 linear regression , 設Lambda = 0.1 # + id="odbk38xJN6q5" colab={"base_uri": "https://localhost:8080/"} outputId="2ab94470-1e53-4ed5-e7a9-1c21acbad6d9" _lambda = 28 X_sigmoid = X T_sigmoid = T # sigmoid X_sigmoid = sigmoid(X_sigmoid) # 80% training dataset and 20% test dataset X_SIZE = X_sigmoid.shape[0] ratio = 8/10 trainRange = int(X_SIZE*ratio) #num of training data x_train = X_sigmoid[:trainRange] x_test = X_sigmoid[trainRange:] y_train = T_sigmoid[:trainRange] y_test = T_sigmoid[trainRange:] M=2 for i in range(1,M+1): print("M = ",i) model = LinearRegression(x_train,i) x_new = model.poly_features(x_train) model.closed_form(x_new,y_train,_lambda,True) #find weight # RMSE error x_new = model.poly_features(x_train) y_predict = model.predict(x_new) train_rmse = RMSE(y_predict,y_train) print("training RMSE: {}".format(train_rmse)) x_new = model.poly_features(x_test) y_predict = model.predict(x_new) test_rmse = RMSE(y_predict,y_test) print("testing RMSE: {}".format(test_rmse)) # + [markdown] id="ycN6sXeyOxOJ" # 使用 Maximum a posteriori 做 N-fold cross-validation # + id="uUWX-oInO4w9" colab={"base_uri": "https://localhost:8080/"} outputId="f5887e93-de8b-472e-d43c-85c5fcf1f55d" X_sigmoid = X T_sigmoid = T # sigmoid X_sigmoid = sigmoid(X_sigmoid) X_SIZE = X_sigmoid.shape[0] N = 10 ratio = 1/N testRange = int(X_SIZE*ratio) M=2 for i in range(1,M+1): train_rmse = [] test_rmse = [] for r in range(N): # data split into 1 set(test) and N-1 sets(train) x_test = X_sigmoid[range((testRange*r),(testRange*(r+1))),:] y_test = T_sigmoid[range((testRange*r),(testRange*(r+1))),:] x_train = np.delete(X_sigmoid, [range((testRange*r),(testRange*(r+1)))], axis=0) y_train = np.delete(T_sigmoid, [range((testRange*r),(testRange*(r+1)))], axis=0) model = LinearRegression(x_train,i) x_new = model.poly_features(x_train) model.closed_form(x_new,y_train,_lambda,True) #find weight # train RMSE error x_new = model.poly_features(x_train) y_predict = model.predict(x_new) train_rmse.append(RMSE(y_predict,y_train)) # test RMSE error x_new = model.poly_features(x_test) y_predict = model.predict(x_new) test_rmse.append(RMSE(y_predict,y_test)) average_train_rmse = sum(train_rmse) / N average_test_rmse = sum(test_rmse) / N print(f'『M = {i}』 Average_train_rmse = {average_train_rmse}, Average_test_rmse = {average_test_rmse}')
Hw1/hw1_310555029.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 # --- # # Calculating Merger Rate # # Calculating and plotting the properties of PBH binaries (PDF etc.). These are then used (along with the remapping procedure) to calculate the average merger rate of PBH binaries today. # + # %matplotlib inline import sys sys.executable print(sys.executable) print(sys.version) print(sys.version_info) from __future__ import division import numpy as np import matplotlib.pyplot as pl import matplotlib as mpl from scipy.integrate import odeint from scipy.special import erf from scipy.integrate import quad, dblquad from scipy.interpolate import interp1d,interp2d,RectBivariateSpline, griddata import emcee #----- MATPLOTLIB paramaters --------- mpl.rcParams.update({'font.size': 18,'font.family':'sans-serif'}) mpl.rcParams['xtick.major.size'] = 7 mpl.rcParams['xtick.major.width'] = 1 mpl.rcParams['xtick.minor.size'] = 3 mpl.rcParams['xtick.minor.width'] = 1 mpl.rcParams['ytick.major.size'] = 7 mpl.rcParams['ytick.major.width'] = 1 mpl.rcParams['ytick.minor.size'] = 3 mpl.rcParams['ytick.minor.width'] = 1 #-------------------------------------- # - # ## Define some constants + parameters # + G_N = 4.302e-3 #(pc/solar mass) (km/s)^2 G_N_Mpc = 1e-6*4.302e-3 #(Mpc/solar mass) (km/s)^2 h = 0.678 Omega_DM = 0.1186/(h**2) H0 = 100.0*h #(km/s) Mpc^-1 H0_peryr = 67.8*(3.24e-20)*(60*60*24*365) ageUniverse = 13.799e9 #y Omega_L = 0.692 Omega_m = 0.308 Omega_r = 9.3e-5 z_eq = 3375.0 rho_eq = 1512.0 #Solar masses per pc^3 sigma_eq = 0.005 #Variance of DM density perturbations at equality lambda_max = 3.0 #Maximum value of lambda = 3.0*z_dec/z_eq (i.e. binaries decouple all the way up to z_dec = z_eq) alpha = 0.1 rtr_interp = None Ubind_interp = None current_MPBH = -10.0 # - # ## Function definitions # # #### Several useful functions that provide truncation radius, mass of accreted DM halo, decoupling redshift # + #M_PBH in solar masses def r_trunc(z, M_PBH): r0 = 6.3e-3 #1300 AU in pc return r0*(M_PBH)**(1.0/3.0)*(1.+z_eq)/(1.+z) #Truncation radiation at equality def r_eq(M_PBH): return r_trunc(z_eq, M_PBH) def M_halo(z, M_PBH): return M_PBH*(r_trunc(z, M_PBH)/r_eq(M_PBH))**1.5 def xbar(f, M_PBH): return (3.0*M_PBH/(4*np.pi*rho_eq*(0.85*f)))**(1.0/3.0) def semimajoraxis(z_pair, f, M_PBH): Mtot = M_PBH X = 3.0*z_eq*0.85*f/z_pair return alpha*xbar(f, M_PBH)*(f*0.85)**(1.0/3.0)*((X/(0.85*f))**(4.0/3.0)) def semimajoraxis_full(z_pair, f, M_PBH): Mtot = M_PBH + M_halo(z_pair, M_PBH) X = 3.0*z_eq*0.85*f/z_pair return alpha*xbar(f, Mtot)*(f*0.85)**(1.0/3.0)*((X/(0.85*f))**(4.0/3.0)) def bigX(x, f, M_PBH): return (x/(xbar(f,M_PBH)))**3.0 def z_decoupling(a, f, mass): return (1. + z_eq)/(1./3 * bigX(x_of_a(a, f, mass), f, mass)/(0.85*f)) - 1. def x_of_a(a, f, M_PBH, withHalo = False): xb = xbar(f, M_PBH) if (not withHalo): return ((a * (0.85*f) * xb**3)/alpha)**(1.0/4.0) elif (withHalo): xb_rescaled = xb * ((M_PBH + M_halo(z_decoupling(a, f, M_PBH), M_PBH))/M_PBH )**(1./3.) return ((a * (0.85*f) * xb_rescaled**3)/alpha)**(1.0/4.0) def a_of_x(x, f, M_PBH): xb = xbar(f, M_PBH) return (alpha/(0.85*f))*x**4/xb**3 def a_max(f, M_PBH): return alpha*xbar(f, M_PBH)*(f*0.85)**(1.0/3.0)*((lambda_max)**(4.0/3.0)) def a_max_with_Halo(f, M_PBH): return alpha*xbar(f, 2.*M_PBH)*(f*0.85)**(1.0/3.0)*((lambda_max)**(4.0/3.0)) def GetRtrInterp(M_PBH): #CHECK dependence on f! global rtr_interp am = a_max_with_Halo(0.01, M_PBH) a_list = np.logspace(-9, np.log10(am*1.1), 101) z_decoupling_0 = z_decoupling(a_list, 0.01, M_PBH) M_halo_0 = M_halo(z_decoupling_0, M_PBH) z_decoupling_1 = np.zeros(len(a_list)) M_halo_1 = np.zeros(len(a_list)) for i in range(len(a_list)): z_decoupling_1[i] = z_decoupling(a_list[i], 0.01, (M_halo_0[i]+M_PBH)) M_halo_1 = M_halo(z_decoupling_1, (M_PBH)) z_decoupling_2 = np.zeros(len(a_list)) M_halo_2 = np.zeros(len(a_list)) for i in range(len(a_list)): z_decoupling_2[i] = z_decoupling(a_list[i], 0.01, (M_halo_1[i]+M_PBH)) M_halo_2 = M_halo(z_decoupling_2, (M_PBH)) z_decoupling_3 = np.zeros(len(a_list)) z_decoupling_check = np.zeros(len(a_list)) M_halo_3 = np.zeros(len(a_list)) for i in range(len(a_list)): z_decoupling_3[i] = z_decoupling(a_list[i], 0.01, (M_halo_2[i]+M_PBH)) M_halo_3 = M_halo(z_decoupling_3, (M_PBH)) r_list = r_trunc(z_decoupling_3, M_PBH) rtr_interp = interp1d(a_list, r_list) return rtr_interp def rho(r, r_tr, M_PBH, gamma=3.0/2.0): x = r/r_tr A = (3-gamma)*M_PBH/(4*np.pi*(r_tr**gamma)*(r_eq(M_PBH)**(3-gamma))) if (x <= 1): return A*x**(-gamma) else: return 0 def Menc(r, r_tr, M_PBH, gamma=3.0/2.0): x = r/r_tr if (x <= 1): return M_PBH*(1.+(r/r_eq(M_PBH))**(3-gamma)) else: return M_PBH*(1.+(r_tr/r_eq(M_PBH))**(3-gamma)) # - # #### Some useful cosmological functions # + def Hubble(z): return H0_peryr*np.sqrt(Omega_L + Omega_m*(1+z)**3 + Omega_r*(1+z)**4) def Hubble2(z): return H0*np.sqrt(Omega_L + Omega_m*(1+z)**3 + Omega_r*(1+z)**4) def HubbleLaw(age): return H0_peryr*age def rho_z(z): return 3.0*Hubble2(z)**2/(8*np.pi*G_N) def t_univ(z): integ = lambda x: 1.0/((1+x)*Hubble(x)) return quad(integ, z, np.inf)[0] def Omega_PBH(f): return f*Omega_DM rho_critical = 3.0*H0**2/(8.0*np.pi*G_N_Mpc) #Solar masses per Mpc^3 def n_PBH(f, M_PBH): return (1e3)**3*rho_critical*Omega_PBH(f)/M_PBH #PBH per Gpc^3 # - # #### Probability distributions # + def j_X(x, f, M_PBH): return bigX(x, f, M_PBH)*0.5*(1+sigma_eq**2/(0.85*f)**2)**0.5 def P_j(j, x, f, M_PBH): y = j/j_X(x, f, M_PBH) return (y**2/(1+y**2)**(3.0/2.0))/j def P_a_j(a, j, f, M_PBH): xval = x_of_a(a, f, M_PBH) X = bigX(xval, f, M_PBH) xb = xbar(f, M_PBH) measure = (3.0/4.0)*(a**-0.25)*(0.85*f/(alpha*xb))**0.75 return P_j(j, xval, f, M_PBH)*np.exp(-X)*measure def P_a_j_withHalo(a, j, f, M_PBH): xval = x_of_a(a, f, M_PBH, withHalo = True) X = bigX(xval, f, M_PBH) xb = xbar(f, M_PBH) measure = (3.0/4.0)*(a**-0.25)*(0.85*f/(alpha*xb))**0.75 measure *= ((M_PBH + M_halo(z_decoupling(a, f, M_PBH), M_PBH))/M_PBH )**(3./4.) return P_j(j, xval, f, M_PBH)*np.exp(-X)*measure def j_of(z,a, M_PBH): Q = (3.0/170.0)*(G_N*M_PBH)**-3 return ( (-(z/H0_peryr) + ageUniverse)/(Q*a**4.) )**(1./7.) def P_la_lj(la,lj, f, M_PBH): j = 10.**lj a = 10.**la return P_a_j(a, j, f, M_PBH)*a*j*(np.log(10)**2) #/Norm1 def P_la_lj_withHalo(la, lj, f, M_PBH): j = 10**lj a = 10**la return P_a_j_withHalo(a, j, f, M_PBH)*a*j*(np.log(10)**2) #/Norm2 def t_coal(a, e, M_PBH): Q = (3.0/170.0)*(G_N*M_PBH)**(-3) # s^6 pc^-3 km^-6 tc = Q*a**4*(1-e**2)**(7.0/2.0) #s^6 pc km^-6 tc *= 3.086e+13 #s^6 km^-5 tc *= (3e5)**5 #s return tc/(60*60*24*365) #in years def j_coal(a, t, M_PBH): Q = (3.0/170.0)*(G_N*M_PBH)**-3 # s^6 pc^-3 km^-6 tc = t*(60*60*24*365) tc /= (3e5)**5 tc /= 3.086e+13 return (tc/(Q*a**4))**(1.0/7.0) # - # ## PDF plot for M_PBH = 30Msun and f_PBH = 0.01 # + M_PBH_ref = 30. f_ref = 0.01 amin = 5.e-5 amax = a_max(f_ref, M_PBH_ref) P1 = lambda y,x,f,M_PBH: P_a_j(x, y, f, M_PBH) Norm1 = dblquad(P1, amin, amax, lambda x: 0, lambda x: 1, args=(f_ref, M_PBH_ref), epsrel=1e-20)[0] a_list = np.logspace(-5, np.log10(amax*1.5), 501) j_list = np.logspace(-5, -2, 501) a_grid, j_grid = np.meshgrid(a_list, j_list, indexing='xy') e_grid = np.sqrt(1-j_grid**2) P_a_j_vec = np.vectorize(P_a_j, excluded=(2,3)) pl.figure(figsize=(7,6)) cf = pl.contourf(a_grid,j_grid, np.log10(P_a_j_vec(a_grid, j_grid, f_ref, M_PBH_ref)/Norm1), cmap="Blues") pl.colorbar(cf,label=r"$\log_{10}\left(P(a, j)/\mathrm{pc}^{-1} \right)$") CS = pl.contour(a_grid, j_grid, t_coal(a_grid, e_grid, M_PBH_ref)/(1e9), levels=[0.1,13.0,1000.0],colors='DarkRed' ) pl.clabel(CS, levels=[13.0], # label every second level inline=1, fmt=' %1.f ', fontsize=16, manual=([0.018, 0.003],)) pl.clabel(CS, levels=[1000.], # label every second level inline=1, fmt=' %1.f ', fontsize=16, manual=([0.045, 0.006],)) pl.clabel(CS, levels=[0.1], # label every second level inline=1, #fmt='$t_\\mathrm{merge}$=%1.1f Gyr$\,$ ', fmt=' %1.1f Gyr$\,$ ', fontsize=16, manual=([0.005, 0.001],)) pl.xlabel("Semi-major axis, $a/\mathrm{pc}$") pl.ylabel("Angular momentum, $j = \sqrt{1-e^2}$") pl.title(r"$M_\mathrm{PBH} = " + str(int(M_PBH_ref)) + "\,M_\odot$, $f = " + str(f_ref) + "$",fontsize=18) pl.axvline(a_max(0.01, 30.), linestyle='--', color='k') pl.xlim(1.e-4, 0.1) pl.ylim(1.e-4, 0.01) pl.xscale("log") pl.yscale("log") pl.text(0.032, 0.0002,r"a$_{\rm max}$",color='black',fontsize=14.0) pl.savefig("PDF.pdf",bbox_inches="tight") pl.show() # - # ## Setting up the 'remapping' prescription # # Code for calculating $(a_i,j_i) \rightarrow (a_f, j_f)$. # + def calcBindingEnergy(r_tr, M_PBH): integ = lambda r: Menc(r, r_tr, M_PBH)*rho(r, r_tr, M_PBH)*r return -G_N*4*np.pi*quad(integ, 1e-8, 1.0*r_tr, epsrel=1e-3)[0] def getBindingEnergy(r_tr, f, M_PBH): global current_MPBH, Ubind_interp, rtr_interp if ((M_PBH - current_MPBH)**2 >1e-3 or Ubind_interp == None): print("I need to generate the r_tr(a) interpolation function for M = ", M_PBH) current_MPBH = M_PBH #print(" Tabulating binding energy and truncation radius (M_PBH = " + str(M_PBH) +")...") rtr_vals = np.logspace(np.log10(1e-8), np.log10(1.0*r_eq(M_PBH)), 500) Ubind_vals = np.asarray([calcBindingEnergy(r1, M_PBH) for r1 in rtr_vals]) Ubind_interp = interp1d(rtr_vals, Ubind_vals) rtr_interp = GetRtrInterp(M_PBH) print("a = 0.001; r_tr = ", rtr_interp(0.001)) print("a = 0.01; r_tr = ", rtr_interp(0.01)) return Ubind_interp(r_tr) def calc_af(ai, f, M_PBH): global current_MPBH, rtr_interp, Ubind_interp if ((M_PBH - current_MPBH)**2 > 1e-3 or (rtr_interp == None)): print("I have to generate the r_tr(a) interpolation function! ") current_MPBH = M_PBH rtr_vals = np.logspace(np.log10(1.e-8), np.log10(1.0*r_eq(M_PBH)), 500) Ubind_vals = np.asarray([calcBindingEnergy(r1, M_PBH) for r1 in rtr_vals]) Ubind_interp = interp1d(rtr_vals, Ubind_vals) rtr_interp = GetRtrInterp(M_PBH) print("0.001 -> ", rtr_interp(0.001)) print("0.01 -> ", rtr_interp(0.01)) #r_tr = CalcTruncRadius(ai, M_PBH) if (rtr_interp == None): print("warning! no interpolation function") r_tr = rtr_interp(ai) Mtot = Menc(r_tr, r_tr, M_PBH) #print Mtot U_orb_before = -G_N*(Mtot**2)/(2.0*ai) if (r_tr > r_eq(M_PBH)): Ubind = getBindingEnergy(r_eq(M_PBH), f, M_PBH) else: #print r_tr, r_eq(M_PBH) Ubind = getBindingEnergy(r_tr, f, M_PBH) return -G_N*M_PBH**2*0.5/(U_orb_before + 2.0*Ubind) def calc_jf(ji, ai, f, M_PBH): af = calc_af(ai, f, M_PBH) return ji*np.sqrt(ai/af) def calc_Tf(Ti, ai, f, M_PBH): af = calc_af(ai, f, M_PBH) return Ti*np.sqrt(af/ai) # - # ## Monte Carlo sampling procedure # + tmin_sampling = 1.e8 tmax_sampling = 1.e11 def lnprior(theta, M_PBH, a1, a2): la, lj = theta a = 10**la j = 10**lj if (j > 1): return -np.inf if (a < a1 or a > a2): return -np.inf t = t_coal(a, np.sqrt(1.-j**2), M_PBH=M_PBH) if (t < tmin_sampling or t > tmax_sampling): return -np.inf return 0 #Log-probability def lnprob(theta, f, M_PBH, PDF, a1, a2): lp = lnprior(theta, M_PBH, a1, a2) if not np.isfinite(lp): return -np.inf la, lj = theta #print la, lj, PDF(la, lj, f, M_PBH) return lp + np.log(PDF(la, lj, f, M_PBH)) #Sampler #PDF should be a function of the form P_la_lj(la, lj, f, M_PBH) #a1 and a2 are the desired ranges for a def GetSamples_MCMC(N_samps, PDF, a1, a2, f, M_PBH): print("This is GetSamples_MCMC from a1 = ", a1, " to a2 = ", a2) ndim, nwalkers = 2, 100 a0 = np.sqrt(a1*a2) j0 = j_coal(a0, 13e9, M_PBH) #print a0, j0 p0 = [[np.log10(a0), np.log10(j0)] + 0.01*np.random.rand(ndim) for i in range(nwalkers)] #print p0 sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=[f, M_PBH,PDF, a1, a2]) sampler.run_mcmc(p0, N_samps) samples = sampler.chain[:, 1000:, :].reshape((-1, ndim)) stride = 5 print(" Generated ", len(samples[::stride,:]), "samples...") return samples[::stride,:] # - # ## Compute the rate from sampled and remapped Ali-Haimoud distribution - Analytical # #### First define the integrals for P(t) # + def P_t_integ(a, t, f, M_PBH, withHalo): c = 3.e5 #km/s Q = (c**6)*(3.0/170.0)*(G_N*M_PBH)**-3 # pc^-3 t_pc = t*(60*60*24*365)*c*3.24078e-14 #Time in years -> Time in parsec ecc = np.sqrt(1-(t_pc*1.0/(Q*a**4))**(2.0/7.0)) j_ecc = np.sqrt(1. - ecc**2.) P1 = 1. if (withHalo == False): P1 = P_a_j(a, j_ecc, f, M_PBH) else: P1 = P_a_j_withHalo(a, j_ecc, f, M_PBH) djdt = j_ecc/(7*t) return P1*djdt #Time in years def P_t_of_z_analytical(z, f, M_PBH, withHalo): t = t_univ(z) avals = np.logspace(np.log10(amin), np.log10(amax), 101) #pc test = np.asarray([P_t_integ(a, t, f, M_PBH, withHalo) for a in avals]) integr = np.trapz(test, avals, withHalo) return integr def P_of_t_analytical(t, f, M_PBH, withHalo): avals = np.logspace(np.log10(amin), np.log10(amax), 101) #pc test = np.asarray([P_t_integ(a, t, f, M_PBH, withHalo) for a in avals]) integr = np.trapz(test, avals) return integr ########################################################################### t_vec = np.logspace(np.log10(tmin_sampling), np.log10(tmax_sampling), 1000) P_true = np.asarray([P_of_t_analytical(t_, f_ref, M_PBH_ref, withHalo=False) for t_ in t_vec]) P_true_withHalo = np.asarray([P_of_t_analytical(t_, f_ref, M_PBH_ref, withHalo=True) for t_ in t_vec]) int_analytical = np.trapz(P_true, t_vec) int_analytical_withHalo = np.trapz(P_true_withHalo, t_vec) # Example: 20 and 40 Msun #integrand_20 = lambda x: n_PBH(f_ref, 30.)*sens_20Msun(x)*P_t_of_z_analytical(x, f_ref, 30., withHalo=False) # Gpc^(-3) * Gpc^3 yr * yr^(-1) #integrand_40 = lambda x: n_PBH(f_ref, 30.)*sens_40Msun(x)*P_t_of_z_analytical(x, f_ref, 30., withHalo=False) #N_20 = quad(integrand_20, 0, 0.7)[0] #N_40 = quad(integrand_40, 0, 0.7)[0] #N_20_flat = quad(sens_20Msun, 0, 0.7)[0] #N_40_flat = quad(sens_40Msun, 0, 0.7)[0] #print("Analytical Merger Rate [Gpc^-3 yr^-1] for 20 and 40 Msun:", N_20/N_20_flat," - ",N_40/N_40_flat) # - # #### Calculate 'remapped' rate using MC sampling # # Note that this may take a while (where a while is probably a few hours). You may want to read in the files `data/rate_averaged_100.0.txt` (etc) instead. # + Nm = 3 Nf = 20 zmax = 1.0 Nsamples = 2**16 print(Nsamples) rtr_interp = None f_vec = np.logspace(-4.,-1., Nf) m_vec = np.array([10., 30., 100.]) rate_vec = np.zeros((Nm,Nf)) rate_remapped_vec = np.zeros((Nm,Nf)) for i_m in range(Nm): print(" ") print("*** M = ", m_vec[i_m]) if (rtr_interp == None): print("rtr_interp == none") print("current_MPBH = ", current_MPBH) print(" ") current_file = "rate_averaged_" + str(m_vec[i_m]) + ".txt" out_f = open(current_file, 'w') for i_f in range(Nf): print("*** f = ", f_vec[i_f]) if (rtr_interp == None): print("rtr_interp == none") print("current_MPBH = ", current_MPBH) print("Sampling PDF... ") #print("amax = ", a_max(f_vec[i_f], m_vec[i_m])) samples_MCMC = GetSamples_MCMC(Nsamples, P_la_lj_withHalo, amin, a_max_with_Halo(f_vec[i_f], m_vec[i_m]), f_vec[i_f], m_vec[i_m]) print("...done!") la_vals_all = samples_MCMC[:,0] print("max a from GetSamples = ", 10.**(np.amax(la_vals_all))) lj_vals_all = samples_MCMC[:,1] z_vals_all = np.zeros(Nsamples) t_vals_all = np.zeros(Nsamples) z_vals_remapped = np.zeros(Nsamples) t_vals_remapped = np.zeros(Nsamples) for ind in range(Nsamples): a_ = 10.**(la_vals_all[ind]) j_ = 10.**(lj_vals_all[ind]) e_ = np.sqrt(1. - (j_**2.)) current_t_coal = t_coal(a_, e_, m_vec[i_m]) t_vals_all[ind] = current_t_coal remapped_a = calc_af(a_, f_vec[i_f], m_vec[i_m]) remapped_j = calc_jf(j_, a_, f_vec[i_f], m_vec[i_m]) remapped_e = np.sqrt(1. - (remapped_j**2.)) remapped_t_coal = t_coal(remapped_a, remapped_e, m_vec[i_m]) t_vals_remapped[ind] = remapped_t_coal bins_t = np.logspace(np.log10(tmin_sampling), np.log10(tmax_sampling), 101) logBins_t = np.linspace(np.log10(tmin_sampling), np.log10(tmax_sampling), 101) bins_t_centres = np.sqrt(bins_t[:-1]*bins_t[1:]) nt_remapped, bins_t_remapped, patches = pl.hist(np.log10(t_vals_remapped), bins=logBins_t, normed=True, alpha=0.85) nt_remapped_normalized = nt_remapped/(bins_t_centres*np.log(10)) P_t_remapped_numerical = interp1d(bins_t_centres, nt_remapped_normalized, kind='linear') t_vec = np.logspace(np.log10(tmin_sampling), np.log10(tmax_sampling), 1000) P_true_withHalo = np.asarray([P_of_t_analytical(t_, f_vec[i_f], m_vec[i_m], withHalo=True) for t_ in t_vec]) int_analytical_withHalo = np.trapz(P_true_withHalo, t_vec) my_integrand = lambda x: P_t_remapped_numerical(t_univ(x)) my_integral = quad(my_integrand, 0.0, zmax)[0] / zmax rate_vec[i_m, i_f] = n_PBH(f_vec[i_f], m_vec[i_m]) * P_t_of_z_analytical(0., f_vec[i_f], m_vec[i_m], withHalo=False) rate_remapped_vec[i_m, i_f] = n_PBH(f_vec[i_f],m_vec[i_m]) * my_integral * int_analytical_withHalo #_withHalo print("fraction of binaries that merge today = ", P_t_remapped_numerical(t_univ(0.)), "; averaged = ", my_integral) current_str = str(f_vec[i_f]) + "\t" + str(rate_vec[i_m, i_f]) + "\t" + str(rate_remapped_vec[i_m, i_f])+"\n" print(current_str) out_f.write(current_str) out_f.close() # - # #### Calculate 'analytic' rate without DM mini-halos # + Nm = 3 Nf_analytical = 100 f_vec_analytical = np.logspace(-5.,0., Nf_analytical) m_vec = np.array([10., 30., 100.]) rate_vec_analytical = np.zeros((Nm,Nf_analytical)) print(f_vec_analytical) for i_m in range(Nm): print("*** M = ", m_vec[i_m]) for i_f in range(Nf_analytical): my_integrand_an = lambda x: P_t_of_z_analytical(x, f_vec_analytical[i_f], m_vec[i_m], withHalo=False) my_integral_an = quad(my_integrand_an, 0.0, zmax)[0] / zmax rate_vec_analytical[i_m, i_f] = n_PBH(f_vec_analytical[i_f], m_vec[i_m]) * my_integral_an # P_t_of_z_analytical(0., f_vec_analytical[i_f], m_vec[i_m], withHalo=False) # - # ## Plot Merger Rates # + from scipy.interpolate import UnivariateSpline print(rate_vec) print(rate_remapped_vec) mpl.rc('font', **{'size' : 18}) pl.figure(figsize=(7,6)) col = np.array(["red","green","blue"]) for iM in range(Nm): current_file = "rate_averaged_" if (iM==0): lab="10 M$_{\odot}$" current_file += (str(m_vec[iM]) + ".txt") if (iM==1): lab="30 M$_{\odot}$" current_file += (str(m_vec[iM]) + ".txt") if (iM==2): lab="100 M$_{\odot}$" current_file += (str(m_vec[iM]) + ".txt") print("Reading ",current_file) f_vec, rate_remapped_vec = np.loadtxt(current_file, usecols=(0, 2), unpack=True) pl.loglog(f_vec_analytical, rate_vec_analytical[iM,:], linewidth=1.5, ls="--", label=lab, color=col[iM]) pl.loglog(f_vec, rate_remapped_vec, linewidth=1.5, ls="-", color=col[iM]) pl.xlim(1.e-4,1.) pl.ylim(.1,1.e6) pl.fill_between(f_vec_analytical, 10., 200.0, color="lightGrey") pl.xlabel(r"$f_{\rm PBH}$") pl.ylabel(r"Merger rate [Gpc$^{-3}$ yr$^{-1}$]") pl.tight_layout() pl.legend(loc='lower right', frameon=False) pl.savefig("../plots/mergerRate_remapped.pdf", format='pdf') pl.show() # -
notebooks/MergerRate.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 # --- # Create a list that contains ZINC ids for the library F = open('../../../hivpr-docking/virtual_screen/library/dbfda-world.sdf','r') lines = F.read().split('\n') F.close() cids = [line for line in lines if line.startswith('ZINC')] # + import os, shutil import glob pdbqt_FNs = glob.glob('../docked/*.pdbqt') for FN in pdbqt_FNs: if os.path.basename(FN).startswith('receptor_dbfda'): cid = cids[int(os.path.basename(FN)[len('receptor_dbfda'):-6])-1] shutil.move(FN, os.path.join(os.path.dirname(FN),'receptor_'+cid+'.pdbqt')) # -
static_files/tutorials/3cl-pro/ADVina/analyze/renameDocked.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/EnsiyehRaoufi/ML_Models_Linear_treebased_XGBoost__AutoGluon/blob/main/XGBoost.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="VaywendvkkUv" import pandas as pd import xgboost as xgb import sklearn.datasets as datasets from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, accuracy_score # + id="HPMzmfJfl0ZI" #Load in the wine dataset from scikit learn. wine = datasets.load_wine() df = pd.DataFrame(wine['data'], columns=wine['feature_names'] ) df['target'] = wine['target'] # + colab={"base_uri": "https://localhost:8080/", "height": 270} id="xzk-nhHy1cm3" outputId="4b2f623d-eb2b-445a-db15-945faa25de4e" df.head() # + id="NTxneZ9CmeQ9" #For the wine dataset, create a train and test split, 80% train / 20% test. df_train, df_test = train_test_split(df, test_size=0.2, random_state=0 ) # + id="aQi3NKyHxIrU" #Load the train/test data into the xgboost matrix df_train_xgb = xgb.DMatrix(df_train.loc[:, df_train.columns!='target'], label=df_train['target']) df_test_xgb = xgb.DMatrix(df_test.loc[:, df_test.columns!='target'], label=df_test['target']) # + [markdown] id="-9YgXAeBx9Xv" # Create a XGBoost Classifier model with these hyperparameters: # * max_depth: 5 # * eta: 0.1 # * objective: multi:softmax # * num_class: 3 # * num_round: 100 # + id="y-Cbrlycxtpe" num_round = 100 params = {"max_depth":5, "eta":0.1, "objective": "multi:softmax", "num_class":3} bst = xgb.train(params, df_train_xgb, num_round) # + id="ebutM65izQWa" #Evaluate the model with the test dataset xgb_prediction = bst.predict(df_test_xgb) # + colab={"base_uri": "https://localhost:8080/"} id="ok2rnUmAz45C" outputId="c4d77015-832a-4994-ecaf-dd17317226de" #Accuracy score using sklearn function for classification metric accuracy_score(df_test["target"], xgb_prediction) # + colab={"base_uri": "https://localhost:8080/", "height": 314} id="OOXEjmD91Iah" outputId="fe6ff4cb-c819-4784-d355-8dba671beecf" # Plot the importance of the features based on fitted trees xgb.plot_importance(bst) # + [markdown] id="mV0bJofA1nOw" # # **XGBoost Regression** # + id="7rQm3Vy21Ygh" # Load in the diabetes dataset diabetes = datasets.load_diabetes() # + id="xKDEP5Ue1rFs" # Create the diabetes `data` dataset as a dataframe and name the columns with `feature_names` dfd = pd.DataFrame(diabetes["data"], columns=diabetes["feature_names"]) # Include the target as well dfd["target"] = diabetes["target"] # + id="8nJeOIwZ1syH" # Split your data with these ratios: train: 0.8 | test: 0.2 dfd_train, dfd_test = train_test_split(dfd, test_size=0.2, random_state=0) # + id="XIiIet1D1udy" # Load your train/test dataframe into DMatrix dtrain = xgb.DMatrix( dfd_train.loc[:, dfd_train.columns != "target"], label=dfd_train["target"] ) dtest = xgb.DMatrix( dfd_test.loc[:, dfd_test.columns != "target"], label=dfd_test["target"] ) # + id="yfXNyPo51xHq" # How does the model perform on the training dataset and default model parameters? # Using the hyperparameters in the requirements, is there improvement? # Remember we use the test dataset to score the model param = { "max_depth": 2, "eta": 0.03, "gamma": 0.09, "colsample_bytree": 0.5, "objective": "reg:squarederror", } num_round = 100 bst = xgb.train(param, dtrain, num_round) # + id="6v3n6Ixg16xA" # xgboost is not scikit learn, so you'll need to do predictions using their API preds = bst.predict(dtest) # + colab={"base_uri": "https://localhost:8080/"} id="e7Hy1fIn19mV" outputId="e4826562-a91b-4578-a415-6029d15f465c" # R2 score using scikit learn function for regression metric r2_score(dfd_test["target"], preds) # + colab={"base_uri": "https://localhost:8080/", "height": 314} id="bWMB7f6f2BSb" outputId="fcd46e27-c6c5-49fb-e914-b3c75eb56238" # Plot the importance of the features based on fitted trees xgb.plot_importance(bst) # + id="EK9UxOBE2HI5"
XGBoost.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] hideCode=false hidePrompt=false # # Beam profiles and corresponding spectrum amplitudes # + [markdown] hideCode=false hidePrompt=false # This notebook summarises formulas on which the corresponding Scheme configuration (`.ctl`) files are based. Furthermore it gives additional information, derivations and references. # + code_folding=[0] hideCode=false hidePrompt=false ## import of required modules # %matplotlib inline import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.pyplot as plt from scipy.misc import derivative from scipy import integrate print("NumPy:", np.__version__) print("SciPy:", sp.__version__) print("Matplotlib:", mpl.__version__) # + [markdown] hideCode=false hidePrompt=false # ## 1 Gauss beam # - # ### 1.1 Beam profile # The profile of a Gaussian beam at waist is given by # # \begin{equation*} # \psi_\text{G} (x, z=0) = \exp\biggl[-\Bigl(\frac{x}{w_0} \Bigr)^2\biggr]. # \end{equation*} # ### 1.2 Spectrum amplitude # The corresponding spectrum amplitude is # # \begin{equation*} # f_\text{G} (k_x) = \frac{w_0}{2 \sqrt{\pi}} \exp\biggl[-\Bigl(\frac{k_x w_0}{2} \Bigr)^2 \biggr]. # \end{equation*} # + [markdown] hideCode=false hidePrompt=false # ## 2 Laguerre-Gauss (vortex) beam # - # ### 2.1 Beam propagation in spherical coordinates # \begin{equation*} # \psi_\text{LG}(x,y,z) = k^2 \int_0^{\pi/2}\mathrm{d}\theta\int_0^{2\pi}\mathrm{d}\phi\, \sin{\theta}\cos{\theta}\,f_\text{LG}(\theta, \phi) \exp\bigl[\mathrm{i}k \bigl(x \cos{\theta} + y\sin{\theta}\sin{\phi} - z \sin{\theta}\cos{\phi}\bigr)\bigr]. # \end{equation*} # ### 2.2 Spectrum amplitude # The spectrum amplitude for Laguerre-Gaussian beams taken from eq. (2.22) in [[Bliokh2013](#Bliokh2013)] is given by # # \begin{equation*} # f_\text{LG}(\theta,\phi) = \theta^{|m|} \exp\biggl[-\Bigl(\frac{kw_0}{2}\sin\theta\Bigr)^2 \biggr] \exp(\mathrm{i} m \phi) # \end{equation*} # # with azimuthal angle $\phi$, polar angle $\theta$ and vortex charge $m$. # + [markdown] hideCode=false hidePrompt=false # ## 3 Incomplete Airy beam # - # With regards to [[Ring2013](#Ring2013)] we substitute $X\equiv x/w_0$, $Z \equiv z/(2kw_0^2)$, $K_x\equiv k_xw_0$, $K\equiv kw_0$ and as characteristic inverse length, $\kappa \equiv 1/w_0$. # + [markdown] hideCode=false hidePrompt=false # ### 3.1 Beam profile # + [markdown] hideCode=false hidePrompt=false # The beam profile at waist is defined by the incomplete Airy function, see [[Ring2013](#Ring2013)] # # \begin{equation*} # \psi^\text{Airy}_{M,W}(x, z=0) = \int_{M-W}^{M+W}\mathrm{d}\xi\, \mathrm{exp}\left[\mathrm{i}\left(\frac{1}{3} \xi^3 + \xi \frac{x}{w_0}\right)\right]. # \end{equation*} # + code_folding=[0] def Ai_inc(X, M, W): """Incomplete Airy function.""" π = np.pi integrand = lambda ξ: sp.exp(1j * ((ξ**3)/3 + ξ*X)) / (2*π) re, re_err = integrate.quad(lambda ξ: np.real(integrand(ξ)), M - W, M + W) im, im_err = integrate.quad(lambda ξ: np.imag(integrand(ξ)), M - W, M + W) return re + im*1j vec_Ai_inc = np.vectorize(Ai_inc) # - X = np.linspace(-20, 3, 400) plt.plot(X, np.abs(vec_Ai_inc(X, 0, 4))**2); # + [markdown] hideCode=false hidePrompt=false # ### 3.2 Spectrum amplitude # + [markdown] hideCode=false hidePrompt=false # \begin{align*} # f^\text{Airy}_{M,W}(k_x) &= \frac{1}{2 \pi} \int_{-\infty}^\infty\mathrm{d}x\, \psi^\text{Airy}_{M,W}(x, z=0) \exp(-\mathrm{i}k_x x)\\ # &= \int_{M-W}^{M+W}\mathrm{d}\xi\, \exp\Bigl(\mathrm{i}\frac{1}{3}\xi^3 \Bigr) \delta\Bigl(\frac{\xi}{w_0} -k_x\Bigr)\\ # &=\begin{cases} # w_0 \exp\Bigl[\mathrm{i} \frac{1}{3} \bigl(w_0k_x \bigr)^3\Bigr] & M-W < w_0k_x <M+W \\ # 0 & \text{otherwise} # \end{cases} # \end{align*} # + code_folding=[] def f_Airy_inc(K_x, M, W): """Spectrum amplitude of the incomplete Airy beam.""" return np.exp(1j*(K_x**3)/3) * np.heaviside(K_x - (M - W), 0) * np.heaviside(M + W - K_x, 0) # - w_0 = 0.4138028520389279 k_x = 0.2 np.exp(1j*((w_0*k_x)**3)/3) # + [markdown] hideCode=false hidePrompt=false # ### 3.3 Paraxially propagating incomplete Airy beam # # \begin{align*} # \psi^\text{Airy}_{M,W}(x, z) &= \frac{1}{2\pi}\int_{-\infty}^\infty \mathrm{d}k_x\, f^\text{Airy}_{M,W}(k_x) \exp\Bigl(\mathrm{i} z \sqrt{k^2 - k_x^2}\Bigr)\exp(\mathrm{i}k_x x) \\ # \text{expanding square root} & \text{ up to second order}\\ # &\simeq \frac{w_0}{2\pi}\int_{(M-W)/w_0}^{(M+W)/w_0} \mathrm{d}k_x\, \exp\Bigl(\mathrm{i}\frac{1}{3}(k_xw_0)^3\Bigr) \exp\Bigl[\mathrm{i}z \Bigl(k - \frac{k_x^2}{2k}\Bigr)\Bigr]\exp(\mathrm{i}k_x x)\\ # \text{apply transformations }& z \to 2kw_0^2 Z \text{ and } k_x \to k_x^\prime + Z/w_0\\ # &= \frac{w_0}{2\pi}\exp\Bigl[\mathrm{i}\Bigl(zk + \frac{x}{w_0}Z(z)-\frac{2}{3}Z^3(z)\Bigr)\Bigr] \psi^\text{Airy}_{M-Z(z)/w_0,W}(x-w_0Z^2(z), z=0) # \end{align*} # + def phase(K_x, K, X, Z): return -(K_x**3)/3 - 2*K*Z*sp.sqrt(K**2 - K_x**2) - K_x*X def stat_points(X, Z): return [Z - sp.sqrt(-X + Z**2), Z + sp.sqrt(-X + Z**2)] # + K_x = np.linspace(-5, 15, 10000) X, Z = 10, 4 # x < Z**2 print(stat_points(X, Z)) plt.plot(K_x, np.exp(-1j*phase(K_x, 100, X, Z)).real) # K must be large plt.axhline(0, color='k', ls='--') plt.axvline(0, color='k', ls='--') plt.axvline(stat_points(X, Z)[0], color='red', ls='-') plt.axvline(stat_points(X, Z)[1], color='red', ls='-'); # + code_folding=[] def AiB_inc_exa(X, Z, M, W, K): """Exact incomplete Airy beam.""" π = np.pi integrand = lambda K_x: sp.exp(1j*((K_x**3)/3 + 2*K*Z*np.sqrt(K**2 - K_x**2) + K_x*X)) / (2*π) re, re_err = integrate.quad(lambda K_x: np.real(integrand(K_x)), M - W, M + W) im, im_err = integrate.quad(lambda K_x: np.imag(integrand(K_x)), M - W, M + W) return re + im*1j vec_AiB_inc_exa = np.vectorize(AiB_inc_exa) # + code_folding=[0] def AiB_inc_par(X, Z, M, W, K): """Paraxial incomplete Airy beam.""" return np.exp(1j*(2*(K**2)*Z + X*Z - 2*(Z**3)/3)) * Ai_inc(X - Z**2, M-Z, W) vec_AiB_inc_par = np.vectorize(AiB_inc_par) # - X_, Z_, K_ = 4, 10.5, 100 print("exact: ", AiB_inc_exa(X_, Z_, 0, 4, K_), np.abs(AiB_inc_exa(X_, Z_, 0, 4, K_))**2) print("paraxial:", AiB_inc_par(X_, Z_, 0, 4, K_), np.abs(AiB_inc_par(X_, Z_, 0, 4, K_))**2) # + code_folding=[] X = np.linspace(-30, 30, 200) Z = np.linspace( -2, 5, 100) Xm, Zm = np.meshgrid(X, Z) # - airy_beam_field_par = vec_AiB_inc_par(Xm, Zm, 0, 4, 10) airy_beam_field_exa = vec_AiB_inc_exa(Xm, Zm, 0, 4, 10) # + code_folding=[0] # visualisation scale_factor = 1 # 2*kw_0 extent = np.min(X), np.max(X), scale_factor*np.min(Z), scale_factor*np.max(Z) diff_real = np.real(airy_beam_field_par)**2 - np.real(airy_beam_field_exa)**2 diff_abs = np.abs( airy_beam_field_par)**2 - np.abs( airy_beam_field_exa)**2 class MidpointNormalize(mpl.colors.Normalize): """ class to help renormalize the color scale """ def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint mpl.colors.Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) fig, axes = plt.subplots(figsize=(14.2,6),nrows=2, ncols=3) args = {'origin': 'lower', 'extent': extent, 'aspect': 'auto', 'interpolation': 'bicubic'} norm = MidpointNormalize(midpoint=0) a = axes[0,0]; b = axes[0,1]; c = axes[0,2] # first row d = axes[1,0]; e = axes[1,1]; f = axes[1,2] # second row a.imshow(np.abs(airy_beam_field_par)**2, cmap=plt.cm.hot, **args); a.set_title("paraxial"); b.imshow(np.abs(airy_beam_field_exa)**2, cmap=plt.cm.hot, **args); b.set_title("exact"); c.imshow(diff_abs, cmap=plt.cm.seismic, norm=norm, **args); c.set_title("difference"); d.imshow(np.real(airy_beam_field_par)**2, cmap=plt.cm.hot, **args); e.imshow(np.real(airy_beam_field_exa)**2, cmap=plt.cm.hot, **args); f.imshow(diff_real, cmap=plt.cm.seismic, norm=norm, **args); a.text(0.1, 0.8, r"$|\mathrm{AiB}^\mathrm{inc}_{M,W}(X,Z)|^2$", color="w", transform=a.transAxes) b.text(0.1, 0.8, r"$|\mathrm{AiB}^\mathrm{inc}_{M,W}(X,Z)|^2$", color="w", transform=b.transAxes) d.text(0.1, 0.8, r"$\Re(\mathrm{AiB}^\mathrm{inc}_{M,W}(X,Z))^2$", color="w", transform=d.transAxes) e.text(0.1, 0.8, r"$\Re(\mathrm{AiB}^\mathrm{inc}_{M,W}(X,Z))^2$", color="w", transform=e.transAxes) axes[0,0].set_ylabel('Z'); axes[1,0].set_ylabel('Z') for ax in axes[1]: ax.set_xlabel('X') # + [markdown] hideCode=false hidePrompt=false # # References # [<a id="Bliokh2013"></a>Bliokh2013] <NAME> and <NAME>, [Goos-Hänchen and Imbert-Fedorov beam shifts: an overview](https://doi.org/10.1088/2040-8978/15/1/014001), Journal of Optics, vol. 15, number 1, pp. 014001, 2013. # # [<a id="Ring2013"></a>Ring2013] <NAME>, <NAME> and <NAME>, [Incomplete Airy beams: finite energy from a sharp spectral cutoff](https://doi.org/10.1364/OL.38.001639), Optics Letters, vol. 38, number 10, pp. 1639–1641, May 2013.
beam_profiles.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: # 1. Perform a fit on data using a linear model and a quadratic model. # 2. Measure the Euclidean distance (mean squared error) of each model on the dataset. # 3. Try to guess a function that explains the data better. Measure its performance. # # # # Stretch Goals: # - Try a different loss function (such as a different $L_p$ norm). Answer: Does the order of models change in terms of performance? # - Try other regression methods from scikit-learn. Measure their performance. Which is the best? # - Answer: What would you expect the $L_0$ and $L_\infty$ norms to do? # + import numpy as np with open('../Part 1/test_data.csv') as f: data = np.loadtxt(f, delimiter=',') # Sort data by X axis we will use... better way? data = data[np.argsort(data, axis=0)[:,0]] input_data = data[:,0] # first column output_data = data[:,2] # third column # + from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline train_input = input_data.reshape(-1, 1) train_output = output_data.reshape(-1, 1) line_model = make_pipeline(LinearRegression()) line_model.fit(train_input, train_output) line_preds = line_model.predict(train_input) quad_model = make_pipeline(PolynomialFeatures(2), LinearRegression()) quad_model.fit(train_input, train_output) quad_preds = quad_model.predict(train_input) # + # %matplotlib inline from matplotlib import pyplot as plt plt.scatter(input_data, output_data) plt.plot(train_input, line_preds) plt.plot(train_input, quad_preds) plt.show() # - L = lambda preds, p: np.sum((preds - train_output)**p)**(1/p) L(line_preds, 2), L(quad_preds, 2)
Section 1/Part 2/1-2 Assignment.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: opencadd # language: python # name: opencadd # --- # # KLIFS API # # Check out result values when using KLIFS API: # # https://klifs.vu-compmedchem.nl/swagger/ # + from bravado.client import SwaggerClient from bravado_core.exception import SwaggerMappingError KLIFS_API_DEFINITIONS = "http://klifs.vu-compmedchem.nl/swagger/swagger.json" KLIFS_CLIENT = SwaggerClient.from_url( KLIFS_API_DEFINITIONS, config={"validate_responses": False} ) # - def print_result(result): """Use when result is a list.""" if isinstance(result, list): print("Result type:", type(result)) print("Number of list items:", len(result)) print("List item type:", type(result[0])) print("First list item:", result[0]) if isinstance(result, str): print("Result type:", type(result)) # ## Information result = KLIFS_CLIENT.Information.get_kinase_groups().response().result print_result(result) result = KLIFS_CLIENT.Information.get_kinase_families().response().result print_result(result) type(int) result = KLIFS_CLIENT.Information.get_kinase_names().response().result print_result(result) result = KLIFS_CLIENT.Information.get_kinase_information(kinase_ID=[33]).response().result print_result(result) result = KLIFS_CLIENT.Information.get_kinase_ID(kinase_name="EGFR").response().result print_result(result) # ## Interactions result = KLIFS_CLIENT.Interactions.get_interactions_get_types().response().result print_result(result) result = KLIFS_CLIENT.Interactions.get_interactions_get_IFP(structure_ID=[33]).response().result print_result(result) result = KLIFS_CLIENT.Interactions.get_interactions_match_residues(structure_ID=33).response().result print_result(result) # ## Ligands result = KLIFS_CLIENT.Ligands.get_ligands_list(kinase_ID=[22]).response().result print_result(result) result = KLIFS_CLIENT.Ligands.get_ligands_list_structures(ligand_ID=[22]).response().result print_result(result) result = KLIFS_CLIENT.Ligands.get_bioactivity_list_id(ligand_ID=50).response().result print_result(result) try: result = KLIFS_CLIENT.Ligands.get_bioactivity_list_pdb(ligand_PDB="STU").response().result except (SwaggerMappingError, ValueError) as e: print(e) # ## Structures result = KLIFS_CLIENT.Structures.get_structure_list(structure_ID=[33]).response().result print_result(result) result = KLIFS_CLIENT.Structures.get_structures_list(kinase_ID=[33]).response().result print_result(result) result = KLIFS_CLIENT.Structures.get_structures_pdb_list(pdb_codes=["3w32"]).response().result print_result(result) result = KLIFS_CLIENT.Structures.get_structure_get_complex(structure_ID=33).response().result print_result(result) result = KLIFS_CLIENT.Structures.get_structure_get_pdb_complex(structure_ID=33).response().result print_result(result) result = KLIFS_CLIENT.Structures.get_structure_get_ligand(structure_ID=33).response().result print_result(result) result = KLIFS_CLIENT.Structures.get_structure_get_pocket(structure_ID=33).response().result print_result(result) result = KLIFS_CLIENT.Structures.get_structure_get_protein(structure_ID=33).response().result print_result(result)
docs/examples/klifs_swagger_api_example_usage.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 # --- # # Manejo de Errores y Excepciones # En algunas ocasiones nuestros programas pueden fallar ocasionando su detención. Ya sea por errores de sintaxis o de lógica, tenemos que que ser capaces de detectar esos momentos y tratarlos debidamente para prevenirlos. # <img src='https://www.programarya.com/img/Cursos/Fundamentacion/Errores/Errores-header.png'> # ## Errores # ------------------------------ # Los errores detienen la ejecución del programa y tienen varias causas. Para poder estudiarlos mejor vamos a provocar algunos intencionadamente. # ### Errores de Sintaxis # Identificados con el código **SyntaxError**, son los que podemos apreciar repasando el código, por ejemplo al dejarnos de cerrar un paréntesis: print("Hola" # ### Errores de Nombre # Se producen cuando el sistema interpreta que debe ejecutar alguna función, método... pero no lo encuentra definido. Devuelven el código **NameError**: prit('Hola') # La mayoría de errores sintácticos y de nombre los identifican los editores de código antes de la ejecución, pero existen otros tipos que pasan más desapercibidos. # ### Errores semánticos # Estos errores son muy difíciles de identificar porque van ligados al sentido del funcionamiento y dependen de la situación. Algunas veces pueden ocurrir y otras no. # # La mejor forma de prevenirlos es programando mucho y aprendiendo de tus propios fallos, la experiencia es la clave. Veamos un par de ejemplos: # **Ejemplo lectura de cadena y operación sin conversión a número** # # Cuando leemos un valor con la función input(), éste siempre se obtendrá como una cadena de caracteres. Si intentamos operarlo directamente con otros números tendremos un fallo **TypeError** que tampoco detectan los editores de código: # + n = input("Introduce un número: ") print("{}/{} = {}".format(n,m,n/m)) # - # **Ejemplo pop() con lista vacía** # # Si intentamos sacar un elemento de una lista vacía, algo que no tiene mucho sentido, el programa dará fallo de tipo **IndexError**. Esta situación ocurre sólo durante la ejecución del programa, por lo que los editores no lo detectarán: l = [] l.pop() # ## Excepciones # ------------------------------ # Las excepciones son bloques de código que nos permiten continuar con la ejecución de un programa pese a que ocurra un error. # # Siguiendo con el ejemplo de la lección anterior, teníamos el caso en que leíamos un número por teclado, pero el usuario no introducía un número: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) # ### Bloques try - except # Para prevenir el fallo debemos poner el código propenso a errores en un bloque **try** y luego encadenar un bloque **except** para tratar la situación excepcional mostrando que ha ocurrido un fallo: try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") # Como vemos esta forma nos permite controlar situaciones excepcionales que generalmente darían error y en su lugar mostrar un mensaje o ejecutar una pieza de código alternativo. # # Podemos aprovechar las excepciones para forzar al usuario a introducir un número haciendo uso de un bucle while, repitiendo la lectura por teclado hasta que lo haga bien y entonces romper el bucle con un break: while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) break # Importante romper la iteración si todo ha salido bien except: print("Ha ocurrido un error, introduce bien el número") # ### Bloque else # Es posible encadenar un bloque else después del except para comprobar el caso en que **todo funcione correctamente** (no se ejecuta la excepción). # # El bloque else es un buen momento para romper la iteración con break si todo funciona correctamente: while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") else: print("Todo ha funcionado correctamente") break # Importante romper la iteración si todo ha salido bien # ### Bloque finally # Por último es posible utilizar un bloque finally que se ejecute al final del código, **ocurra o no ocurra un error**: while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") else: print("Todo ha funcionado correctamente") break # Importante romper la iteración si todo ha salido bien finally: print("Fin de la iteración") # Siempre se ejecuta
Modulo3/1. Manejo de Errores.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.10 64-bit (''PythonData'': conda)' # language: python # name: python361064bitpythondataconda7465b2e4d16447d5bf5dcc356c678f6e # --- # %matplotlib inline from matplotlib import style style.use('fivethirtyeight') import matplotlib.pyplot as plt import numpy as np import pandas as pd from sqlalchemy import create_engine engine = create_engine('postgresql://localhost:5432/<your_db_name>') connection = engine.connect()
Notebooks/SQL/Employeesdb.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 # --- # # Simple Boston Demo # # The ability to use hierarchical feature clusterings to control PartitionExplainer is still in an Alpha state, but this notebook demonstrates how to use it right now. Note that I am releasing this to get feedback and show how I am working to address concerns about the speed of our model agnostic approaches and the impact of feature correlations. This is all as-yet unpublished work, so treat it accordingly. # # When given a balanced partition tree PartitionExplainer has $O(M^2)$ runtime, where $M$ is the number of input features. This is much better than the $O(2^M)$ runtime of KernelExplainer. import numpy as np import scipy as sp import scipy.cluster import matplotlib.pyplot as pl import xgboost import shap import pandas as pd # ## Train the model # + X,y = shap.datasets.boston() #X = X.iloc[:,:4] model = xgboost.XGBRegressor(n_estimators=100, subsample=0.3) model.fit(X, y) x = X.values[0:1,:] refs = X.values[1:100] # use 100 samples for our background references (using the whole dataset would be slower) # - # ## Compute a hierarchal clustering of the input features D = sp.spatial.distance.pdist(X.fillna(X.mean()).T, metric="correlation") cluster_matrix = sp.cluster.hierarchy.complete(D) cluster_matrix = shap.partition_tree(X) # plot the clustering pl.figure(figsize=(15, 6)) pl.title('Hierarchical Clustering Dendrogram') pl.xlabel('sample index') pl.ylabel('distance') sp.cluster.hierarchy.dendrogram( cluster_matrix, leaf_rotation=90., # rotates the x axis labels leaf_font_size=10., # font size for the x axis labels labels=X.columns ) pl.show() shap.common.shapley_coefficients(12) # ## Explain the first sample with Partition Explainer # + # define the model as a python function f = lambda x: model.predict(x, output_margin=True, validate_features=False) # explain the model # pexplainer = shap.PartitionExplainer(f, refs, cluster_matrix) # shap_values = pexplainer(x, npartitions=500) m = shap.maskers.Tabular(refs, hclustering="correlation") pexplainer = shap.explainers.BruteForce(f, refs) p2explainer = shap.explainers.Partition(f, m) # - import sys shap_values = pexplainer(x, max_evals=5000) shap_values2 = p2explainer(x, max_evals=50000) # ## Compare with TreeExplainer texplainer = shap.TreeExplainer(model, refs) tshap_values = texplainer(x) pl.plot(shap_values.values[0]) pl.plot(shap_values2.values[0]) #pl.plot(tshap_values.values[0]) nexplainer = shap.PermutationExplainer(f, refs) shap_values3 = nexplainer(x, npermutations=10) batch_size = 10 data = X batch = np.zeros((batch_size,) + data.shape[1:]) batch_index = 0 for i in range(npermutations): n_sizes = 4 svals = np.zeros((n_sizes, X.shape[1])) pvals = np.zeros((n_sizes, X.shape[1])) nvals = np.zeros((n_sizes, X.shape[1])) sizes = np.linspace(100, 500000, n_sizes) for i,s in enumerate(sizes): s = int(s) s -= s % 2 pvals[i] = pexplainer(x, nsamples=s).values[0] svals[i] = sexplainer(x, nsamples=s).values[0] nvals[i] = nexplainer(x, npermutations=s).values[0] for i in range(svals.shape[1]): pl.plot(sizes, svals[:,i].T) pl.plot(sizes, pvals[:,i].T) pl.show() pl.plot(sizes, svals[:,0].T) pl.plot(sizes, pvals[:,0].T) pl.plot(shap_values2.values[0], label="TreeExplainer") pl.plot(shap_values.values[0], label="PartitionExplainer") pl.legend()
notebooks/tabular_examples/model_agnostic/Simple Boston Demo.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 # --- # # Math Module and its builtin functions import math a =int(input('enter yout number to be squared ')) print(math.sqrt(a)) math.sqrt(26) # print(math.pow(a,2)) # print(math.factorial(a)) # print(math.remainder(a,2)) print(math.pi) x=5 y=6 # #less than # print(x<y) # #greater than # print(x>y) #equal to # print(x==y) #not equal to print(x!=y) #Greater than or equal to print(x>=y) # + if x == 5: print('yes') else: print("No") # - # #Binary Operations #anyone y or x y and x # #Loops fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) # #Conditional Flow of Control if x != 5: print('not found') else: print('it is equal to zero') b = int(input('Enter the number to find if its true')) if b == 5: print("it is") elif b != 5: print('not') else: print('nothing found') s = [8,5,6,8] for s in s: print(s) i = 0 while (i<3): print(s) i+=1
fourth class 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 # language: python # name: python3 # --- # # Project: Identify Customer Segments # # In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task. # # This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. **Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks.** The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it. # # It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. **There will be times in the project where you will need to make and justify your own decisions on how to treat the data.** These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made. # # At the end of most sections, there will be a Markdown cell labeled **Discussion**. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. **Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.** # + # import libraries here; add more as necessary import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import Imputer from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.cluster import KMeans # magic word for producing visualizations in notebook # %matplotlib inline ''' Import note: The classroom currently uses sklearn version 0.19. If you need to use an imputer, it is available in sklearn.preprocessing.Imputer, instead of sklearn.impute as in newer versions of sklearn. ''' # - # ### Step 0: Load the Data # # There are four files associated with this project (not including this one): # # - `Udacity_AZDIAS_Subset.csv`: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns). # - `Udacity_CUSTOMERS_Subset.csv`: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns). # - `Data_Dictionary.md`: Detailed information file about the features in the provided datasets. # - `AZDIAS_Feature_Summary.csv`: Summary of feature attributes for demographics data; 85 features (rows) x 4 columns # # Each row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign. # # To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the `.csv` data files in this project: they're semicolon (`;`) delimited, so you'll need an additional argument in your [`read_csv()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely. # # Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings. # + # Load in the general demographics data. azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv',delimiter=';') # Load in the feature summary file. feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv',delimiter=';') # + # Check the structure of the data after it's loaded (e.g. print the number of # rows and columns, print the first few rows). print(f'azdias Shape{azdias.shape}') print(f'feat_info Shape{feat_info.shape}') # - #understand Azdias data frame azdias.head() feat_info.head() # > **Tip**: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut `esc --> a` (press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, and `esc --> b` adds a new cell after the active cell. If you need to convert an active cell to a markdown cell, use `esc --> m` and to convert to a code cell, use `esc --> y`. # # ## Step 1: Preprocessing # # ### Step 1.1: Assess Missing Data # # The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the **Discussion** cell with your findings and decisions at the end of each step that has one! # # #### Step 1.1.1: Convert Missing Value Codes to NaNs # The fourth column of the feature attributes summary (loaded in above as `feat_info`) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. `[-1,0]`), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest. # # **As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.** # + # Identify missing or unknown data values and convert them to NaNs. for attr in feat_info['attribute']: tmplist = feat_info[feat_info['attribute']==attr].missing_or_unknown.iloc[0].replace('[','').replace(']','').split(',') missing_or_unknown_list = [float(x) if x.lstrip('-').isnumeric() else x for x in tmplist] azdias[attr].replace(to_replace=missing_or_unknown_list, value=np.nan, inplace=True) # - azdias.head() azdias.tail() # #### Step 1.1.2: Assess Missing Data in Each Column # # How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's [`hist()`](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html) function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!) # # For the remaining features, are there any patterns in which columns have, or share, missing data? # Perform an assessment of how much missing data there is in each column of the # dataset. azdias.isnull().sum().sort_values(ascending=False) # Investigate patterns in the amount of missing data in each column. azdias.isnull().sum().hist() # Remove the outlier columns from the dataset. (You'll perform other data # engineering tasks such as re-encoding and imputation later.) drop_columns = list(azdias.isnull().sum()[azdias.isnull().sum()>300000].index) azdias.drop(drop_columns, axis='columns', inplace=True) print(drop_columns) # #### Discussion 1.1.2: Assess Missing Data in Each Column # # (Double click this cell and replace this text with your own text, reporting your observations regarding the amount of missing data in each column. Are there any patterns in missing values? Which columns were removed from the dataset?) # # Most of the columns are having missing data less than 160000 and it looks like 6 columns are having outlier or large amount of data. # Below are the columns removed which are in outlier # ('AGER_TYP', 'GEBURTSJAHR', 'TITEL_KZ', 'ALTER_HH', 'KK_KUNDENTYP', 'KBA05_BAUMAX') # #### Step 1.1.3: Assess Missing Data in Each Row # # Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold. # # In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values. # - You can use seaborn's [`countplot()`](https://seaborn.pydata.org/generated/seaborn.countplot.html) function to create a bar chart of code frequencies and matplotlib's [`subplot()`](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplot.html) function to put bar charts for the two subplots side by side. # - To reduce repeated code, you might want to write a function that can perform this comparison, taking as one of its arguments a column to be compared. # # Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. **Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.** # How much data is missing in each row of the dataset? azdias.isnull().sum(axis=1).sort_values(ascending=False).hist() # Write code to divide the data into two subsets based on the number of missing # values in each row. below_threshold = azdias.drop(azdias[azdias.isnull().sum(axis=1)>25].index) above_threshold = azdias.drop(azdias[azdias.isnull().sum(axis=1)<=25].index) # + # Compare the distribution of values for at least five columns where there are # no or few missing values, between the two subsets. below_threshold.isnull().sum()[below_threshold.isnull().sum()==0] # - print(below_threshold.shape) below_threshold.columns above_threshold.isnull().sum()[above_threshold.isnull().sum()==0] print(above_threshold.shape) above_threshold.columns # + def drawchart(column): axis1 = plt.subplot(1,2,1) sns.countplot(above_threshold[column], ax=axis1) axis2 = plt.subplot(1,2,2) sns.countplot(below_threshold[column], ax=axis2) drawchart('ANREDE_KZ') # - drawchart('FINANZ_MINIMALIST') drawchart('FINANZ_SPARER') drawchart('FINANZ_VORSORGER') drawchart('FINANZ_ANLEGER') # #### Discussion 1.1.3: Assess Missing Data in Each Row # # (Double-click this cell and replace this text with your own text, reporting your observations regarding missing data in rows. Are the data with lots of missing values are qualitatively different from data with few or no missing values?) # # By looking at the data it looks like lot of missing values are having different distribution. One or two values are having large number. # ### Step 1.2: Select and Re-Encode Features # # Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (`feat_info`) for a summary of types of measurement. # - For numeric and interval data, these features can be kept without changes. # - Most of the variables in the dataset are ordinal in nature. While ordinal values may technically be non-linear in spacing, make the simplifying assumption that the ordinal variables can be treated as being interval in nature (that is, kept without any changes). # - Special handling may be necessary for the remaining two variable types: categorical, and 'mixed'. # # In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns. # # Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project! # How many features are there of each data type? feat_info.groupby(by='type').count() # #### Step 1.2.1: Re-Encode Categorical Features # # For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following: # - For binary (two-level) categoricals that take numeric values, you can keep them without needing to do anything. # - There is one binary variable that takes on non-numeric values. For this one, you need to re-encode the values as numbers or create a dummy variable. # - For multi-level categoricals (three or more values), you can choose to encode the values using multiple dummy variables (e.g. via [OneHotEncoder](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html)), or (to keep things straightforward) just drop them from the analysis. As always, document your choices in the Discussion section. for attribute in feat_info[feat_info['type']=='categorical'].attribute: if attribute in azdias.columns: print(attribute, azdias[attribute].nunique()) # Assess categorical variables: which are binary, which are multi-level, and # which one needs to be re-encoded? #Assess categorical variables: binary for attribute in feat_info[feat_info['type']=='categorical'].attribute: if attribute in azdias.columns: if azdias[attribute].nunique() == 2: print(attribute, azdias[attribute].unique()) #Drop columns before adding multi level attributes print(drop_columns) # add multi-level attributes for drop_columns for attribute in feat_info[feat_info['type']=='categorical'].attribute: if attribute in below_threshold.columns: if below_threshold[attribute].nunique() > 2: below_threshold.drop(attribute, axis='columns', inplace=True) drop_columns.append(attribute) print(drop_columns) #below Threshold columns and shape print("Below Threshold:",below_threshold.shape) print("Columns:",below_threshold.columns) # Re-encode categorical variable(s) to be kept in the analysis. below_threshold = pd.get_dummies(below_threshold, columns=['OST_WEST_KZ']) print(below_threshold.columns) # #### Discussion 1.2.1: Re-Encode Categorical Features # # (Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding categorical features. Which ones did you keep, which did you drop, and what engineering steps did you perform?) # # ###### Binary: # Here are the Binary variables: ANREDE_KZ,GREEN_AVANTGARDE,SOHO_KZ,VERS_TYP,OST_WEST_KZ # # ###### Multilevel variables: # Here are the Multi level variables: 'CJT_GESAMTTYP', 'FINANZTYP', 'GFK_URLAUBERTYP', 'LP_FAMILIE_FEIN', 'LP_FAMILIE_GROB', 'LP_STATUS_FEIN', 'LP_STATUS_GROB', 'NATIONALITAET_KZ', 'SHOPPER_TYP', 'ZABEOTYP', 'GEBAEUDETYP', 'CAMEO_DEUG_2015', 'CAMEO_DEU_2015' # # ###### Encoded Variable: # OST_WEST_KZ # # Will keep Binary variables and remove multi level variables. # # # # #### Step 1.2.2: Engineer Mixed-Type Features # # There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices: # - "PRAEGENDE_JUGENDJAHRE" combines information on three dimensions: generation by decade, movement (mainstream vs. avantgarde), and nation (east vs. west). While there aren't enough levels to disentangle east from west, you should create two new variables to capture the other two dimensions: an interval-type variable for decade, and a binary variable for movement. # - "CAMEO_INTL_2015" combines information on two axes: wealth and life stage. Break up the two-digit codes by their 'tens'-place and 'ones'-place digits into two new ordinal variables (which, for the purposes of this project, is equivalent to just treating them as their raw numeric values). # - If you decide to keep or engineer new features around the other mixed-type features, make sure you note your steps in the Discussion section. # # Be sure to check `Data_Dictionary.md` for the details needed to finish these tasks. # + # Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables. movement = { 1: [40,0], 2: [40,1], 3: [50,0], 4: [50,1], 5: [60,0], 6: [60,1], 7: [60,1], 8: [70,0], 9: [70,1], 10: [80,0], 11: [80,1], 12: [80,0], 13: [80,1], 14: [90,0], 15: [90,1], np.nan: [np.nan, np.nan] } below_threshold['GENERATION'] = below_threshold['PRAEGENDE_JUGENDJAHRE'].apply(lambda x: np.nan if np.isnan(x) else movement[x][0]) below_threshold['MOVEMENT'] = below_threshold['PRAEGENDE_JUGENDJAHRE'].apply(lambda x: np.nan if np.isnan(x) else movement[x][1]) below_threshold.drop('PRAEGENDE_JUGENDJAHRE', axis='columns', inplace=True) # - # Investigate "CAMEO_INTL_2015" and engineer two new variables. below_threshold['CAMEO_INTL_2015_tens'] = below_threshold['CAMEO_INTL_2015'].str[0] below_threshold['CAMEO_INTL_2015_ones'] = below_threshold['CAMEO_INTL_2015'].str[1] below_threshold.drop('CAMEO_INTL_2015', axis=1, inplace=True) below_threshold.head() # remove all mixed attributes except PRAEGENDE_JUGENDJAHRE and CAMEO_INTL_2015 for attribute in feat_info[feat_info['type']=='mixed'].attribute: drop_columns.append(attribute) drop_columns.remove('PRAEGENDE_JUGENDJAHRE') drop_columns.remove('CAMEO_INTL_2015') print(drop_columns) # #### Discussion 1.2.2: Engineer Mixed-Type Features # # (Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding mixed-value features. Which ones did you keep, which did you drop, and what engineering steps did you perform?) # # Drop PRAEGENDE_JUGENDJAHRE and engineer two new variables. Out of these two, one for movement and other one for generation. # Drop CAMEO_INTL_2015 and engineer two new variables. Out of these two, one for its tens digit and other one for ones digit. # # By looking at the mixed value features, most of them are having several feature with in one feature and we can't simply encode all of them with dummy values. At the same time if we need them then we need to deal with one by one. Hence drop all other mixed value features and it makes our job more easy. # #### Step 1.2.3: Complete Feature Selection # # In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following: # - All numeric, interval, and ordinal type columns from the original dataset. # - Binary categorical features (all numerically-encoded). # - Engineered features from other multi-level categorical features and mixed features. # # Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from **the subset with few or no missing values**. # + # If there are other re-engineering tasks you need to perform, make sure you # take care of them here. (Dealing with missing data will come in step 2.1.) # + # Do whatever you need to in order to ensure that the dataframe only contains # the columns that should be passed to the algorithm functions. # - # ### Step 1.3: Create a Cleaning Function # # Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step. # + movement = { 1: [40,0], 2: [40,1], 3: [50,0], 4: [50,1], 5: [60,0], 6: [60,1], 7: [60,1], 8: [70,0], 9: [70,1], 10: [80,0], 11: [80,1], 12: [80,0], 13: [80,1], 14: [90,0], 15: [90,1] } # - def clean_data(df): """ Perform feature trimming, re-encoding, and engineering for demographics data INPUT: Demographics DataFrame OUTPUT: Trimmed and cleaned demographics DataFrame """ # Put in code here to execute all main cleaning steps: # convert missing value codes into NaNs, ... for attribute in feat_info['attribute']: tmp_list = feat_info[feat_info['attribute']==attribute].missing_or_unknown.iloc[0].replace('[','').replace(']','').split(',') missing_or_unknown_list = [float(x) if x.lstrip('-').isnumeric() else x for x in tmp_list] df[attribute].replace(to_replace=missing_or_unknown_list, value=np.nan, inplace=True) # remove selected columns and rows, ... df.drop(drop_columns, axis='columns', inplace=True) # select, re-encode, and engineer column values. df = pd.get_dummies(df, columns=['OST_WEST_KZ']) df['GENERATION'] = df['PRAEGENDE_JUGENDJAHRE'].apply(lambda x: np.nan if np.isnan(x) else movement[x][0]) df['MOVEMENT'] = df['PRAEGENDE_JUGENDJAHRE'].apply(lambda x: np.nan if np.isnan(x) else movement[x][1]) df.drop('PRAEGENDE_JUGENDJAHRE', axis='columns', inplace=True) df['CAMEO_INTL_2015_tens'] = df['CAMEO_INTL_2015'].str[0] df['CAMEO_INTL_2015_ones'] = df['CAMEO_INTL_2015'].str[1] df.drop('CAMEO_INTL_2015', axis=1, inplace=True) below_threshold = df.drop(df[df.isnull().sum(axis=1)>25].index) above_threshold = df.drop(df[df.isnull().sum(axis=1)<=25].index) # Return the cleaned dataframe. return below_threshold # ## Step 2: Feature Transformation # # ### Step 2.1: Apply Feature Scaling # # Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the [API reference page for sklearn](http://scikit-learn.org/stable/modules/classes.html) to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following: # # - sklearn requires that data not have missing values in order for its estimators to work properly. So, before applying the scaler to your data, make sure that you've cleaned the DataFrame of the remaining missing values. This can be as simple as just removing all data points with missing data, or applying an [Imputer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html) to replace all missing values. You might also try a more complicated procedure where you temporarily remove missing values in order to compute the scaling parameters before re-introducing those missing values and applying imputation. Think about how much missing data you have and what possible effects each approach might have on your analysis, and justify your decision in the discussion section below. # - For the actual scaling function, a [StandardScaler](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html) instance is suggested, scaling each feature to mean 0 and standard deviation 1. # - For these classes, you can make use of the `.fit_transform()` method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project. # If you've not yet cleaned the dataset of all NaN values, then investigate and # do that now. azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv', delimiter=';') df = clean_data(azdias) #usign Imputer imp = Imputer() imp = imp.fit(df) clean_df = imp.transform(df) # + # Apply feature scaling to the general population demographics data. scaler = StandardScaler() scaler = scaler.fit(clean_df) new_df = scaler.transform(clean_df) pca_df = pd.DataFrame(new_df) pca_df.columns = df.columns pca_df.index = df.index # - print(pca_df.shape) pca_df.head() def scaling(df): clean_df = imp.transform(df) new_df = scaler.transform(clean_df) pca_df = pd.DataFrame(new_df) pca_df.columns = df.columns pca_df.index = df.index return pca_df # ### Discussion 2.1: Apply Feature Scaling # # (Double-click this cell and replace this text with your own text, reporting your decisions regarding feature scaling.) # # # I am more inclined towards imputer to fill in all missing data and use standardscalar for feature scaling. # ### Step 2.2: Perform Dimensionality Reduction # # On your scaled data, you are now ready to apply dimensionality reduction techniques. # # - Use sklearn's [PCA](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html) class to apply principal component analysis on the data, thus finding the vectors of maximal variance in the data. To start, you should not set any parameters (so all components are computed) or set a number of components that is at least half the number of features (so there's enough features to see the general trend in variability). # - Check out the ratio of variance explained by each principal component as well as the cumulative variance explained. Try plotting the cumulative or sequential values using matplotlib's [`plot()`](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html) function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project. # - Once you've made a choice for the number of components to keep, make sure you re-fit a PCA instance to perform the decided-on transformation. # + # Apply PCA to the data. pca = PCA(n_components=35) pca_X = pca.fit_transform(new_df) pca # - def pca_results(full_dataset, pca): ''' Create a DataFrame of the PCA results Add dimension feature weights and explained variance Display the PCA results ''' dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)] # PCA components components = pd.DataFrame(np.round(pca.components_, 4), columns = full_dataset.keys()) components.index = dimensions # PCA explained variance ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1) variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance']) variance_ratios.index = dimensions # Create a bar plot visualization fig, ax = plt.subplots(figsize = (14,8)) # Plot the feature weights as a function of the components components.plot(ax = ax, kind = 'bar'); ax.set_ylabel("Feature Weights") ax.set_xticklabels(dimensions, rotation=0) # Display the explained variance ratios for i, ev in enumerate(pca.explained_variance_ratio_): ax.text(i-0.40, ax.get_ylim()[1] + 0.05, "Explained Variance\n %.4f"%(ev)) # Return a concatenated DataFrame return pd.concat([variance_ratios, components], axis = 1) # + # Investigate the variance accounted for by each principal component. pca_results(pca_df, pca) # - plt.plot(np.cumsum(pca.explained_variance_ratio_)) np.cumsum(pca.explained_variance_ratio_) # Re-apply PCA to the data while selecting for number of components to retain. pca = PCA(n_components=28) pca_reduced = pca.fit(pca_df) pca_X = pca.transform(pca_df) np.cumsum(pca.explained_variance_ratio_) pca_X_df = pd.DataFrame(data=pca_X) pca_X_df.head() pca_reduced # ### Discussion 2.2: Perform Dimensionality Reduction # # (Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding dimensionality reduction. How many principal components / transformed features are you retaining for the next step of the analysis?) # # 28 features got retained and we can explain 85% variability pca_reduced.components_ # ### Step 2.3: Interpret Principal Components # # Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion. # # As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other. # # - To investigate the features, you should map each weight to their corresponding feature name, then sort the features according to weight. The most interesting features for each principal component, then, will be those at the beginning and end of the sorted list. Use the data dictionary document to help you understand these most prominent features, their relationships, and what a positive or negative value on the principal component might indicate. # - You should investigate and interpret feature associations from the first three principal components in this substep. To help facilitate this, you should write a function that you can call at any time to print the sorted list of feature weights, for the *i*-th principal component. This might come in handy in the next step of the project, when you interpret the tendencies of the discovered clusters. # + # Map weights for the first principal component to corresponding feature names # and then print the linked values, sorted by weight. # HINT: Try defining a function here or in a new cell that you can reuse in the # other cells. def map_weight(df, component): pca_df = pd.DataFrame(pca.components_, columns=list(df.columns)) pca_component = pd.DataFrame(pca_df.iloc[component]) print(pca_component.sort_values(component, ascending=False)) # - map_weight(pca_df, 0) # + # Map weights for the second principal component to corresponding feature names # and then print the linked values, sorted by weight. map_weight(pca_df, 1) # + # Map weights for the third principal component to corresponding feature names # and then print the linked values, sorted by weight. map_weight(pca_df, 2) # - # ### Discussion 2.3: Interpret Principal Components # # (Double-click this cell and replace this text with your own text, reporting your observations from detailed investigation of the first few principal components generated. Can we interpret positive and negative values from them in a meaningful way?) # # If we got positive values then it means that the feature is directly proportional to associated principal component. In the first principal components, we know that number of family houses in the PLZ8 region are very important features PLZ8_ANTG3 & PLZ8_ANTG4 (positive), PLZ8_ANTG1 (negative). It shows that top 5 positive and top 5 negative. # # In the second principal components, we know that Personality typology is a influent factor: event-oriented(+ve), sensual-minded(+ve), dutiful(-ve), religious(-ve) are like top 5 are positive and top5 negative. In the third principal components, we know that other personality typology contributes a lot: # # Positive: dreamful, socially-minded, cultural-minded, family-minded. # # Negative: event-oriented, critical-minded, dominant-minded, combative attitude. # ## Step 3: Clustering # # ### Step 3.1: Apply Clustering to General Population # # You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep. # # - Use sklearn's [KMeans](http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans) class to perform k-means clustering on the PCA-transformed data. # - Then, compute the average difference from each point to its assigned cluster's center. **Hint**: The KMeans object's `.score()` method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding. # - Perform the above two steps for a number of different cluster counts. You can then see how the average distance decreases with an increasing number of clusters. However, each additional cluster provides a smaller net benefit. Use this fact to select a final number of clusters in which to group the data. **Warning**: because of the large size of the dataset, it can take a long time for the algorithm to resolve. The more clusters to fit, the longer the algorithm will take. You should test for cluster counts through at least 10 clusters to get the full picture, but you shouldn't need to test for a number of clusters above about 30. # - Once you've selected a final number of clusters to use, re-fit a KMeans instance to perform the clustering operation. Make sure that you also obtain the cluster assignments for the general demographics data, since you'll be using them in the final Step 3.3. # + # Over a number of different cluster counts... def lets_kmeans(n, df): kmeans = KMeans(n_clusters=n) # run k-means clustering on the data and... preds = kmeans.fit_predict(df) # compute the average within-cluster distances. pred_centroids = kmeans.cluster_centers_ centers = pred_centroids[preds] distance = np.sqrt(((train_trans - centers) ** 2).sum(axis = 1)).mean() distances.append(distance) return model.score(df) # + # Investigate the change in within-cluster distance across number of clusters. # HINT: Use matplotlib's plot function to visualize this relationship. cluster_nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] distances = [] for c in cluster_nums: print('evaluating for {} clusters'.format(c)) kmeans = KMeans(n_clusters=c) preds = kmeans.fit_predict(pca_X_df) pred_centroids = kmeans.cluster_centers_ centers = pred_centroids[preds] distance = np.sqrt(((pca_X_df - centers) ** 2).sum(axis = 1)).mean() distances.append(distance) plt.plot(cluster_nums, distances, '-o') plt.ylabel('Avg. distance to centroid') plt.xlabel('# of clusters') plt.savefig('distance_to_centroid.png') # - # Re-fit the k-means model with the selected number of clusters and obtain # cluster predictions for the general population demographics data. kmeans = KMeans(n_clusters=8) model = kmeans.fit(pca_X_df) prediction_azdias = model.predict(pca_X_df) # ### Discussion 3.1: Apply Clustering to General Population # # (Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding clustering. Into how many clusters have you decided to segment the population?) # # By looking at the curve, decided to use 8 clusters. # ### Step 3.2: Apply All Steps to the Customer Data # # Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data. # # - Don't forget when loading in the customers data, that it is semicolon (`;`) delimited. # - Apply the same feature wrangling, selection, and engineering steps to the customer demographics using the `clean_data()` function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.) # - Use the sklearn objects from the general demographics data, and apply their transformations to the customers data. That is, you should not be using a `.fit()` or `.fit_transform()` method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data. # Load in the customer demographics data. customers = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', delimiter=';') customers.columns # Apply preprocessing, feature transformation, and clustering from the general # demographics onto the customer data, obtaining cluster predictions for the # customer demographics data. cleaned_customers = clean_data(customers) scaled_customers = scaling(cleaned_customers) scaled_customers print(scaled_customers.shape) pca_X_customers = pca.transform(scaled_customers) pca_X_customers_df = pd.DataFrame(data=pca_X_customers) pca_X_customers prediction_of_customer = model.predict(pca_X_customers_df) prediction_of_customer # ### Step 3.3: Compare Customer Data to Demographics Data # # At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is. # # Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics. # # Take a look at the following points in this step: # # - Compute the proportion of data points in each cluster for the general population and the customer data. Visualizations will be useful here: both for the individual dataset proportions, but also to visualize the ratios in cluster representation between groups. Seaborn's [`countplot()`](https://seaborn.pydata.org/generated/seaborn.countplot.html) or [`barplot()`](https://seaborn.pydata.org/generated/seaborn.barplot.html) function could be handy. # - Recall the analysis you performed in step 1.1.3 of the project, where you separated out certain data points from the dataset if they had more than a specified threshold of missing values. If you found that this group was qualitatively different from the main bulk of the data, you should treat this as an additional data cluster in this analysis. Make sure that you account for the number of data points in this subset, for both the general population and customer datasets, when making your computations! # - Which cluster or clusters are overrepresented in the customer dataset compared to the general population? Select at least one such cluster and infer what kind of people might be represented by that cluster. Use the principal component interpretations from step 2.3 or look at additional components to help you make this inference. Alternatively, you can use the `.inverse_transform()` method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly. # - Perform a similar investigation for the underrepresented clusters. Which cluster or clusters are underrepresented in the customer dataset compared to the general population, and what kinds of people are typified by these clusters? # Compare the proportion of data in each cluster for the customer data to the # proportion of data in each cluster for the general population. sns.countplot(prediction_of_customer) sns.countplot(prediction_azdias) sns.barplot(x=prediction_of_customer, y=prediction_of_customer, estimator=lambda x: len(x)/len(prediction_of_customer)*100) sns.barplot(x=prediction_azdias, y=prediction_azdias, estimator=lambda x: len(x)/len(prediction_azdias)*100) def plot_scaled_comparison(df_sample, kmeans, cluster): X = pd.DataFrame.from_dict(dict(zip(df_sample.columns, pca_reduced.inverse_transform(kmeans.cluster_centers_[cluster]))), orient='index').rename( columns={0: 'feature_values'}).sort_values('feature_values', ascending=False) X['feature_values_abs'] = abs(X['feature_values']) pd.concat((X['feature_values'][:10], X['feature_values'][-10:]), axis=0).plot(kind='barh') # What kinds of people are part of a cluster that is overrepresented in the # customer data compared to the general population? plot_scaled_comparison(scaled_customers, model, 3) # What kinds of people are part of a cluster that is underrepresented in the # customer data compared to the general population? plot_scaled_comparison(scaled_customers, model, 5) plot_scaled_comparison(scaled_customers, model, 6) # ### Discussion 3.3: Compare Customer Data to Demographics Data # # (Double-click this cell and replace this text with your own text, reporting findings and conclusions from the clustering analysis. Can we describe segments of the population that are relatively popular with the mail-order company, or relatively unpopular with the company?) # # Segments of Population that are Popular: # # Company 3 are much more than the public. It is related to high affinity of combative attitude, male, low financial interest. # Segments of Population that are Unpopular: # # Company: 5,6 are much less than the public. 5 is mostly related with Personality typology especially low affinity of rational, and relative young age (ALTERSKATEGORIE_GROB). 6 is mostly related with Personality typology especially rational, and high financial interest. # > Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in **Discussion** cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to **File -> Download as -> HTML (.html)**. You will submit both that document and this notebook for your project submission.
Identify_Customer_Segments.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 shutil import apiquery import pandas as pd import sys import seaborn as sns import os import numpy as np import random import torch import gc DATA_PATH = '../01.Data' shutil.copy("apiquery_pyc.py", "apiquery.pyc") module_path = "../src" if module_path not in sys.path: sys.path.append(module_path) from utils.training import * from utils.encoding import * from utils.utils import * from utils.fetch import * from dataset.dataset import BNPParibasText from models.models import Roberta_Model from utils.EarlyStopping import EarlyStopping from utils.LoopFunctions import train_fn,valid_fn from utils.prediction import get_prediction pd.options.display.max_rows = 100 pd.options.display.max_columns = 100 import math from collections import Counter from sklearn.model_selection import StratifiedKFold from sklearn.metrics import mean_squared_error import math import time import lightgbm as lgbm import matplotlib.pyplot as plt import torch.nn as nn import config import transformers # - # %%time df_train = pd.read_csv(os.path.join("../01.Data",'fold.csv')) y_submission = pd.read_csv(os.path.join(DATA_PATH,'y_test_submission_example.tsv'), index_col='Index', encoding='utf-8', sep='\t') def generate_col_unique(df,cols_encode): col_unique = '' suma = '' for i in cols_encode: col_unique = col_unique + i + '_' suma = suma + ', '+df[i] df[col_unique] = suma return col_unique def calc_oof(df,config): df.loc[:,'oof'] = -1 for fold in np.sort(df.fold.unique()): print(f'Predicting Model: {fold}') valid = df[df['fold']==fold] valid_index = valid.index.to_list() valid = valid.reset_index(drop=True) # Defining DataSet col_unique = generate_col_unique(valid,config.COLUMNS_ENCODE) tokenizer = transformers.RobertaTokenizer.from_pretrained(config.PRETRAINED) valid_dataset = BNPParibasText(valid,config.MAX_LENGTH,tokenizer,col_unique) valid_loader = torch.utils.data.DataLoader( valid_dataset, batch_size = config.BATCH_SIZE, num_workers = config.NUM_WORKERS, shuffle = False, pin_memory = True, ) # Defining Device model = Roberta_Model(pretrained_model=config.PRETRAINED,dropout = config.DROPOUT) model.load_state_dict(torch.load(f'../03.Models/BNP_PARIBAS_ROBERTA_FOLD_{fold}')) model.to(config.DEVICE) preds = get_prediction(valid_loader, model,config.DEVICE) df.loc[valid_index,'oof'] = preds oof_score = np.sqrt(mean_squared_error(df['target'],df['oof'])) print('OOF_SCORE (RMSE): ',oof_score) return oof_score # Calculating predictions for test def calculate_test(test,config): col_unique = generate_col_unique(test,config.COLUMNS_ENCODE) tokenizer = transformers.RobertaTokenizer.from_pretrained(config.PRETRAINED) test_dataset = BNPParibasText(test,config.MAX_LENGTH,tokenizer,col_unique) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size = config.BATCH_SIZE, pin_memory = True, num_workers = config.NUM_WORKERS ) preds = 0 for fold in range(0,5): model = Roberta_Model(pretrained_model=config.PRETRAINED,dropout = config.DROPOUT) model.load_state_dict(torch.load(f'../03.Models/BNP_PARIBAS_ROBERTA_FOLD_{fold}')) model.to(config.DEVICE) preds = preds + get_prediction(test_loader, model,config.DEVICE) test['preds'] = preds/5 print(f'Real RMSE: ',math.sqrt(mean_squared_error(test['preds'].values,test['Target'].values))) def run(data,fold,output_path,config,run=None): print(f'******************** Model Fold {fold} *****************') seed_everything(seed=config.SEED) train = data[data['fold']!=fold].reset_index(drop=True) valid = data[data['fold']==fold].reset_index(drop=True) col_unique = generate_col_unique(train,config.COLUMNS_ENCODE) col_unique = generate_col_unique(valid,config.COLUMNS_ENCODE) print('Train: ',train.shape[0], 'Valid: ',valid.shape[0]) # Defining DataSet tokenizer = transformers.RobertaTokenizer.from_pretrained(config.PRETRAINED) train_dataset = BNPParibasText(train,config.MAX_LENGTH,tokenizer,col_unique) valid_dataset = BNPParibasText(valid,config.MAX_LENGTH,tokenizer,col_unique) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size = config.BATCH_SIZE, pin_memory = True, num_workers = config.NUM_WORKERS ) valid_loader = torch.utils.data.DataLoader( valid_dataset, batch_size = config.BATCH_SIZE, num_workers = config.NUM_WORKERS, shuffle = False, pin_memory = True, ) # Defining Device model = Roberta_Model(pretrained_model=config.PRETRAINED,dropout = config.DROPOUT) model.to(config.DEVICE) criterion = nn.MSELoss() criterion.to(config.DEVICE) param_optimizer = list(model.named_parameters()) no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"] optimizer_parameters = [ { "params": [ p for n, p in param_optimizer if not any(nd in n for nd in no_decay) ], "weight_decay": config.WEIGHT_DECAY, }, { "params": [ p for n, p in param_optimizer if any(nd in n for nd in no_decay) ], "weight_decay": 0.0, }, ] num_train_steps = int((len(train) / config.BATCH_SIZE )* config.EPOCHS) config.SCHEDULER_PARAMETERS['NUM_TRAIN_STEPS'] = num_train_steps print(f'num_train_steps: {num_train_steps}') optimizer = fetch_optimizer(config.OPTIMIZER_NAME,config.LEARNING_RATE,optimizer_parameters) scheduler = fetch_scheduler(config.SCHEDULER_NAME,optimizer,config.SCHEDULER_PARAMETERS) es = EarlyStopping (patience = config.EARLY_STOPPING, mode = config.MODE,delta=0) for epoch in range(config.EPOCHS): print('Epoch {}, lr {}'.format(epoch, optimizer.param_groups[0]['lr'])) training_loss = train_fn(train_loader,model,criterion,optimizer,config.DEVICE,scheduler,mode_sched = config.MODE_SCHEDULER) valid_loss = valid_fn(valid_loader,model,criterion,config.DEVICE) if run: run.log({'training_loss':training_loss,'valid_loss':valid_loss}) es(valid_loss, model,output_path) if es.early_stop: print('Meet early stopping') return es.get_best_val_score() gc.collect() torch.cuda.empty_cache() print("Didn't meet early stopping") return es.get_best_val_score() for i in range(0,5): output_path = f'../03.Models/BNP_PARIBAS_ROBERTA_FOLD_{i}' run(df_train,i,output_path,config) calc_oof(df_train,config) test = pd.read_csv(os.path.join(DATA_PATH,'test_preprocessed.csv')) test['target'] = -1 calculate_test(test,config) # ## Combining Word Embeddings with More Features def get_embedding(data_loader, model, device): from tqdm.notebook import tqdm # Put the model in eval mode model.to(device) model.eval() # List for store final predictions final_predictions = [] with torch.no_grad(): tk0 = tqdm(data_loader, total=len(data_loader)) for b_idx, data in enumerate(tk0): for key,value in data.items(): data[key] = value.to(device) predictions = model._embeddings(data['ids'],data['mask']) predictions = predictions.cpu() final_predictions.append(predictions) return np.vstack(final_predictions) col_unique = generate_col_unique(df_train,config.COLUMNS_ENCODE) tokenizer = transformers.RobertaTokenizer.from_pretrained(config.PRETRAINED) train_dataset = BNPParibasText(df_train,config.MAX_LENGTH,tokenizer,col_unique) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size = 32, pin_memory = True, num_workers = 72 ) embedding_all = 0 for fold in np.sort(df_train['fold'].unique()): model = Roberta_Model(pretrained_model=config.PRETRAINED) model.load_state_dict(torch.load(f'../03.Models/BNP_PARIBAS_ROBERTA_FOLD_{fold}')) embedding_all += get_embedding(train_loader, model, 'cuda') del model torch.cuda.empty_cache() embedding_all = embedding_all/len(df_train['fold'].unique()) df_train[[f'emb_{col_unique}_{i}' for i in range(embedding_all.shape[1])]] = embedding_all # + df_test = pd.read_csv(os.path.join(DATA_PATH,'test_preprocessed.csv')) df_test['target'] = -1 col_unique = generate_col_unique(df_test,config.COLUMNS_ENCODE) tokenizer = transformers.RobertaTokenizer.from_pretrained(config.PRETRAINED) test_dataset = BNPParibasText(df_test,config.MAX_LENGTH,tokenizer,col_unique) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size = 32, pin_memory = True, num_workers = 72 ) embedding_all = 0 for fold in np.sort(df_train['fold'].unique()): model = Roberta_Model(pretrained_model=config.PRETRAINED) model.load_state_dict(torch.load(f'../03.Models/BNP_PARIBAS_ROBERTA_FOLD_{fold}')) embedding_all += get_embedding(test_loader, model, 'cuda') del model torch.cuda.empty_cache() embedding_all = embedding_all/len(df_train['fold'].unique()) df_test[[f'emb_{col_unique}_{i}' for i in range(embedding_all.shape[1])]] = embedding_all # - columns_modeling = ['additives_n','ingredients_from_palm_oil_n', 'ingredients_that_may_be_from_palm_oil_n','target', 'states_en_brands','states_en_categories','states_en_characteristics','states_en_expiration date', 'states_en_general_complete','states_en_ingredients','pnns_groups_1','pnns_groups_2', 'states_en_packaging','states_en_packaging-code-','states_en_photo_upload', 'states_en_photo_validate','states_en_product name','states_en_quantity','diff_t'] + [f'emb_{col_unique}_{i}' for i in range(embedding_all.shape[1])] columns_label = df_train[columns_modeling].select_dtypes(include=['object']).columns.to_list() print(columns_label) df_train,dict_le = label_encoding(df_train,label_cols = columns_label, drop_original = True, missing_new_cat = True) df_test = apply_label_encoder(df_test,dict_le,drop_original = True, missing_new_cat = True) # + params = { 'task': 'train', 'boosting_type': 'gbdt', 'objective': 'regression', 'metric': {'rmse'}, 'num_leaves':12, 'learning_rate': 0.001, "min_child_samples": 150, "max_depth" : 5, 'feature_fraction': 0.5, "bagging_freq": 1, 'bagging_fraction': 0.75, "is_unbalance" : False, 'force_col_wise':True, 'num_threads':18, #"scale_pos_weight":5 -> Generally is the ratio of number of negative class to the positive class. 'bagging_seed':42, 'lambda_l1':1.5, 'lambda_l2':1, 'verbose': 1 } cat_columns = [i for i in df_train.columns.to_list() if i.startswith('label_')] columns_modeling_last = list(set(columns_modeling)-set(columns_label)) + ['fold'] + cat_columns # - results,models,importances,oof,feature_list = Training_Lightgbm(df_train[columns_modeling_last],params,fold_column = 'fold',target_column = 'target',cat_vars = cat_columns ,metric = 'RMSE',early_stopping = 200,max_boost_round = 8000) probs = 0 for i in models: probs = probs + (i.predict(df_test[feature_list])) print('fin_predict') y_test_pred = probs/5.0 print(f'Real: ',math.sqrt(mean_squared_error(y_test_pred,df_test['Target'].values)))
02.Code/03.Roberta Model.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Q# # language: qsharp # name: iqsharp # --- # # Joint Measurements Kata # # **Joint Measurements** quantum kata is a series of exercises designed to get you familiar with programming in Q#. It covers the joint parity measurements and using them for distinguishing quantum states or for performing multi-qubit gates. # # * In Q# joint measurements are implemented as the [Measure](https://docs.microsoft.com/qsharp/api/qsharp/microsoft.quantum.intrinsic.measure) operation. # * You can read more about measurements of multi-qubit Pauli operators in the [Q# documentation](https://docs.microsoft.com/quantum/concepts/pauli-measurements). # # Each task is wrapped in one operation preceded by the description of the task. Your goal is to fill in the blank (marked with `// ...` comments) # with some Q# code that solves the task. To verify your answer, run the cell using Ctrl/⌘+Enter. # # The tasks are given in approximate order of increasing difficulty; harder ones are marked with asterisks. # To begin, first prepare this notebook for execution (if you skip this step, you'll get "Syntax does not match any known patterns" error when you try to execute Q# code in the next cells): %package Microsoft.Quantum.Katas::0.12.20072031 # > The package versions in the output of the cell above should always match. If you are running the Notebooks locally and the versions do not match, please install the IQ# version that matches the version of the `Microsoft.Quantum.Katas` package. # > <details> # > <summary><u>How to install the right IQ# version</u></summary> # > For example, if the version of `Microsoft.Quantum.Katas` package above is 0.1.2.3, the installation steps are as follows: # > # > 1. Stop the kernel. # > 2. Uninstall the existing version of IQ#: # > dotnet tool uninstall microsoft.quantum.iqsharp -g # > 3. Install the matching version: # > dotnet tool install microsoft.quantum.iqsharp -g --version 0.1.2.3 # > 4. Reinstall the kernel: # > dotnet iqsharp install # > 5. Restart the Notebook. # > </details> # %workspace reload # ### Task 1. Single-qubit measurement # # **Input:** Two qubits (stored in an array) which are guaranteed to be either in superposition of states $|00\rangle$ and $|11\rangle$ or in superposition of states $|01\rangle$ and $|10\rangle$. # # **Output:** 0 if qubits were in the first superposition, 1 if they were in the second superposition. # *The state of the qubits at the end of the operation does not matter.* # # <br/> # <details closed> # <summary><b>Need a hint? Click here</b></summary> # Use two single-qubit measurements. # </details> # + %kata T01_SingleQubitMeasurement_Test operation SingleQubitMeasurement (qs : Qubit[]) : Int { // ... return -1; } # - # *Can't come up with a solution? See the explained solution in the [Joint Measurements Workbook](./Workbook_JointMeasurements.ipynb#Task-1.-Single-qubit-measurement).* # ### Task 2. Parity measurement # # **Inputs**: Two qubits (stored in an array) which are guaranteed to be either in superposition of states $|00\rangle$ and $|11\rangle$ or in superposition of states $|01\rangle$ and $|10\rangle$. # # **Output**: 0 if qubits were in the first superposition, 1 if they were in the second superposition. # *The state of the qubits at the end of the operation should be the same as the starting state.* # + %kata T02_ParityMeasurement_Test operation ParityMeasurement (qs : Qubit[]) : Int { // ... return -1; } # - # *Can't come up with a solution? See the explained solution in the [Joint Measurements Workbook](./Workbook_JointMeasurements.ipynb#Task-2.-Parity-measurement).* # ### Task 3. $|0000\rangle + |1111\rangle$ or $|0011\rangle + |1100\rangle$ ? # **Inputs**: Four qubits (stored in an array) which are guaranteed to be either in superposition of states $|0000\rangle$ and $|1111\rangle$ or in superposition of states $|0011\rangle$ and $|1100\rangle$. # # **Output** : 0 if qubits were in the first superposition, 1 if they were in the second superposition. # *The state of the qubits at the end of the operation should be the same as the starting state.* # + %kata T03_GHZOrGHZWithX_Test operation GHZOrGHZWithX (qs : Qubit[]) : Int { // ... return -1; } # - # *Can't come up with a solution? See the explained solution in the [Joint Measurements Workbook](./Workbook_JointMeasurements.ipynb#Task-3.-$|0000\rangle-+-|1111\rangle$-or-$|0011\rangle-+-|1100\rangle$--?).* # ### Task 4. GHZ state or W state ? # # **Inputs:** An **even** number of qubits (stored in an array) which are guaranteed to be either in a superposition of states $|0..0\rangle$ and $|1..1\rangle$ (the [GHZ state](https://en.wikipedia.org/wiki/Greenberger%E2%80%93Horne%E2%80%93Zeilinger_state)) or in the [W state](https://en.wikipedia.org/wiki/W_state). # # **Output:** 0 if qubits were in the first superposition, 1 if they were in the second superposition. # *The state of the qubits at the end of the operation should be the same as the starting state.* # + %kata T04_GHZOrWState_Test operation GHZOrWState (qs : Qubit[]) : Int { // ... return -1; } # - # *Can't come up with a solution? See the explained solution in the [Joint Measurements Workbook](./Workbook_JointMeasurements.ipynb#Task-4.-GHZ-state-or-W-state-?).* # ### <a name="parity-x"></a> Task 5*. Parity measurement in different basis # # **Inputs:** Two qubits (stored in an array) which are guaranteed to be # * either in superposition $\alpha |00\rangle + \beta |01\rangle + \beta |10\rangle + \alpha |11\rangle$ # * or in superposition $\alpha |00\rangle - \beta |01\rangle + \beta |10\rangle - \alpha |11\rangle$ # # **Output:** 0 if qubits were in the first superposition, 1 if they were in the second superposition. # *The state of the qubits at the end of the operation should be the same as the starting state.* # + %kata T05_DifferentBasis_Test operation DifferentBasis (qs : Qubit[]) : Int { // ... return -1; } # - # *Can't come up with a solution? See the explained solution in the [Joint Measurements Workbook](./Workbook_JointMeasurements.ipynb#parity-x).* # ### <a name="controlled-x-0"></a> Task 6*. Controlled X gate with $|0\rangle$ target # # **Input:** Two unentangled qubits (stored in an array of length 2). The first qubit (`qs[0]`) will be in state $|\psi\rangle = \alpha |0\rangle + \beta |1\rangle$ , the second (`qs[1]`) - in state $|0\rangle$ (this can be written as two-qubit state $\big(\alpha |0\rangle + \beta |1\rangle\big) \otimes |0\rangle$). # # **Output:** Change the two-qubit state to $\alpha |00\rangle + \beta |11\rangle$ using only single-qubit gates and joint measurements. Do not use two-qubit gates. You do not need to allocate extra qubits. # + %kata T06_ControlledX_Test operation ControlledX (qs : Qubit[]) : Unit { // ... } # - # *Can't come up with a solution? See the explained solution in the [Joint Measurements Workbook](./Workbook_JointMeasurements.ipynb#controlled-x-0).* # ### <a name="controlled-x"></a> Task 7**. Controlled X gate with arbitrary target # # **Input:** Two qubits (stored in an array of length 2) in an arbitrary two-qubit state $\alpha |00\rangle + \beta |01\rangle + \color{blue}\gamma |10\rangle + \color{blue}\delta |11\rangle$. # # **Goal:** Change the two-qubit state to $\alpha |00\rangle + \beta |01\rangle + \color{red}\delta |10\rangle + \color{red}\gamma |11\rangle$ using only single-qubit gates and joint measurements. Do not use two-qubit gates. # # > A general-case implementation of CNOT gate via joint measurements is described in [this paper](https://arxiv.org/pdf/1201.5734.pdf). # # <details> # <summary><b>Need a hint? Click here</b></summary> # You can use an extra qubit to perform this operation. # </details> # + %kata T07_ControlledX_General_Test operation ControlledX_General (qs : Qubit[]) : Unit { // ... } # - # *Can't come up with a solution? See the explained solution in the [Joint Measurements Workbook](./Workbook_JointMeasurements.ipynb#controlled-x).*
JointMeasurements/JointMeasurements.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 numpy as np import pandas as pd import requests import json import plotly.figure_factory as ff import plotly.express as px import plotly.graph_objects as go import seaborn as sns import matplotlib.pyplot as plt # ## Import elastic V0 data df_test = pd.read_csv("./data/results_matomo_v0.csv", dtype=str) df_test = df_test.drop(columns=["url", "Status", "Commentaire"], axis=1) df_test.head(3) df_test_2 = pd.read_csv("./data/results_nginx_v0.csv", dtype=str) df_test_2 = df_test_2.drop( columns=[ "url_post", "url_elastic", "Google", "Pappers", "siret", "degree of condifence", ], axis=1, ) df_test_2.head(3) df_test_2.columns df_test.columns df_test.shape df_test_2.shape df_test = pd.concat([df_test, df_test_2], ignore_index=True) df_test.shape df_test.dtypes df_test.head(3) df_test.shape # ## Add results V1 (avec enseignes et adresses enseignes) def find(key, dictionary): for k, v in dictionary.items(): if k == key: yield v elif isinstance(v, dict): for result in find(key, v): yield result elif isinstance(v, list): for d in v: for result in find(key, d): yield result def get_response(url, q): params["q"] = q response = requests.get(url, params=params) time_elapsed = response.elapsed.total_seconds() content = json.loads(response.content) total_results = content[0]["total_results"] total_pages = content[0]["total_pages"] siren_list = list(find("siren", content[0])) return total_results, total_pages, siren_list, time_elapsed url_elastic = "http://api.sirene.dataeng.etalab.studio/search" params = {"q": "", "page": "1", "per_page": "20"} ( df_test["results_elastic_1"], df_test["pages_elastic_1"], df_test["siren_elastic_1"], df_test["resp_time_elastic_1"], ) = ("", "", "", "") df_test for index, row in df_test.iterrows(): ( df_test["results_elastic_1"][index], df_test["pages_elastic_1"][index], df_test["siren_elastic_1"][index], df_test["resp_time_elastic_1"][index], ) = get_response(url_elastic, row["terms"]) df_test["results_elastic"] = df_test["results_elastic"].astype("int32") df_test["pages_elastic"] = df_test["pages_elastic"].astype("int32") df_test["resp_time_elastic"] = df_test["resp_time_elastic"].astype("float64") df_test["results_postgres"] = df_test["results_postgres"].astype("int32") df_test["pages_postgres"] = df_test["pages_postgres"].astype("int32") df_test["resp_time_postgres"] = df_test["resp_time_postgres"].astype("float64") df_test["results_elastic_1"] = df_test["results_elastic_1"].astype("int32") df_test["pages_elastic_1"] = df_test["pages_elastic_1"].astype("int32") df_test["resp_time_elastic_1"] = df_test["resp_time_elastic_1"].astype("float64") df_test.describe() # ## Ranks df_test["rank_elastic_1"] = "" for ind, row in df_test.iterrows(): if str(row["siren"]) in row["siren_elastic_1"]: df_test["rank_elastic_1"][ind] = row["siren_elastic_1"].index(str(row["siren"])) else: df_test["rank_elastic_1"][ind] = -1 # + # df_test['rank_elastic_1'] = df_test['rank_elastic_1'].astype('int32') # - # ## KPIs fig = px.histogram( df_test.sort_values(by=["rank_elastic_1"]), x="rank_elastic_1", color_discrete_sequence=["indianred"], title="Distribution elastic des rangs du bon résultat", ) fig.update_layout(bargap=0.5) fig.update_xaxes(type="category") fig.show() # + x_elastic = df_test.sort_values(by=["rank_elastic"])["rank_elastic"] x_postgres = df_test.sort_values(by=["rank_postgres"])["rank_postgres"] x_elastic_1 = df_test.sort_values(by=["rank_elastic_1"])["rank_elastic_1"] fig = go.Figure() fig.add_trace( go.Histogram( histfunc="count", x=x_elastic_1, name="Elasticsearch_1", marker_color="#eb0e3e", ) ) fig.add_trace( go.Histogram( histfunc="count", x=x_elastic, marker_color="#EB89B5", name="Elasticsearch" ) ) fig.add_trace( go.Histogram( histfunc="count", x=x_postgres, name="Postgres", marker_color="#330C73", ) ) fig.update_layout( title_text="Fréquence des rangs des résultats de la recherche", # title of plot xaxis_title_text="Rang du résulat dans la page", # xaxis label yaxis_title_text="Nombre de requêtes", # yaxis label bargap=0.2, # gap between bars of adjacent location coordinates bargroupgap=0.1, # gap between bars of the same location coordinates ) fig.update_xaxes(type="category") fig.show() # - fig = px.pie( df_test, names="rank_elastic_1", hole=0.7, color="rank_elastic_1", title="Pourcentages des rangs du bon résultat dans la recherche elasticsearch", ) fig.update_traces(textposition="inside", textinfo="percent+label") fig.show() fig = px.pie( df_test, names="rank_elastic", hole=0.7, color="rank_elastic", title="Pourcentages des rangs du bon résultat dans la recherche elasticsearch", ) fig.update_traces(textposition="inside", textinfo="percent+label") fig.show() df_test.to_csv("./data/elastic_wars.csv", header=True, index=False) df_test[df_test["rank_elastic_1"] == -1]["rank_elastic"].value_counts() df_test[(df_test["rank_elastic_1"] == -1) & (df_test["rank_elastic"] == "0")] df_test[(df_test["rank_elastic_1"] == -1) & (df_test["rank_elastic"] == 0)] df_test = pd.read_csv("./data/elastic_wars.csv", dtype=str) df_test
testing/elastic_war.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/fuse999/DS-Unit-1-Sprint-1-Dealing-With-Data/blob/master/module3-databackedassertions/Drive_LS_DS_113_Making_Data_backed_Assertions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="Okfr_uhwhS1X" colab_type="text" # # Lambda School Data Science - Making Data-backed Assertions # # This is, for many, the main point of data science - to create and support reasoned arguments based on evidence. It's not a topic to master in a day, but it is worth some focused time thinking about and structuring your approach to it. # + [markdown] id="9dtJETFRhnOG" colab_type="text" # ## Lecture - generating a confounding variable # # The prewatch material told a story about a hypothetical health condition where both the drug usage and overall health outcome were related to gender - thus making gender a confounding variable, obfuscating the possible relationship between the drug and the outcome. # # Let's use Python to generate data that actually behaves in this fashion! # + id="WiBkgmPJhmhE" colab_type="code" outputId="4e8ced64-58d9-46f4-a13f-c5483ff542d1" colab={"base_uri": "https://localhost:8080/", "height": 1102} import random dir(random) # Reminding ourselves what we can do here # + id="Ks5qFtpnq-q5" colab_type="code" outputId="4d8e1064-bf60-4a45-81c1-d6dcd3ecfe0a" colab={"base_uri": "https://localhost:8080/", "height": 35} # Let's think of another scenario: # We work for a company that sells accessories for mobile phones. # They have an ecommerce site, and we are supposed to analyze logs # to determine what sort of usage is related to purchases, and thus guide # website development to encourage higher conversion. # The hypothesis - users who spend longer on the site tend # to spend more. Seems reasonable, no? # But there's a confounding variable! If they're on a phone, they: # a) Spend less time on the site, but # b) Are more likely to be interested in the actual products! # Let's use namedtuple to represent our data from collections import namedtuple # purchased and mobile are bools, time_on_site in seconds User = namedtuple('User', ['purchased','time_on_site', 'mobile']) example_user = User(False, 12, False) print(example_user) # + id="lfPiHNG_sefL" colab_type="code" outputId="903da34a-fa19-4d4a-8cc7-45dd14f022cf" colab={"base_uri": "https://localhost:8080/", "height": 55} # And now let's generate 1000 example users # 750 mobile, 250 not (i.e. desktop) # A desktop user has a base conversion likelihood of 10% # And it goes up by 1% for each 15 seconds they spend on the site # And they spend anywhere from 10 seconds to 10 minutes on the site (uniform) # Mobile users spend on average half as much time on the site as desktop # But have three times as much base likelihood of buying something users = [] for _ in range(250): # Desktop users time_on_site = random.uniform(10, 600) purchased = random.random() < 0.1 + (time_on_site / 1500) users.append(User(purchased, time_on_site, False)) for _ in range(750): # Mobile users time_on_site = random.uniform(5, 300) purchased = random.random() < 0.3 + (time_on_site / 1500) users.append(User(purchased, time_on_site, True)) random.shuffle(users) print(users[:10]) # + id="9gDYb5qGuRzy" colab_type="code" outputId="bc3cb99f-c2d2-4fca-c5a0-0efb421313fb" colab={"base_uri": "https://localhost:8080/", "height": 206} # Let's put this in a dataframe so we can look at it more easily import pandas as pd user_data = pd.DataFrame(users) user_data.head() # + id="sr6IJv77ulVl" colab_type="code" outputId="07eace5e-1308-4f04-d3a9-6093a31f24ed" colab={"base_uri": "https://localhost:8080/", "height": 193} # Let's use crosstabulation to try to see what's going on pd.crosstab(user_data['purchased'], user_data['time_on_site']) # + id="hvAv6J3EwA9s" colab_type="code" outputId="7b45d8c5-2fda-4df6-fecc-a14129ed76fb" colab={"base_uri": "https://localhost:8080/", "height": 161} # OK, that's not quite what we want # Time is continuous! We need to put it in discrete buckets # Pandas calls these bins, and pandas.cut helps make them time_bins = pd.cut(user_data['time_on_site'], 5) # 5 equal-sized bins pd.crosstab(user_data['purchased'], time_bins) # + id="pjcXnJw0wfaj" colab_type="code" outputId="e8f6d2d9-7f66-46b4-d213-04145889e0df" colab={"base_uri": "https://localhost:8080/", "height": 161} # We can make this a bit clearer by normalizing (getting %) pd.crosstab(user_data['purchased'], time_bins, normalize='columns') # + id="C3GzvDxlvZMa" colab_type="code" outputId="d07bf197-350b-4bf2-a5d8-8897b8fc8446" colab={"base_uri": "https://localhost:8080/", "height": 143} # That seems counter to our hypothesis # More time on the site can actually have fewer purchases # But we know why, since we generated the data! # Let's look at mobile and purchased pd.crosstab(user_data['purchased'], user_data['mobile'], normalize='columns') # + id="KQb-wU60xCum" colab_type="code" colab={} # Yep, mobile users are more likely to buy things # But we're still not seeing the *whole* story until we look at all 3 at once # Live/stretch goal - how can we do that?
module3-databackedassertions/Drive_LS_DS_113_Making_Data_backed_Assertions_in_class.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 # --- # # Backdoor Attacks-Resilient Aggregation based on Robust Filtering of Outliers in Federated Learning for image classification # # In this notebook we provide the implemetation of the averaging mechanism RFOut, presented in [this paper](). We also provide a simple example of how to use it in a federated environment. We use [EMNIST Digits](https://www.nist.gov/itl/products-and-services/emnist-dataset) dataset, a popular dataset for the experiments. We federate the data following an I.I.D. distribution over 20 nodes (clients). # # ### Data reading # + pycharm={"is_executing": false} import warnings warnings.filterwarnings('ignore') import matplotlib.pyplot as plt import shfl database = shfl.data_base.Emnist() train_data, train_labels, test_data, test_labels = database.load_data() # + pycharm={"is_executing": false} iid_distribution = shfl.data_distribution.IidDataDistribution(database) federated_data, test_data, test_labels = iid_distribution.get_federated_data(num_nodes=20, percent=100) # - # We reshape training and test data in order to fit the required shape. For reshaping the federated data, we use the class FederatedTransformation. # + import numpy as np class Reshape(shfl.private.FederatedTransformation): def apply(self, labeled_data): labeled_data.data = np.reshape(labeled_data.data, (labeled_data.data.shape[0], labeled_data.data.shape[1], labeled_data.data.shape[2],1)) shfl.private.federated_operation.apply_federated_transformation(federated_data, Reshape()) test_data = np.reshape(test_data, (test_data.shape[0], test_data.shape[1], test_data.shape[2],1)) # - # ### Deep Learning model # # We use a simple deep learning model based on two layers of CNN implemented in Keras. # + pycharm={"is_executing": false} import tensorflow as tf def model_builder(): model = tf.keras.models.Sequential() model.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu', strides=1, input_shape=(28, 28, 1))) model.add(tf.keras.layers.MaxPooling2D(pool_size=2, strides=2, padding='valid')) model.add(tf.keras.layers.Dropout(0.4)) model.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu', strides=1)) model.add(tf.keras.layers.MaxPooling2D(pool_size=2, strides=2, padding='valid')) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(128, activation='relu')) model.add(tf.keras.layers.Dropout(0.1)) model.add(tf.keras.layers.Dense(64, activation='relu')) model.add(tf.keras.layers.Dense(10, activation='softmax')) model.compile(optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"]) return shfl.model.DeepLearningModel(model) # - # ### Federated Aggregator: RFOut # # In this point, we provide the implementation of the RFOut aggregation mechanism. For that purpose, we overwrite the implementation of the FedAvg aggregator in [rfout.py](./rfout.py). # # + pycharm={"is_executing": false} from rfout import RFOut1d aggregator = RFOut1d() federated_government = shfl.federated_government.FederatedGovernment(model_builder, federated_data, aggregator) # - # ### Run the federated algorithm # # Finally, we run 10 rounds of learning. # + pycharm={"is_executing": true} federated_government.run_rounds(10, test_data, test_labels) # -
shfl/rfout.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda root] # language: python # name: conda-root-py # --- def factorial(n): '''no recursion''' val = 1 while n > 0: val *= n n -= 1 return val factorial(8) def factorial2(n): '''with recursion''' if n < 1: return 1 else: num = n * factorial2(n - 1) return num factorial2(8) # --- def fibonacci(n): '''with recursion''' if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1)+fibonacci(n-2)
notebooks/Python/Recursion/Factorial_&_Fibonacci.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 urdubiometer import json gp = urdubiometer.GraphParser.from_yaml( ''' tokens: a: [class_a] b: [class_b] c: [class_c] ' ': [wb] rules: a: A b: B <class_c> a: A(AFTER_CLASS_C) (<class_c> b) a: A(AFTER_B_AND_CLASS_C) (<class_c> b b) a: A(AFTER_BB_AND_CLASS_C) a <class_c>: A(BEFORE_CLASS_C) a (c <class_b>): A(BEFORE_C_AND_CLASS_B) a (a): A(BEFORE_A) a (a b): A(BEFORE_AB) (a) a: A(AFTER_A) c: C ' ': ' ' onmatch_rules: - <class_a> <class_b> + <class_a> <class_b>: '!' - <class_a> + <class_b>: ',' whitespace: default: ' ' consolidate: True token_class: wb ''') _ = gp.serialize() print("'"+json.dumps(_)+"'") gp.parse("aNa") gp._graph.node[1] [gp._graph.node[_] for _ in gp._graph.node[1]['rule_children']] gp._graph.node
.ipynb_checkpoints/Untitled-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 # --- # + [markdown] colab_type="text" id="Ty1goXveqjte" # ### Author: [<NAME>](https://github.com/sharmapratik88/) # # Project 3 - Recurrent Neural Network - TV Script Generation # # In this project, we'll generate our own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs. We'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chronicles#scripts.csv) of scripts from 9 seasons. The Neural Network we'll build will generate a new, "fake" TV script, based on patterns it recognizes in this training data. # # ## Get the Data # # The data is already provided in `./data/Seinfeld_Scripts.txt` and let's open that file and look at the text. # >* As a first step, we'll load in this data and look at some samples. # * Then, we'll define and train an RNN to generate a new script! # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="65n8imT3qwtZ" outputId="f72d83ec-38fc-4a59-b6e7-eb3dcee01dd6" # Mounting Google Drive from google.colab import drive drive.mount('/content/drive') # + colab={} colab_type="code" id="VcQGqu8rq8yN" # Setting the current working directory import os; os.chdir('drive/My Drive/Udacity/Project03_TV Script Generation') # + colab={"base_uri": "https://localhost:8080/", "height": 306} colab_type="code" id="3bh6kf0lstwM" outputId="e283bf26-2adb-40a8-b206-6d761dffdea7" # !nvidia-smi # + colab={} colab_type="code" id="qJ5N2WsTqjtf" # Import packages import helper, problem_unittests as tests import numpy as np, torch from torch.utils.data import TensorDataset, DataLoader # Set seed seed = 2020 np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True # Suppress warnings import warnings; warnings.filterwarnings('ignore') # Check for a GPU train_on_gpu = torch.cuda.is_available() if not train_on_gpu: print('No GPU found. Please use a GPU to train your neural network.') # + colab={} colab_type="code" id="veSa3B5Tqjth" # load in data data_dir = './data/Seinfeld_Scripts.txt' text = helper.load_data(data_dir) # + [markdown] colab_type="text" id="V23hxn5qqjtj" # ## Explore the Data # Playing around with `view_line_range` to view different parts of the data. This will give us a sense of the data we'll be working with. We can see, for example, that it is all lowercase text, and each new line of dialogue is separated by a newline character `\n`. # + colab={"base_uri": "https://localhost:8080/", "height": 309} colab_type="code" id="k5dNP2Hzqjtk" outputId="2b5db785-330b-4dde-a72c-693e32a94340" view_line_range = (0, 10) print('Dataset Stats') print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()}))) lines = text.split('\n') print('Number of lines: {}'.format(len(lines))) word_count_line = [len(line.split()) for line in lines] print('Average number of words in each line: {}'.format(np.average(word_count_line))) print() print('The lines {} to {}:'.format(*view_line_range)) print('\n'.join(text.split('\n')[view_line_range[0]:view_line_range[1]])) # + [markdown] colab_type="text" id="8u5EsUzHqjtm" # --- # ## Implement Pre-processing Functions # The first thing to do to any dataset is pre-processing. Implement the following pre-processing functions below: # - Lookup Table # - Tokenize Punctuation # # ### Lookup Table # To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries: # - Dictionary to go from the words to an id, we'll call `vocab_to_int` # - Dictionary to go from the id to word, we'll call `int_to_vocab` # # Return these dictionaries in the following **tuple** `(vocab_to_int, int_to_vocab)` # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="gcJ8uFebqjtm" outputId="72f7dace-3220-4e06-e560-53a9d54980c3" import problem_unittests as tests def create_lookup_tables(text): """ Create lookup tables for vocabulary :param text: The text of tv scripts split into words :return: A tuple of dicts (vocab_to_int, int_to_vocab) """ vocab = set(text) w2i = {w:i for i, w in enumerate(vocab)} i2w = {i:w for i, w in enumerate(vocab)} # return tuple return (w2i, i2w) tests.test_create_lookup_tables(create_lookup_tables) # + [markdown] colab_type="text" id="nneQaKoDqjtp" # ### Tokenize Punctuation # We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks can create multiple ids for the same word. For example, "bye" and "bye!" would generate two different word ids. # # Implement the function `token_lookup` to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||". Create a dictionary for the following symbols where the symbol is the key and value is the token: # - Period ( **.** ) # - Comma ( **,** ) # - Quotation Mark ( **"** ) # - Semicolon ( **;** ) # - Exclamation mark ( **!** ) # - Question mark ( **?** ) # - Left Parentheses ( **(** ) # - Right Parentheses ( **)** ) # - Dash ( **-** ) # - Return ( **\n** ) # # This dictionary will be used to tokenize the symbols and add the delimiter (space) around it. This separates each symbols as its own word, making it easier for the neural network to predict the next word. Make sure you don't use a value that could be confused as a word; for example, instead of using the value "dash", try using something like "||dash||". # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="25_pJG6mqjtp" outputId="ee5cbeba-61e1-482e-ad9c-5d0b87d4d1ec" def token_lookup(): """ Generate a dict to turn punctuation into a token. :return: Tokenized dictionary where the key is the punctuation and the value is the token """ sym = {'.': '||Period||', ',': '||Comma||', '"': '||Quotation_Mark||', ';': '||Semicolon||', '!': '||Exclamation_mark||', '?': '||Question_mark||', '(': '||Left_Parentheses||', ')': '||Right_Parentheses||', '-': '||Dash||', '\n': '||Return||'} return sym tests.test_tokenize(token_lookup) # + [markdown] colab_type="text" id="_OdP-o7Hqjtr" # ## Pre-process all the data and save it # # Running the code cell below will pre-process all the data and save it to file. We can also look at the code for `preprocess_and_save_data` in the `helpers.py` file to see what it's doing in detail. # + colab={} colab_type="code" id="UbzzbmRrqjts" # pre-process training data helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables) # + [markdown] colab_type="text" id="dIi66iezqjtu" # # Check Point # This is our first checkpoint. If we ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. # + colab={} colab_type="code" id="w7M5GQZhqjtu" int_text, w2i, i2w, token_dict = helper.load_preprocess() # + [markdown] colab_type="text" id="u4fylIn-qjtw" # ## Build the Neural Network # In this section, we'll build the components necessary to build an RNN by implementing the RNN Module and forward and backpropagation functions. # + [markdown] colab_type="text" id="lJafKT1Qqjtx" # ## Input # Let's start with the preprocessed input data. We'll use [TensorDataset](http://pytorch.org/docs/master/data.html#torch.utils.data.TensorDataset) to provide a known format to our dataset; in combination with [DataLoader](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader), it will handle batching, shuffling, and other dataset iteration functions. # # We can create data with TensorDataset by passing in feature and target tensors. Then create a DataLoader as usual. # ``` # data = TensorDataset(feature_tensors, target_tensors) # data_loader = torch.utils.data.DataLoader(data, batch_size = batch_size) # ``` # # ### Batching # Implement the `batch_data` function to batch `words` data into chunks of size `batch_size` using the `TensorDataset` and `DataLoader` classes. # # >We can batch words using the DataLoader, but it will be up to us to create `feature_tensors` and `target_tensors` of the correct size and content for a given `sequence_length`. # # For example, say we have these as input: # ``` # words = [1, 2, 3, 4, 5, 6, 7] # sequence_length = 4 # ``` # # Your first `feature_tensor` should contain the values: # ``` # [1, 2, 3, 4] # ``` # And the corresponding `target_tensor` should just be the next "word"/tokenized word value: # ``` # 5 # ``` # This should continue with the second `feature_tensor`, `target_tensor` being: # ``` # [2, 3, 4, 5] # features # 6 # target # ``` # + colab={"base_uri": "https://localhost:8080/", "height": 102} colab_type="code" id="pSpi6sK6qjtx" outputId="138af453-d484-4f6a-9ad3-9babcc18c7e9" def batch_data(words, sequence_length, batch_size): """ Batch the neural network data using DataLoader :param words: The word ids of the TV scripts :param sequence_length: The sequence length of each batch :param batch_size: The size of each batch; the number of sequences in a batch :return: DataLoader with batched data """ feature_tens, target_tens = [], [] word_length = len(words) n_targets = word_length - sequence_length for x in range(0, n_targets): feature = words[x : sequence_length + x] target = words[sequence_length + x] feature_tens.append(feature); target_tens.append(target) feature_tens, target_tens = torch.from_numpy(np.asarray(feature_tens)), torch.from_numpy(np.asarray(target_tens)) data = TensorDataset(feature_tens, target_tens) data_loader = DataLoader(data, batch_size = batch_size, shuffle = True) return data_loader # Check for a sample words, sequence length and batch size words, sequence_length, batch_size = range(10), 5, 1 data_loader = batch_data(words, sequence_length, batch_size) print(data_loader.dataset.tensors) # + [markdown] colab_type="text" id="aU1exsHQqjt0" # ### Test your dataloader # # You'll have to modify this code to test a batching function, but it should look fairly similar. # # Below, we're generating some test text data and defining a dataloader using the function you defined, above. Then, we are getting some sample batch of inputs `sample_x` and targets `sample_y` from our dataloader. # # Your code should return something like the following (likely in a different order, if you shuffled your data): # # ``` # torch.Size([10, 5]) # tensor([[ 28, 29, 30, 31, 32], # [ 21, 22, 23, 24, 25], # [ 17, 18, 19, 20, 21], # [ 34, 35, 36, 37, 38], # [ 11, 12, 13, 14, 15], # [ 23, 24, 25, 26, 27], # [ 6, 7, 8, 9, 10], # [ 38, 39, 40, 41, 42], # [ 25, 26, 27, 28, 29], # [ 7, 8, 9, 10, 11]]) # # torch.Size([10]) # tensor([ 33, 26, 22, 39, 16, 28, 11, 43, 30, 12]) # ``` # # ### Sizes # Your sample_x should be of size `(batch_size, sequence_length)` or (10, 5) in this case and sample_y should just have one dimension: batch_size (10). # # ### Values # # You should also notice that the targets, sample_y, are the *next* value in the ordered test_text data. So, for an input sequence `[ 28, 29, 30, 31, 32]` that ends with the value `32`, the corresponding output should be `33`. # + colab={"base_uri": "https://localhost:8080/", "height": 272} colab_type="code" id="l83It964qjt1" outputId="57a52b9b-ca04-46a5-c679-6392d9f0de73" # test dataloader test_text = range(50); t_loader = batch_data(test_text, sequence_length = 5, batch_size = 10) data_iter = iter(t_loader); sample_x, sample_y = data_iter.next() print('Shape of feature sample: {}'.format(sample_x.shape)) print('Feature Sample:\n{}\n'.format(sample_x)) print('Shape of target sample: {}'.format(sample_y.shape)) print('Target Sample: {}'.format(sample_y)) # + [markdown] colab_type="text" id="L-P8ePDTqjt3" # --- # ## Build the Neural Network # Implement an RNN using PyTorch's [Module class](http://pytorch.org/docs/master/nn.html#torch.nn.Module). We can choose to use a GRU or an LSTM. To complete the RNN, implement the following functions for the class: # - `__init__` - The initialize function. # - `init_hidden` - The initialization function for an LSTM/GRU hidden state # - `forward` - Forward propagation function. # # The initialize function should create the layers of the neural network and save them to the class. The forward propagation function will use these layers to run forward propagation and generate an output and a hidden state. # # **The output of this model should be the *last* batch of word scores** after a complete sequence has been processed. That is, for each input sequence of words, we only want to output the word scores for a single, most likely, next word. # # ### Hints # # 1. Make sure to stack the outputs of the lstm to pass to your fully-connected layer, you can do this with `lstm_output = lstm_output.contiguous().view(-1, self.hidden_dim)` # 2. You can get the last batch of word scores by shaping the output of the final, fully-connected layer like so: # # ``` # # reshape into (batch_size, seq_length, output_size) # output = output.view(batch_size, -1, self.output_size) # # get last batch # out = output[:, -1] # ``` # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="k0_8FqD-qjt3" outputId="bb0bd505-251b-4d8d-9c4a-47d1d09c0f84" import torch.nn as nn class RNN(nn.Module): def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout = 0.5): """ Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimensions of the neural network :param embedding_dim: The size of embeddings, should you choose to use them :param hidden_dim: The size of the hidden layer outputs :param dropout: dropout to add in between LSTM/GRU layers """ super(RNN, self).__init__() self.output_size = output_size self.n_layers = n_layers self.hidden_dim = hidden_dim self.embedding = nn.Embedding(vocab_size, embedding_dim) self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout = dropout, batch_first = True) self.dropout = nn.Dropout(dropout) self.fc = nn.Linear(hidden_dim,output_size) def _weights_init(m): if isinstance(m, nn.Conv2d or nn.Linear or nn.GRU or nn.LSTM): init.xavier_normal_(m.weight) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d or nn.BatchNorm1d): m.weight.data.fill_(1) m.bias.data.zero_() self.apply(_weights_init) def forward(self, nn_input, hidden): """ Forward propagation of the neural network :param nn_input: The input to the neural network :param hidden: The hidden state :return: Two Tensors, the output of the neural network and the latest hidden state """ batch_size = nn_input.size(0) embeds = self.embedding(nn_input.long()) lstm_out, hidden = self.lstm(embeds, hidden) lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim) output = self.dropout(lstm_out) output = self.fc(output) output = output.view(batch_size, -1, self.output_size) out = output[:, -1] return out, hidden def init_hidden(self, batch_size): """ Initialize the hidden state of an LSTM/GRU :param batch_size: The batch_size of the hidden state :return: hidden state of dims (n_layers, batch_size, hidden_dim) """ weight = next(self.parameters()).data if (train_on_gpu): hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda(), weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda()) else: hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_(), weight.new(self.n_layers, batch_size, self.hidden_dim).zero_()) return hidden tests.test_rnn(RNN, train_on_gpu) # + [markdown] colab_type="text" id="PNSp-kI0qjt5" # ### Define forward and backpropagation # # Use the RNN class implemented to apply forward and back propagation. This function will be called, iteratively, in the training loop as follows: # ``` # loss = forward_back_prop(decoder, decoder_optimizer, criterion, inp, target) # ``` # # And it should return the average loss over a batch and the hidden state returned by a call to `RNN(inp, hidden)`. Recall that you can get this loss by computing it, as usual, and calling `loss.item()`. # # **If a GPU is available, you should move your data to that GPU device, here.** # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="X7XNw_iUqjt6" outputId="c8484b00-6650-4ede-87ec-053d51fd03ce" def forward_back_prop(rnn, optimizer, criterion, inp, target, hidden): """ Forward and backward propagation on the neural network :param rnn: The PyTorch Module that holds the neural network :param optimizer: The PyTorch optimizer for the neural network :param criterion: The PyTorch loss function :param inp: A batch of input to the neural network :param target: The target output for the batch of input :return: The loss and the latest hidden state Tensor """ # move data to GPU, if available if train_on_gpu: inp, target = inp.cuda(), target.cuda() hidden = tuple([each.data for each in hidden]) optimizer.zero_grad() if train_on_gpu: inpt, tgt = inp.type(torch.cuda.FloatTensor).detach(), target.type(torch.cuda.LongTensor).detach() else: inpt, tgt = inp.type(torch.FloatTensor), target.type(torch.LongTensor) output, hidden = rnn(inpt, hidden) loss = criterion(output, tgt) # perform backpropagation and optimization loss.backward(retain_graph = True) nn.utils.clip_grad_norm_(rnn.parameters(), 5) optimizer.step() # return the loss over a batch and the hidden state produced by our model return loss.item(), hidden tests.test_forward_back_prop(RNN, forward_back_prop, train_on_gpu) # + [markdown] colab_type="text" id="WwZKJIpcqjt8" # ## Neural Network Training # # With the structure of the network complete and data ready to be fed in the neural network, it's time to train it. # # ### Train Loop # # The training loop is implemented in the `train_decoder` function. This function will train the network over all the batches for the number of epochs given. The model progress will be shown every number of batches. This number is set with the `show_every_n_batches` parameter. # + colab={} colab_type="code" id="ZTdBUTrMqjt8" def train_rnn(rnn, batch_size, optimizer, criterion, n_epochs, show_every_n_batches = 100): batch_losses = [] rnn.train() print("Training for %d epoch(s)..." % n_epochs) for epoch_i in range(1, n_epochs + 1): # initialize hidden state hidden = rnn.init_hidden(batch_size) for batch_i, (inputs, labels) in enumerate(train_loader, 1): # make sure you iterate over completely full batches, only n_batches = len(train_loader.dataset)//batch_size if(batch_i > n_batches): break # forward, back prop loss, hidden = forward_back_prop(rnn, optimizer, criterion, inputs, labels, hidden) # record loss batch_losses.append(loss) # printing loss stats if batch_i % show_every_n_batches == 0: print('Epoch: {:>4}/{:<4} Loss: {}'.format( epoch_i, n_epochs, np.average(batch_losses))) batch_losses = [] # returns a trained rnn return rnn # + [markdown] colab_type="text" id="OOiu5as1qjt-" # ### Hyperparameters # # Set and train the neural network with the following parameters: # - Set `sequence_length` to the length of a sequence. # - Set `batch_size` to the batch size. # - Set `num_epochs` to the number of epochs to train for. # - Set `learning_rate` to the learning rate for an Adam optimizer. # - Set `vocab_size` to the number of unique tokens in our vocabulary. # - Set `output_size` to the desired size of the output. # - Set `embedding_dim` to the embedding dimension; smaller than the vocab_size. # - Set `hidden_dim` to the hidden dimension of your RNN. # - Set `n_layers` to the number of layers/cells in your RNN. # - Set `show_every_n_batches` to the number of batches at which the neural network should print progress. # # If the network isn't getting the desired results, tweak these parameters and/or the layers in the `RNN` class. # + colab={} colab_type="code" id="v8yR0OzTqjt_" # Data params # Sequence Length sequence_length = 25 # Batch Size batch_size = 256 # Length of w2i dictionary len_w2i = len(w2i) # Data Loader train_loader = batch_data(int_text, sequence_length, batch_size) # + colab={} colab_type="code" id="CJy_fvxTqjuA" # Training parameters # Number of Epochs num_epochs = 10 # Learning Rate learning_rate = 0.001 # Model parameters # Vocab size vocab_size = len(i2w) # Output size output_size = vocab_size # Embedding Dimension embedding_dim = 256 # Hidden Dimension hidden_dim = 1024 # Number of RNN Layers n_layers = 1 # Show stats for every n number of batches show_every_n_batches = 1000 # + [markdown] colab_type="text" id="rNtpaMj-qjuC" # ### Train # In the next cell, we'll train the neural network on the pre-processed data. If we have a hard time getting a good loss, we may consider changing your hyperparameters. In general, we may get better results with larger hidden and n_layer dimensions, but larger models take a longer time to train. # > **Let's aim for a loss less than 3.5.** # # We should also experiment with different sequence lengths, which determine the size of the long range dependencies that a model can learn. # + colab={"base_uri": "https://localhost:8080/", "height": 561} colab_type="code" id="eiMmzTkoqjuD" outputId="e3284106-6635-4d13-9b90-64f84a7a1c69" # create model and move to gpu if available rnn = RNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout = 0.5) if train_on_gpu: rnn.cuda() # defining loss and optimization functions for training optimizer = torch.optim.Adam(rnn.parameters(), lr = learning_rate) criterion = nn.CrossEntropyLoss() # training the model trained_rnn = train_rnn(rnn, batch_size, optimizer, criterion, num_epochs, show_every_n_batches) # saving the trained model helper.save_model('./save/trained_rnn', trained_rnn) print('Model Trained and Saved') # + [markdown] colab_type="text" id="E7sFT3zrqjuF" # ### Question: How did you decide on your model hyperparameters? # For example, did you try different sequence_lengths and find that one size made the model converge faster? What about your hidden_dim and n_layers; how did you decide on those? # + [markdown] colab_type="text" id="C4ur4mWGqjuF" # **Answer:** I started with exploring different settings for sequence length and batch size then realized that this didn't impact much on either the performance or convergence. Most of options I tried had a training loss of 5.X for batch 1 in epoch 1. I decided to look for research papers already published on the same, came across [paper](https://arxiv.org/ftp/arxiv/papers/1908/1908.04332.pdf), from which I tried LSTM single layer option with a `batch size, hidden_dim = 256, 1024`. With `sequence_length = 10` the loss for first `n=1000` batches was **4.85**. With `sequence_length = 20` then `sequence_length = 25`, convergence improved, next step was to modify embedding dimension from 200 to 256 and see if the convergence of loss improves, it did. Then added weight initialization method and the final selected model gave 2.74 training loss. # + [markdown] colab_type="text" id="lqs0jeMpqjuG" # --- # # Checkpoint # # After running the above training cell, your model will be saved by name, `trained_rnn`, and if you save your notebook progress, **you can pause here and come back to this code at another time**. You can resume your progress by running the next cell, which will load in our word:id dictionaries _and_ load in your saved model by name! # + colab={} colab_type="code" id="PvAOTciDqjuG" _, w2i, i2w, token_dict = helper.load_preprocess() trained_rnn = helper.load_model('./save/trained_rnn') # + [markdown] colab_type="text" id="9Gf0aNzMqjuI" # ## Generate TV Script # With the network trained and saved, We'll use it to generate a new, "fake" Seinfeld TV script in this section. # # ### Generate Text # To generate the text, the network needs to start with a single word and repeat its predictions until it reaches a set length. We'll be using the `generate` function to do this. It takes a word id to start with, `prime_id`, and generates a set length of text, `predict_len`. Also note that it uses topk sampling to introduce some randomness in choosing the most likely next word, given an output set of word scores! # + colab={} colab_type="code" id="kxY1xlobqjuI" import torch.nn.functional as F def generate(rnn, prime_id, int_to_vocab, token_dict, pad_value, predict_len = 100): """ Generate text using the neural network :param decoder: The PyTorch Module that holds the trained neural network :param prime_id: The word id to start the first prediction :param int_to_vocab: Dict of word id keys to word values :param token_dict: Dict of puncuation tokens keys to puncuation values :param pad_value: The value used to pad a sequence :param predict_len: The length of text to generate :return: The generated text """ rnn.eval() # create a sequence (batch_size=1) with the prime_id current_seq = np.full((1, sequence_length), pad_value) current_seq[-1][-1] = prime_id predicted = [int_to_vocab[prime_id]] for _ in range(predict_len): if train_on_gpu: current_seq = torch.LongTensor(current_seq).cuda() else: current_seq = torch.LongTensor(current_seq) # initialize the hidden state hidden = rnn.init_hidden(current_seq.size(0)) # get the output of the rnn output, _ = rnn(current_seq, hidden) # get the next word probabilities p = F.softmax(output, dim=1).data if(train_on_gpu): p = p.cpu() # move to cpu # use top_k sampling to get the index of the next word top_k = 5 p, top_i = p.topk(top_k) top_i = top_i.numpy().squeeze() # select the likely next word index with some element of randomness p = p.numpy().squeeze() word_i = np.random.choice(top_i, p=p/p.sum()) # retrieve that word from the dictionary word = int_to_vocab[word_i] predicted.append(word) if(train_on_gpu): current_seq = current_seq.cpu() # move to cpu # the generated word becomes the next "current sequence" and the cycle can continue if train_on_gpu: current_seq = current_seq.cpu() current_seq = np.roll(current_seq, -1, 1) current_seq[-1][-1] = word_i gen_sentences = ' '.join(predicted) # Replace punctuation tokens for key, token in token_dict.items(): ending = ' ' if key in ['\n', '(', '"'] else '' gen_sentences = gen_sentences.replace(' ' + token.lower(), key) gen_sentences = gen_sentences.replace('\n ', '\n') gen_sentences = gen_sentences.replace('( ', '(') # return all the sentences return gen_sentences # + [markdown] colab_type="text" id="3rRnazeQqjuL" # ### Generate a New Script # It's time to generate the text. Set `gen_length` to the length of TV script you want to generate and set `prime_word` to one of the following to start the prediction: # - "jerry" # - "elaine" # - "george" # - "kramer" # # You can set the prime word to _any word_ in our dictionary, but it's best to start with a name for generating a TV script. (You can also start with any other names you find in the original text file!) # + colab={"base_uri": "https://localhost:8080/", "height": 918} colab_type="code" id="pTXUHBhzqjuL" outputId="30415309-85b8-42dd-8959-8143f75c007e" # run the cell multiple times to get different results! gen_length = 400 # modify the length to your preference prime_word = 'jerry' # name for starting the script pad_word = helper.SPECIAL_WORDS['PADDING'] generated_script = generate(trained_rnn, w2i[prime_word + ':'], i2w, token_dict, w2i[pad_word], gen_length) print(generated_script) # + [markdown] colab_type="text" id="2HkhidkHqjuM" # #### Save your favorite scripts # # Once you have a script that you like (or find interesting), save it to a text file! # + colab={} colab_type="code" id="WlXKDQfWqjuN" # save script to a text file f = open("generated_script_1.txt","w") f.write(generated_script) f.close() # + [markdown] colab_type="text" id="yLZfPsXRqjuO" # # The TV Script is Not Perfect # It's ok if the TV script doesn't make perfect sense. It should look like alternating lines of dialogue, here is one such example of a few generated lines. # # ### Example generated script # # >jerry: what about me? # > # >jerry: i don't have to wait. # > # >kramer:(to the sales table) # > # >elaine:(to jerry) hey, look at this, i'm a good doctor. # > # >newman:(to elaine) you think i have no idea of this... # > # >elaine: oh, you better take the phone, and he was a little nervous. # > # >kramer:(to the phone) hey, hey, jerry, i don't want to be a little bit.(to kramer and jerry) you can't. # > # >jerry: oh, yeah. i don't even know, i know. # > # >jerry:(to the phone) oh, i know. # > # >kramer:(laughing) you know...(to jerry) you don't know. # # You can see that there are multiple characters that say (somewhat) complete sentences, but it doesn't have to be perfect! It takes quite a while to get good results, and often, you'll have to use a smaller vocabulary (and discard uncommon words), or get more data. The Seinfeld dataset is about 3.4 MB, which is big enough for our purposes; for script generation you'll want more than 1 MB of text, generally.
03_TV Script Generation/03_Pytorch_TV_Script_Generation.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="9gaZUs3rNLho" # !pip install scikit-learn==1.0 # !pip install xgboost==1.4.2 # !pip install catboost==0.26.1 # !pip install pandas==1.3.3 # !pip install radiant-mlhub==0.3.0 # !pip install rasterio==1.2.8 # !pip install numpy==1.21.2 # !pip install pathlib==1.0.1 # !pip install tqdm==4.62.3 # !pip install joblib==1.0.1 # !pip install matplotlib==3.4.3 # !pip install Pillow==8.3.2 # !pip install torch==1.9.1 # !pip install plotly==5.3.1 # + id="JsIZmmD2M_YW" import pandas as pd import numpy as np import random import torch def seed_all(seed_value): random.seed(seed_value) # Python np.random.seed(seed_value) # cpu vars torch.manual_seed(seed_value) # cpu vars if torch.cuda.is_available(): torch.cuda.manual_seed(seed_value) torch.cuda.manual_seed_all(seed_value) # gpu vars torch.backends.cudnn.deterministic = True #needed torch.backends.cudnn.benchmark = False seed_all(13) # + id="XyILW4FsM_Ya" import warnings warnings.filterwarnings("ignore") import gc import pandas as pd import numpy as np from sklearn.metrics import * from xgboost import XGBClassifier from lightgbm import LGBMClassifier from catboost import CatBoostClassifier from sklearn.model_selection import StratifiedKFold from sklearn.metrics import roc_auc_score from sklearn.ensemble import VotingClassifier from sklearn.linear_model import LogisticRegression from indices_creation import * import re from tqdm import tqdm from sklearn.linear_model import LinearRegression # + id="uAA5U-xoM_Yb" outputId="79b83de7-6c0e-451b-c87e-bf463d753627" import os os.getcwd() # + id="ax007iFaM_Yd" outputId="c1dab7ed-b9ca-4844-ce17-e9271fb855b8" train_df_mean = pd.read_csv('/root/sentinel2_updated/Train_data_prep/merged_train_data/train_mean.csv') #### we need to drop 'label' and 'field_id' later in the code test_df_mean = pd.read_csv('/root/sentinel2_updated/Test_data_prep/merged_test_data/test_mean.csv') #### we need to drop 'field_id' later in the code train_df_median = pd.read_csv('/root/sentinel2_updated/Train_data_prep/merged_train_data/train_median.csv') #### we need to drop 'field_id' later in the code test_df_median = pd.read_csv('/root/sentinel2_updated/Test_data_prep/merged_test_data/test_median.csv') #### we need to drop 'field_id' later in the code train_size = pd.read_csv('/root/sentinel2_updated/Train_data_prep/merged_train_data/size_of_field_train.csv') test_size = pd.read_csv('/root/sentinel2_updated/Test_data_prep/merged_test_data/size_of_field_test.csv') train_size = train_size.rename({'Field_id':'field_id'},axis=1) test_size = test_size.rename({'Field_id':'field_id'},axis=1) train_df_median = train_df_mean.merge(train_size, on =['field_id'],how='left') test_df_median = test_df_mean.merge(test_size, on =['field_id'],how='left') gc.collect() # + id="EI1IKy1HM_Ye" outputId="c2244ad2-c18b-4733-8793-2e90bb291d55" print(f'The shape of train data before outlier removal - {train_df_mean.shape}') train_df_mean = train_df_mean[train_df_mean.label.isin(list(range(1,10)))] print(f'The shape of train data after outlier removal - {train_df_mean.shape}') # + id="b5osa0SLM_Yf" outputId="e8308c7a-ef2e-4cc0-f3e8-5b8563a10542" relevant_fids = train_df_mean['field_id'].values.tolist() train_df_median = train_df_median[train_df_median['field_id'].isin(relevant_fids)] print(f'The shape of median train data - {train_df_median.shape} and mean train data {train_df_mean.shape}' ) ###extra columns in train_df_mean being 'label' # + id="SpoSfqGyM_Yf" outputId="4abf6193-a984-4694-cdf5-368fe7bd7607" fids_train = train_df_median['field_id'].values.tolist() fids_test = test_df_median['field_id'].values.tolist() len(fids_train),len(fids_test) # + id="R3jdY6PJM_Yg" outputId="0b2bfc9b-0b64-4232-832e-aceb5b5a0d1b" cols = ['B01_','B02_','B03_','B04_','B05_','B06_','B07_','B08_','B09_','B8A_','B11_','B12_'] columns_available = train_df_mean.columns.tolist() cols2consider = [] for col in cols: cols2consider.extend( [c for c in columns_available if col in c]) bands_with_dates = [c for c in columns_available if 'B01_' in c] dates = [c.replace('B01_','') for c in bands_with_dates] print(f'The sample showing the commencement dates where observations were seen is {dates[:10]}') print(f'The sample showing the ending dates where observations were seen is {dates[-10:]}') # + id="CAeqhA68M_Yh" train_df_mean = train_df_mean[cols2consider+['label']] test_df_mean = test_df_mean[cols2consider] train_df_median = train_df_median[cols2consider+['size_of_field']] test_df_median = test_df_median[cols2consider+['size_of_field']] # + id="Gzcke25hM_Yi" train_df_median = get_band_ndvi_red(train_df_median,dates) train_df_median = get_band_afri(train_df_median,dates) train_df_median = get_band_evi2(train_df_median,dates) train_df_median = get_band_ndmi(train_df_median,dates) train_df_median = get_band_ndvi(train_df_median,dates) train_df_median = get_band_evi(train_df_median,dates) train_df_median = get_band_bndvi(train_df_median,dates) train_df_median = get_band_nli(train_df_median,dates) # train_df_median = get_band_lci(train_df_median,dates) test_df_median = get_band_ndvi_red(test_df_median,dates) test_df_median = get_band_afri(test_df_median,dates) test_df_median = get_band_evi2(test_df_median,dates) test_df_median = get_band_ndmi(test_df_median,dates) test_df_median = get_band_ndvi(test_df_median,dates) test_df_median = get_band_evi(test_df_median,dates) test_df_median = get_band_bndvi(test_df_median,dates) test_df_median = get_band_nli(test_df_median,dates) # test_df_median = get_band_lci(test_df_median,dates) # train_df_median = train_df_median.drop(cols2consider,axis=1) # test_df_median = test_df_median.drop(cols2consider,axis=1) # + id="rs5oG7chM_Yj" train_df_median = train_df_median.reset_index(drop=True) test_df_median = test_df_median.reset_index(drop=True) # + id="ptK1T7qNM_Yj" outputId="d360cf19-dab6-4a7b-96c2-595ed13ac446" train_df_median.head(3) # + id="3-k1nPY4M_Yk" bands = ['B01_','B02_','B03_','B04_','B05_','B06_','B07_','B08_','B8A_','B09_','B11_','B12_'] # + id="IROxn1lbM_Yk" outputId="0d747d10-2343-4376-ea75-502b1b354db1" for band in bands: subtrain = train_df_median[[cols for cols in train_df_median.columns if band in cols]] print(subtrain.shape) ########## Calculating slopes for the index ############# for i in tqdm(range(subtrain.shape[0])): for month in range(4,12): cols_month = [col for col in subtrain.columns if (('month_0'+str(month) in col or 'month_'+str(month) in col) )] array = subtrain.loc[i,cols_month].dropna().values model = LinearRegression(n_jobs=-1) _ = model.fit(np.array([range(1,len(array)+1)]).reshape(-1, 1),array) colname = 'month_'+str(month)+band+'_slope' train_df_median.loc[i,colname] = model.coef_[0] # + id="nygL_ZDxM_Yl" train_df_median['field_id'] = fids_train # + id="FmuLt1_xM_Yl" outputId="958379d2-1eb8-47e2-9336-9e408f6fad39" for band in bands: subtest = test_df_median[[cols for cols in test_df_median.columns if band in cols]] print(subtest.shape) ########## Calculating slopes for the index ############# for i in tqdm(range(subtest.shape[0])): for month in range(4,12): cols_month = [col for col in subtest.columns if (('month_0'+str(month) in col or 'month_'+str(month) in col) )] array = subtest.loc[i,cols_month].dropna().values model = LinearRegression() _ = model.fit(np.array([range(1,len(array)+1)]).reshape(-1, 1),array) colname = 'month_'+str(month)+band+'_slope' test_df_median.loc[i,colname] = model.coef_[0] # + id="wY2qZtcoM_Ym" test_df_median['field_id'] = fids_test # + id="lvyYqSq_M_Ym" train_df_median.to_csv('train_with_slopes.csv',index=False) test_df_median.to_csv('test_with_slopes.csv',index=False) # + id="8WKTNTOIM_Ym" outputId="7f8cb5c5-0564-40e1-d550-ca7d65a0bcec" train_df_median # + id="w2hQj45LM_Ym" outputId="2e3c960e-f72c-4590-e26c-420b67a8e66f" test_df_median # + id="l3N0L2FBM_Yn"
6th Place - Click Click Boom/zindi_sentinel2_codes/step4.3_Slope_calculation_train_test.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="i_f5u2x9nn6I" slideshow={"slide_type": "slide"} # <left><img width=25% src="https://cornell-machine-learning.github.io/aml-images/img/cornell_tech2.svg"></left> # # # Lecture 3: Optimization and Linear Regression # # ### Applied Machine Learning # # __<NAME>__<br>Cornell Tech # + [markdown] colab_type="text" id="08ka9qHWnn6J" slideshow={"slide_type": "slide"} # # Part 1: Optimization and Calculus Background # # In the previous lecture, we learned what is a supervised machine learning problem. # # Before we turn our attention to Linear Regression, we will first dive deeper into the question of optimization. # + [markdown] slideshow={"slide_type": "slide"} # # Review: Components of A Supervised Machine Learning Problem # # At a high level, a supervised machine learning problem has the following structure: # # $$ \text{Dataset} + \underbrace{\text{Learning Algorithm}}_\text{Model Class + Objective + Optimizer } \to \text{Predictive Model} $$ # # The predictive model is chosen to model the relationship between inputs and targets. For instance, it can predict future targets. # + [markdown] slideshow={"slide_type": "slide"} # # Optimizer: Notation # # At a high-level an optimizer takes # * an objective $J$ (also called a loss function) and # * a model class $\mathcal{M}$ and finds a model $f \in \mathcal{M}$ with the smallest value of the objective $J$. # # \begin{align*} # \min_{f \in \mathcal{M}} J(f) # \end{align*} # # Intuitively, this is the function that bests "fits" the data on the training dataset $\mathcal{D} = \{(x^{(i)}, y^{(i)}) \mid i = 1,2,...,n\}$. # + [markdown] slideshow={"slide_type": "subslide"} # We will use the a quadratic function as our running example for an objective $J$. # - import numpy as np import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [8, 4] # + slideshow={"slide_type": "fragment"} def quadratic_function(theta): """The cost function, J(theta).""" return 0.5*(2*theta-1)**2 # + [markdown] slideshow={"slide_type": "subslide"} # We can visualize it. # + slideshow={"slide_type": "fragment"} # First construct a grid of theta1 parameter pairs and their corresponding # cost function values. thetas = np.linspace(-0.2,1,10) f_vals = quadratic_function(thetas[:,np.newaxis]) plt.plot(thetas, f_vals) plt.xlabel('Theta') plt.ylabel('Objective value') plt.title('Simple quadratic function') # + [markdown] slideshow={"slide_type": "slide"} # # Calculus Review: Derivatives # # Recall that the derivative $$\frac{d f(\theta_0)}{d \theta}$$ of a univariate function $f : \mathbb{R} \to \mathbb{R}$ is the instantaneous rate of change of the function $f(\theta)$ with respect to its parameter $\theta$ at the point $\theta_0$. # + slideshow={"slide_type": "subslide"} def quadratic_derivative(theta): return (2*theta-1)*2 df0 = quadratic_derivative(np.array([[0]])) # derivative at zero f0 = quadratic_function(np.array([[0]])) line_length = 0.2 plt.plot(thetas, f_vals) plt.annotate('', xytext=(0-line_length, f0-line_length*df0), xy=(0+line_length, f0+line_length*df0), arrowprops={'arrowstyle': '-', 'lw': 1.5}, va='center', ha='center') plt.xlabel('Theta') plt.ylabel('Objective value') plt.title('Simple quadratic function') # + slideshow={"slide_type": "subslide"} pts = np.array([[0, 0.5, 0.8]]).reshape((3,1)) df0s = quadratic_derivative(pts) f0s = quadratic_function(pts) plt.plot(thetas, f_vals) for pt, f0, df0 in zip(pts.flatten(), f0s.flatten(), df0s.flatten()): plt.annotate('', xytext=(pt-line_length, f0-line_length*df0), xy=(pt+line_length, f0+line_length*df0), arrowprops={'arrowstyle': '-', 'lw': 1}, va='center', ha='center') plt.xlabel('Theta') plt.ylabel('Objective value') plt.title('Simple quadratic function') # + [markdown] slideshow={"slide_type": "slide"} # # Calculus Review: Partial Derivatives # # The partial derivative $$\frac{\partial f(\theta_0)}{\partial \theta_j}$$ of a multivariate function $f : \mathbb{R}^d \to \mathbb{R}$ is the derivative of $f$ with respect to $\theta_j$ while all othe other inputs $\theta_k$ for $k\neq j$ are fixed. # + [markdown] slideshow={"slide_type": "slide"} # # Calculus Review: The Gradient # # The gradient $\nabla_\theta f$ further extends the derivative to multivariate functions $f : \mathbb{R}^d \to \mathbb{R}$, and is defined at a point $\theta_0$ as # # $$ \nabla_\theta f (\theta_0) = \begin{bmatrix} # \frac{\partial f(\theta_0)}{\partial \theta_1} \\ # \frac{\partial f(\theta_0)}{\partial \theta_2} \\ # \vdots \\ # \frac{\partial f(\theta_0)}{\partial \theta_d} # \end{bmatrix}.$$ # # The $j$-th entry of the vector $\nabla_\theta f (\theta_0)$ is the partial derivative $\frac{\partial f(\theta_0)}{\partial \theta_j}$ of $f$ with respect to the $j$-th component of $\theta$. # + [markdown] slideshow={"slide_type": "subslide"} # We will use a quadratic function as a running example. # + slideshow={"slide_type": "fragment"} def quadratic_function2d(theta0, theta1): """Quadratic objective function, J(theta0, theta1). The inputs theta0, theta1 are 2d arrays and we evaluate the objective at each value theta0[i,j], theta1[i,j]. We implement it this way so it's easier to plot the level curves of the function in 2d. Parameters: theta0 (np.array): 2d array of first parameter theta0 theta1 (np.array): 2d array of second parameter theta1 Returns: fvals (np.array): 2d array of objective function values fvals is the same dimension as theta0 and theta1. fvals[i,j] is the value at theta0[i,j] and theta1[i,j]. """ theta0 = np.atleast_2d(np.asarray(theta0)) theta1 = np.atleast_2d(np.asarray(theta1)) return 0.5*((2*theta1-2)**2 + (theta0-3)**2) # + [markdown] slideshow={"slide_type": "subslide"} # Let's visualize this function. # + slideshow={"slide_type": "fragment"} theta0_grid = np.linspace(-4,7,101) theta1_grid = np.linspace(-1,4,101) theta_grid = theta0_grid[np.newaxis,:], theta1_grid[:,np.newaxis] J_grid = quadratic_function2d(theta0_grid[np.newaxis,:], theta1_grid[:,np.newaxis]) X, Y = np.meshgrid(theta0_grid, theta1_grid) contours = plt.contour(X, Y, J_grid, 10) plt.clabel(contours) plt.axis('equal') # + [markdown] slideshow={"slide_type": "subslide"} # Let's write down the derivative of the quadratic function. # + slideshow={"slide_type": "fragment"} def quadratic_derivative2d(theta0, theta1): """Derivative of quadratic objective function. The inputs theta0, theta1 are 1d arrays and we evaluate the derivative at each value theta0[i], theta1[i]. Parameters: theta0 (np.array): 1d array of first parameter theta0 theta1 (np.array): 1d array of second parameter theta1 Returns: grads (np.array): 2d array of partial derivatives grads is of the same size as theta0 and theta1 along first dimension and of size two along the second dimension. grads[i,j] is the j-th partial derivative at input theta0[i], theta1[i]. """ # this is the gradient of 0.5*((2*theta1-2)**2 + (theta0-3)**2) grads = np.stack([theta0-3, (2*theta1-2)*2], axis=1) grads = grads.reshape([len(theta0), 2]) return grads # + [markdown] slideshow={"slide_type": "slide"} # We can visualize the derivative. # + slideshow={"slide_type": "subslide"} theta0_pts, theta1_pts = np.array([2.3, -1.35, -2.3]), np.array([2.4, -0.15, 2.75]) dfs = quadratic_derivative2d(theta0_pts, theta1_pts) line_length = 0.2 contours = plt.contour(X, Y, J_grid, 10) for theta0_pt, theta1_pt, df0 in zip(theta0_pts, theta1_pts, dfs): plt.annotate('', xytext=(theta0_pt, theta1_pt), xy=(theta0_pt-line_length*df0[0], theta1_pt-line_length*df0[1]), arrowprops={'arrowstyle': '->', 'lw': 2}, va='center', ha='center') plt.scatter(theta0_pts, theta1_pts) plt.clabel(contours) plt.xlabel('Theta0') plt.ylabel('Theta1') plt.title('Gradients of the quadratic function') plt.axis('equal') # + [markdown] slideshow={"slide_type": "slide"} # <left><img width=25% src="https://cornell-machine-learning.github.io/aml-images/img/cornell_tech2.svg"></left> # # Part 1b: Gradient Descent # # Next, we will use gradients to define an important algorithm called *gradient descent*. # + [markdown] slideshow={"slide_type": "slide"} # # Calculus Review: The Gradient # # The gradient $\nabla_\theta f$ further extends the derivative to multivariate functions $f : \mathbb{R}^d \to \mathbb{R}$, and is defined at a point $\theta_0$ as # # $$ \nabla_\theta f (\theta_0) = \begin{bmatrix} # \frac{\partial f(\theta_0)}{\partial \theta_1} \\ # \frac{\partial f(\theta_0)}{\partial \theta_2} \\ # \vdots \\ # \frac{\partial f(\theta_0)}{\partial \theta_d} # \end{bmatrix}.$$ # # The $j$-th entry of the vector $\nabla_\theta f (\theta_0)$ is the partial derivative $\frac{\partial f(\theta_0)}{\partial \theta_j}$ of $f$ with respect to the $j$-th component of $\theta$. # + slideshow={"slide_type": "subslide"} theta0_pts, theta1_pts = np.array([2.3, -1.35, -2.3]), np.array([2.4, -0.15, 2.75]) dfs = quadratic_derivative2d(theta0_pts, theta1_pts) line_length = 0.2 contours = plt.contour(X, Y, J_grid, 10) for theta0_pt, theta1_pt, df0 in zip(theta0_pts, theta1_pts, dfs): plt.annotate('', xytext=(theta0_pt, theta1_pt), xy=(theta0_pt-line_length*df0[0], theta1_pt-line_length*df0[1]), arrowprops={'arrowstyle': '->', 'lw': 2}, va='center', ha='center') plt.scatter(theta0_pts, theta1_pts) plt.clabel(contours) plt.xlabel('Theta0') plt.ylabel('Theta1') plt.title('Gradients of the quadratic function') plt.axis('equal') # + [markdown] slideshow={"slide_type": "slide"} # # Gradient Descent: Intuition # # Gradient descent is a very common optimization algorithm used in machine learning. # # The intuition behind gradient descent is to repeatedly obtain the gradient to determine the direction in which the function decreases most steeply and take a step in that direction. # + [markdown] slideshow={"slide_type": "slide"} # # Gradient Descent: Notation # More formally, if we want to optimize $J(\theta)$, we start with an initial guess $\theta_0$ for the parameters and repeat the following update until $\theta$ is no longer changing: # $$ \theta_i := \theta_{i-1} - \alpha \cdot \nabla_\theta J(\theta_{i-1}). $$ # # As code, this method may look as follows: # ```python # theta, theta_prev = random_initialization() # while norm(theta - theta_prev) > convergence_threshold: # theta_prev = theta # theta = theta_prev - step_size * gradient(theta_prev) # ``` # In the above algorithm, we stop when $||\theta_i - \theta_{i-1}||$ is small. # + [markdown] slideshow={"slide_type": "subslide"} # It's easy to implement this function in numpy. # + slideshow={"slide_type": "fragment"} convergence_threshold = 2e-1 step_size = 2e-1 theta, theta_prev = np.array([[-2], [3]]), np.array([[0], [0]]) opt_pts = [theta.flatten()] opt_grads = [] while np.linalg.norm(theta - theta_prev) > convergence_threshold: # we repeat this while the value of the function is decreasing theta_prev = theta gradient = quadratic_derivative2d(*theta).reshape([2,1]) theta = theta_prev - step_size * gradient opt_pts += [theta.flatten()] opt_grads += [gradient.flatten()] # + [markdown] slideshow={"slide_type": "slide"} # We can now visualize gradient descent. # + slideshow={"slide_type": "-"} opt_pts = np.array(opt_pts) opt_grads = np.array(opt_grads) contours = plt.contour(X, Y, J_grid, 10) plt.clabel(contours) plt.scatter(opt_pts[:,0], opt_pts[:,1]) for opt_pt, opt_grad in zip(opt_pts, opt_grads): plt.annotate('', xytext=(opt_pt[0], opt_pt[1]), xy=(opt_pt[0]-0.8*step_size*opt_grad[0], opt_pt[1]-0.8*step_size*opt_grad[1]), arrowprops={'arrowstyle': '->', 'lw': 2}, va='center', ha='center') plt.axis('equal') # + [markdown] slideshow={"slide_type": "slide"} # <left><img width=25% src="https://cornell-machine-learning.github.io/aml-images/img/cornell_tech2.svg"></left> # # Part 2: Gradient Descent in Linear Models # # Let's now use gradient descent to derive a supervised learning algorithm for linear models. # + [markdown] slideshow={"slide_type": "slide"} # # Review: Gradient Descent # If we want to optimize $J(\theta)$, we start with an initial guess $\theta_0$ for the parameters and repeat the following update: # $$ \theta_i := \theta_{i-1} - \alpha \cdot \nabla_\theta J(\theta_{i-1}). $$ # # As code, this method may look as follows: # ```python # theta, theta_prev = random_initialization() # while norm(theta - theta_prev) > convergence_threshold: # theta_prev = theta # theta = theta_prev - step_size * gradient(theta_prev) # ``` # + [markdown] slideshow={"slide_type": "slide"} # # Review: Linear Model Family # # Recall that a linear model has the form # \begin{align*} # y & = \theta_0 + \theta_1 \cdot x_1 + \theta_2 \cdot x_2 + ... + \theta_d \cdot x_d # \end{align*} # where $x \in \mathbb{R}^d$ is a vector of features and $y$ is the target. The $\theta_j$ are the *parameters* of the model. # # By using the notation $x_0 = 1$, we can represent the model in a vectorized form # $$ f_\theta(x) = \sum_{j=0}^d \theta_j \cdot x_j = \theta^\top x. $$ # + [markdown] slideshow={"slide_type": "subslide"} # Let's define our model in Python. # + slideshow={"slide_type": "-"} def f(X, theta): """The linear model we are trying to fit. Parameters: theta (np.array): d-dimensional vector of parameters X (np.array): (n,d)-dimensional data matrix Returns: y_pred (np.array): n-dimensional vector of predicted targets """ return X.dot(theta) # + [markdown] slideshow={"slide_type": "slide"} # # An Objective: Mean Squared Error # # We pick $\theta$ to minimize the mean squared error (MSE). Slight variants of this objective are also known as the residual sum of squares (RSS) or the sum of squared residuals (SSR). # $$J(\theta)= \frac{1}{2n} \sum_{i=1}^n(y^{(i)}-\theta^\top x^{(i)})^2$$ # In other words, we are looking for the best compromise in $\theta$ over all the data points. # + [markdown] slideshow={"slide_type": "subslide"} # Let's implement mean squared error. # + slideshow={"slide_type": "-"} def mean_squared_error(theta, X, y): """The cost function, J, describing the goodness of fit. Parameters: theta (np.array): d-dimensional vector of parameters X (np.array): (n,d)-dimensional design matrix y (np.array): n-dimensional vector of targets """ return 0.5*np.mean((y-f(X, theta))**2) # + [markdown] slideshow={"slide_type": "slide"} # # Mean Squared Error: Partial Derivatives # # Let's work out what a partial derivative is for the MSE error loss for a linear model. # # \begin{align*} # \frac{\partial J(\theta)}{\partial \theta_j} & = \frac{\partial}{\partial \theta_j} \frac{1}{2} \left( f_\theta(x) - y \right)^2 \\ # & = \left( f_\theta(x) - y \right) \cdot \frac{\partial}{\partial \theta_j} \left( f_\theta(x) - y \right) \\ # & = \left( f_\theta(x) - y \right) \cdot \frac{\partial}{\partial \theta_j} \left( \sum_{k=0}^d \theta_k \cdot x_k - y \right) \\ # & = \left( f_\theta(x) - y \right) \cdot x_j # \end{align*} # + [markdown] slideshow={"slide_type": "slide"} # # Mean Squared Error: The Gradient # # We can use this derivation to obtain an expression for the gradient of the MSE for a linear model # \begin{align*} # \nabla_\theta J (\theta) = \begin{bmatrix} # \frac{\partial f(\theta)}{\partial \theta_1} \\ # \frac{\partial f(\theta)}{\partial \theta_2} \\ # \vdots \\ # \frac{\partial f(\theta)}{\partial \theta_d} # \end{bmatrix} # = # \begin{bmatrix} # \left( f_\theta(x) - y \right) \cdot x_1 \\ # \left( f_\theta(x) - y \right) \cdot x_2 \\ # \vdots \\ # \left( f_\theta(x) - y \right) \cdot x_d # \end{bmatrix} # = # \left( f_\theta(x) - y \right) \cdot \bf{x} # . # \end{align*} # + [markdown] slideshow={"slide_type": "subslide"} # Let's implement the gradient. # + slideshow={"slide_type": "-"} def mse_gradient(theta, X, y): """The gradient of the cost function. Parameters: theta (np.array): d-dimensional vector of parameters X (np.array): (n,d)-dimensional design matrix y (np.array): n-dimensional vector of targets Returns: grad (np.array): d-dimensional gradient of the MSE """ return np.mean((f(X, theta) - y) * X.T, axis=1) # + [markdown] slideshow={"slide_type": "slide"} # # The UCI Diabetes Dataset # # In this section, we are going to again use the UCI Diabetes Dataset. # * For each patient we have a access to a measurement of their body mass index (BMI) and a quantiative diabetes risk score (from 0-300). # * We are interested in understanding how BMI affects an individual's diabetes risk. # + slideshow={"slide_type": "subslide"} # %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [8, 4] import numpy as np import pandas as pd from sklearn import datasets # Load the diabetes dataset X, y = datasets.load_diabetes(return_X_y=True, as_frame=True) # add an extra column of onens X['one'] = 1 # Collect 20 data points and only use bmi dimension X_train = X.iloc[-20:].loc[:, ['bmi', 'one']] y_train = y.iloc[-20:] / 300 plt.scatter(X_train.loc[:,['bmi']], y_train, color='black') plt.xlabel('Body Mass Index (BMI)') plt.ylabel('Diabetes Risk') # + [markdown] slideshow={"slide_type": "slide"} # # Gradient Descent for Linear Regression # # Putting this together with the gradient descent algorithm, we obtain a learning method for training linear models. # # # ```python # theta, theta_prev = random_initialization() # while abs(J(theta) - J(theta_prev)) > conv_threshold: # theta_prev = theta # theta = theta_prev - step_size * (f(x, theta)-y) * x # ``` # # This update rule is also known as the Least Mean Squares (LMS) or Widrow-Hoff learning rule. # + slideshow={"slide_type": "subslide"} threshold = 1e-3 step_size = 4e-1 theta, theta_prev = np.array([2,1]), np.ones(2,) opt_pts = [theta] opt_grads = [] iter = 0 while np.linalg.norm(theta - theta_prev) > threshold: if iter % 100 == 0: print('Iteration %d. MSE: %.6f' % (iter, mean_squared_error(theta, X_train, y_train))) theta_prev = theta gradient = mse_gradient(theta, X_train, y_train) theta = theta_prev - step_size * gradient opt_pts += [theta] opt_grads += [gradient] iter += 1 # + slideshow={"slide_type": "subslide"} x_line = np.stack([np.linspace(-0.1, 0.1, 10), np.ones(10,)]) y_line = opt_pts[-1].dot(x_line) plt.scatter(X_train.loc[:,['bmi']], y_train, color='black') plt.plot(x_line[0], y_line) plt.xlabel('Body Mass Index (BMI)') plt.ylabel('Diabetes Risk') # + [markdown] slideshow={"slide_type": "slide"} # <left><img width=25% src="https://cornell-machine-learning.github.io/aml-images/img/cornell_tech2.svg"></left> # # Part 3: Ordinary Least Squares # # In practice, there is a more effective way than gradient descent to find linear model parameters. # # We will see this method here, which will lead to our first non-toy algorithm: Ordinary Least Squares. # + [markdown] slideshow={"slide_type": "slide"} # # Review: The Gradient # # The gradient $\nabla_\theta f$ further extends the derivative to multivariate functions $f : \mathbb{R}^d \to \mathbb{R}$, and is defined at a point $\theta_0$ as # # $$ \nabla_\theta f (\theta_0) = \begin{bmatrix} # \frac{\partial f(\theta_0)}{\partial \theta_1} \\ # \frac{\partial f(\theta_0)}{\partial \theta_2} \\ # \vdots \\ # \frac{\partial f(\theta_0)}{\partial \theta_d} # \end{bmatrix}.$$ # # In other words, the $j$-th entry of the vector $\nabla_\theta f (\theta_0)$ is the partial derivative $\frac{\partial f(\theta_0)}{\partial \theta_j}$ of $f$ with respect to the $j$-th component of $\theta$. # + [markdown] slideshow={"slide_type": "slide"} # # The UCI Diabetes Dataset # # In this section, we are going to again use the UCI Diabetes Dataset. # * For each patient we have a access to a measurement of their body mass index (BMI) and a quantiative diabetes risk score (from 0-300). # * We are interested in understanding how BMI affects an individual's diabetes risk. # + slideshow={"slide_type": "subslide"} # %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [8, 4] import numpy as np import pandas as pd from sklearn import datasets # Load the diabetes dataset X, y = datasets.load_diabetes(return_X_y=True, as_frame=True) # add an extra column of onens X['one'] = 1 # Collect 20 data points X_train = X.iloc[-20:] y_train = y.iloc[-20:] plt.scatter(X_train.loc[:,['bmi']], y_train, color='black') plt.xlabel('Body Mass Index (BMI)') plt.ylabel('Diabetes Risk') # + [markdown] slideshow={"slide_type": "slide"} # # Notation: Design Matrix # # <!-- Suppose that we have a dataset of size $n$ (e.g., $n$ patients), indexed by $i=1,2,...,n$. Each $x^{(i)}$ is a vector of $d$ features. --> # # Machine learning algorithms are most easily defined in the language of linear algebra. Therefore, it will be useful to represent the entire dataset as one matrix $X \in \mathbb{R}^{n \times d}$, of the form: # $$ X = \begin{bmatrix} # x^{(1)}_1 & x^{(1)}_2 & \ldots & x^{(1)}_d \\ # x^{(2)}_1 & x^{(2)}_2 & \ldots & x^{(2)}_d \\ # \vdots \\ # x^{(n)}_1 & x^{(n)}_2 & \ldots & x^{(n)}_d # \end{bmatrix} # = # \begin{bmatrix} # - & (x^{(1)})^\top & - \\ # - & (x^{(2)})^\top & - \\ # & \vdots & \\ # - & (x^{(n)})^\top & - \\ # \end{bmatrix} # .$$ # + [markdown] slideshow={"slide_type": "subslide"} # We can view the design matrix for the diabetes dataset. # + slideshow={"slide_type": "fragment"} X_train.head() # + [markdown] slideshow={"slide_type": "slide"} # # Notation: Design Matrix # # # Similarly, we can vectorize the target variables into a vector $y \in \mathbb{R}^n$ of the form # $$ y = \begin{bmatrix} # y^{(1)} \\ # y^{(2)} \\ # \vdots \\ # y^{(n)} # \end{bmatrix}.$$ # + [markdown] slideshow={"slide_type": "slide"} # # Squared Error in Matrix Form # # Recall that we may fit a linear model by choosing $\theta$ that minimizes the squared error: # $$J(\theta)=\frac{1}{2}\sum_{i=1}^n(y^{(i)}-\theta^\top x^{(i)})^2$$ # In other words, we are looking for the best compromise in $\beta$ over all the data points. # + [markdown] slideshow={"slide_type": "fragment"} # We can write this sum in matrix-vector form as: # $$J(\theta) = \frac{1}{2} (y-X\theta)^\top(y-X\theta) = \frac{1}{2} \|y-X\theta\|^2,$$ # where $X$ is the design matrix and $\|\cdot\|$ denotes the Euclidean norm. # + [markdown] slideshow={"slide_type": "slide"} # # The Gradient of the Squared Error # # We can a gradient for the mean squared error as follows. # # \begin{align*} # \nabla_\theta J(\theta) # & = \nabla_\theta \frac{1}{2} (X \theta - y)^\top (X \theta - y) \\ # & = \frac{1}{2} \nabla_\theta \left( (X \theta)^\top (X \theta) - (X \theta)^\top y - y^\top (X \theta) + y^\top y \right) \\ # & = \frac{1}{2} \nabla_\theta \left( \theta^\top (X^\top X) \theta - 2(X \theta)^\top y \right) \\ # & = \frac{1}{2} \left( 2(X^\top X) \theta - 2X^\top y \right) \\ # & = (X^\top X) \theta - X^\top y # \end{align*} # # We used the facts that $a^\top b = b^\top a$ (line 3), that $\nabla_x b^\top x = b$ (line 4), and that $\nabla_x x^\top A x = 2 A x$ for a symmetric matrix $A$ (line 4). # + [markdown] slideshow={"slide_type": "slide"} # # Normal Equations # # <!-- We know from calculus that a function is minimized when its derivative is set to zero. In our case, our objective function is a (multivariate) quadratic; hence it only has one minimum, which is the global minimum. # --> # Setting the above derivative to zero, we obtain the *normal equations*: # $$ (X^\top X) \theta = X^\top y.$$ # # Hence, the value $\theta^*$ that minimizes this objective is given by: # $$ \theta^* = (X^\top X)^{-1} X^\top y.$$ # + [markdown] slideshow={"slide_type": "fragment"} # Note that we assumed that the matrix $(X^\top X)$ is invertible; if this is not the case, there are easy ways of addressing this issue. # + [markdown] slideshow={"slide_type": "subslide"} # Let's apply the normal equations. # + slideshow={"slide_type": "fragment"} import numpy as np theta_best = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train) theta_best_df = pd.DataFrame(data=theta_best[np.newaxis, :], columns=X.columns) theta_best_df # + [markdown] slideshow={"slide_type": "subslide"} # We can now use our estimate of theta to compute predictions for 3 new data points. # + slideshow={"slide_type": "-"} # Collect 3 data points for testing X_test = X.iloc[:3] y_test = y.iloc[:3] # generate predictions on the new patients y_test_pred = X_test.dot(theta_best) # + [markdown] slideshow={"slide_type": "subslide"} # Let's visualize these predictions. # - # visualize the results plt.xlabel('Body Mass Index (BMI)') plt.ylabel('Diabetes Risk') plt.scatter(X_train.loc[:, ['bmi']], y_train) plt.scatter(X_test.loc[:, ['bmi']], y_test, color='red', marker='o') plt.plot(X_test.loc[:, ['bmi']], y_test_pred, 'x', color='red', mew=3, markersize=8) plt.legend(['Model', 'Prediction', 'Initial patients', 'New patients']) # + [markdown] slideshow={"slide_type": "slide"} # # Algorithm: Ordinary Least Squares # # * __Type__: Supervised learning (regression) # * __Model family__: Linear models # * __Objective function__: Mean squared error # * __Optimizer__: Normal equations # + [markdown] slideshow={"slide_type": "slide"} # <left><img width=25% src="https://cornell-machine-learning.github.io/aml-images/img/cornell_tech2.svg"></left> # # Part 4: Non-Linear Least Squares # # So far, we have learned about a very simple linear model. These can capture only simple linear relationships in the data. How can we use what we learned so far to model more complex relationships? # # We will now see a simple approach to model complex non-linear relationships called *least squares*. # + [markdown] slideshow={"slide_type": "slide"} # # Review: Polynomial Functions # # Recall that a polynomial of degree $p$ is a function of the form # $$ # a_p x^p + a_{p-1} x^{p-1} + ... + a_{1} x + a_0. # $$ # # Below are some examples of polynomial functions. # + slideshow={"slide_type": "subslide"} import warnings warnings.filterwarnings("ignore") plt.figure(figsize=(16,4)) x_vars = np.linspace(-2, 2) plt.subplot('131') plt.title('Quadratic Function') plt.plot(x_vars, x_vars**2) plt.legend(["$x^2$"]) plt.subplot('132') plt.title('Cubic Function') plt.plot(x_vars, x_vars**3) plt.legend(["$x^3$"]) plt.subplot('133') plt.title('Third Degree Polynomial') plt.plot(x_vars, x_vars**3 + 2*x_vars**2 + x_vars + 1) plt.legend(["$x^3 + 2 x^2 + x + 1$"]) # + [markdown] slideshow={"slide_type": "slide"} # # Modeling Non-Linear Relationships With Polynomial Regression # # <!-- Note that the set of $p$-th degree polynomials forms a linear model with parameters $a_p, a_{p-1}, ..., a_0$. # This means we can use our algorithms for linear models to learn non-linear features! --> # # Specifically, given a one-dimensional continuous variable $x$, we can defining a feature function $\phi : \mathbb{R} \to \mathbb{R}^{p+1}$ as # $$ \phi(x) = \begin{bmatrix} # 1 \\ # x \\ # x^2 \\ # \vdots \\ # x^p # \end{bmatrix}. # $$ # + [markdown] slideshow={"slide_type": "subslide"} # The class of models of the form # $$ f_\theta(x) := \sum_{j=0}^p \theta_p x^p = \theta^\top \phi(x) $$ # with parameters $\theta$ and polynomial features $\phi$ is the set of $p$-degree polynomials. # + [markdown] slideshow={"slide_type": "fragment"} # * This model is non-linear in the input variable $x$, meaning that we can model complex data relationships. # + [markdown] slideshow={"slide_type": "fragment"} # * It is a linear model as a function of the parameters $\theta$, meaning that we can use our familiar ordinary least squares algorithm to learn these features. # + [markdown] slideshow={"slide_type": "slide"} # # The UCI Diabetes Dataset # # In this section, we are going to again use the UCI Diabetes Dataset. # * For each patient we have a access to a measurement of their body mass index (BMI) and a quantiative diabetes risk score (from 0-300). # * We are interested in understanding how BMI affects an individual's diabetes risk. # + slideshow={"slide_type": "subslide"} # %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [8, 4] import numpy as np import pandas as pd from sklearn import datasets # Load the diabetes dataset X, y = datasets.load_diabetes(return_X_y=True, as_frame=True) # add an extra column of onens X['one'] = 1 # Collect 20 data points X_train = X.iloc[-20:] y_train = y.iloc[-20:] plt.scatter(X_train.loc[:,['bmi']], y_train, color='black') plt.xlabel('Body Mass Index (BMI)') plt.ylabel('Diabetes Risk') # + [markdown] slideshow={"slide_type": "slide"} # # Diabetes Dataset: A Non-Linear Featurization # # Let's now obtain linear features for this dataset. # + slideshow={"slide_type": "-"} X_bmi = X_train.loc[:, ['bmi']] X_bmi_p3 = pd.concat([X_bmi, X_bmi**2, X_bmi**3], axis=1) X_bmi_p3.columns = ['bmi', 'bmi2', 'bmi3'] X_bmi_p3['one'] = 1 X_bmi_p3.head() # + [markdown] slideshow={"slide_type": "slide"} # # Diabetes Dataset: A Polynomial Model # # By training a linear model on this featurization of the diabetes set, we can obtain a polynomial model of diabetest risk as a function of BMI. # + slideshow={"slide_type": "subslide"} # Fit a linear regression theta = np.linalg.inv(X_bmi_p3.T.dot(X_bmi_p3)).dot(X_bmi_p3.T).dot(y_train) # Show the learned polynomial curve x_line = np.linspace(-0.1, 0.1, 10) x_line_p3 = np.stack([x_line, x_line**2, x_line**3, np.ones(10,)], axis=1) y_train_pred = x_line_p3.dot(theta) plt.xlabel('Body Mass Index (BMI)') plt.ylabel('Diabetes Risk') plt.scatter(X_bmi, y_train) plt.plot(x_line, y_train_pred) # + [markdown] slideshow={"slide_type": "slide"} # # Multivariate Polynomial Regression # # We can also take this approach to construct non-linear function of multiples variable by using multivariate polynomials. # # For example, a polynomial of degree $2$ over two variables $x_1, x_2$ is a function of the form # <!-- $$ # a_{20} x_1^2 + a_{10} x_1 + a_{02} x_2^2 + a_{01} x_2 + a_{22} x_1^2 x_2^2 + a_{21} x_1^2 x_2 + a_{12} x_1 x_2^2 + a_11 x_1 x_2 + a_{00}. # $$ --> # $$ # a_{20} x_1^2 + a_{10} x_1 + a_{02} x_2^2 + a_{01} x_2 + a_{11} x_1 x_2 + a_{00}. # $$ # + [markdown] slideshow={"slide_type": "fragment"} # In general, a polynomial of degree $p$ over two variables $x_1, x_2$ is a function of the form # $$ # f(x_1, x_2) = \sum_{i,j \geq 0 : i+j \leq p} a_{ij} x_1^i x_2^j. # $$ # + [markdown] slideshow={"slide_type": "subslide"} # In our two-dimensional example, this corresponds to a feature function $\phi : \mathbb{R}^2 \to \mathbb{R}^6$ of the form # $$ \phi(x) = \begin{bmatrix} # 1 \\ # x_1 \\ # x_1^2 \\ # x_2 \\ # x_2^2 \\ # x_1 x_2 # \end{bmatrix}. # $$ # # The same approach holds for polynomials of an degree and any number of variables. # + [markdown] slideshow={"slide_type": "slide"} # # Towards General Non-Linear Features # # Any non-linear feature map $\phi(x) : \mathbb{R}^d \to \mathbb{R}^p$ can be used in this way to obtain general models of the form # $$ f_\theta(x) := \theta^\top \phi(x) $$ # that are highly non-linear in $x$ but linear in $\theta$. # + [markdown] slideshow={"slide_type": "subslide"} # For example, here is a way of modeling complex periodic functions via a sum of sines and cosines. # + slideshow={"slide_type": "fragment"} import warnings warnings.filterwarnings("ignore") plt.figure(figsize=(16,4)) x_vars = np.linspace(-5, 5) plt.subplot('131') plt.title('Cosine Function') plt.plot(x_vars, np.cos(x_vars)) plt.legend(["$cos(x)$"]) plt.subplot('132') plt.title('Sine Function') plt.plot(x_vars, np.sin(2*x_vars)) plt.legend(["$x^3$"]) plt.subplot('133') plt.title('Combination of Sines and Cosines') plt.plot(x_vars, np.cos(x_vars) + np.sin(2*x_vars) + np.cos(4*x_vars)) plt.legend(["$cos(x) + sin(2x) + cos(4x)$"]) # + [markdown] slideshow={"slide_type": "slide"} # # Algorithm: Non-Linear Least Squares # # * __Type__: Supervised learning (regression) # * __Model family__: Linear in the parameters; non-linear with respect to raw inputs. # * __Features__: Non-linear functions of the attributes # * __Objective function__: Mean squared error # * __Optimizer__: Normal equations # -
_site/notes/notes_ipynb/lecture3-linear-regression.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 # --- # + # original : http://www.voidcn.com/blog/u014365862/article/p-6355756.html import tensorflow as tf import numpy as np import nltk import random import pickle from collections import Counter import nltk from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer """ 词形还原(lemmatizer),即把一个任何形式的英语单词还原到一般形式,与词根还原不同(stemmer),后者是抽取一个单词的词根。 """ # - # 创建词汇表 pos_file = "./data/p1/pos.txt" neg_file = "./data/p1/neg.txt" def create_lexicon(pos_file, neg_file, upper=0.9, lower=0.0001): # TODO 如何选择这里的lower和upper? lex = [] # 读取文件 def process_file(f): with open(pos_file, 'r') as f: lex = [] lines = f.readlines() for line in lines: try: words = word_tokenize(line.lower()) lex += words except Exception: continue return lex def is_ascii(s): return all(ord(c) < 128 for c in s) lex += process_file(pos_file) lex += process_file(neg_file) # lex 包含了两个文件中所有的词汇 lemmatizer = WordNetLemmatizer() lex = [lemmatizer.lemmatize(word) for word in lex if is_ascii(word)] # 词形还原 (cats->cat) word_count = Counter(lex) # {'.': 13944, ',': 10536, 'the': 10120, 'a': 9444, 'and': 7108, 'of': 6624, 'it': 4748, 'to': 3940......} # 去掉一些常用词,像the,a and等等,和一些不常用词; 这些词对判断一个评论是正面还是负面没有做任何贡献 ret = [] for word in word_count: if word_count[word] < len(lex) * upper and word_count[word] > len(lex) * lower: # 这写死了,好像能用百分比 ret.append(word) # 齐普夫定律-使用Python验证文本的Zipf分布 http://blog.topspeedsnail.com/archives/9546 return ret res = create_lexicon(pos_file, neg_file) len(res) # + # 把每条评论转换为向量, 转换原理: # 假设lex为['woman', 'great', 'feel', 'actually', 'looking', 'latest', 'seen', 'is'] 当然实际上要大的多 # 评论'i think this movie is great' 转换为 [0,1,0,0,0,0,0,1], 把评论中出现的字在lex中标记,出现过的标记为1,其余标记为0 def normalize_dataset(lex): dataset = [] # lex:词汇表;review:评论;clf:评论对应的分类,[0,1]代表负面评论 [1,0]代表正面评论 def string_to_vector(lex, review, clf): words = word_tokenize(line.lower()) lemmatizer = WordNetLemmatizer() words = [lemmatizer.lemmatize(word) for word in words] features = np.zeros(len(lex)) for word in words: if word in lex: features[lex.index(word)] = 1 # 一个句子中某个词可能出现两次,可以用+=1,其实区别不大 return [features, clf] with open(pos_file, 'r') as f: lines = f.readlines() for line in lines: try: one_sample = string_to_vector(lex, line, [1,0]) # [array([ 0., 1., 0., ..., 0., 0., 0.]), [1,0]] dataset.append(one_sample) except Exception: continue with open(neg_file, 'r') as f: lines = f.readlines() for line in lines: try: one_sample = string_to_vector(lex, line, [0,1]) # [array([ 0., 0., 0., ..., 0., 0., 0.]), [0,1]]] dataset.append(one_sample) except Exception: continue #print(len(dataset)) return dataset dataset = normalize_dataset(res) random.shuffle(dataset) # - #把整理好的数据保存到文件,方便使用。到此完成了数据的整理工作 with open('./data/p1/save.pickle', 'wb') as f: pickle.dump(dataset, f) # + # 取样本中的10%做为测试数据 test_size = int(len(dataset) * 0.1) dataset = np.array(dataset) train_dataset = dataset[:-test_size] test_dataset = dataset[-test_size:] # Feed-Forward Neural Network # 定义每个层有多少'神经元'' n_input_layer = len(res) # 输入层 n_layer_1 = 1024 # hiden layer n_layer_2 = 512 # hiden layer(隐藏层)听着很神秘,其实就是除输入输出层外的中间层 n_layer_3 = 256 # hiden layer n_output_layer = 2 # 输出层 # - # 定义待训练的神经网络 def neural_network(data): # 定义第一层"神经元"的权重和biases layer_1_w_b = {'w_':tf.Variable(tf.random_normal([n_input_layer, n_layer_1])), 'b_':tf.Variable(tf.random_normal([n_layer_1]))} # 定义第二层"神经元"的权重和biases layer_2_w_b = {'w_':tf.Variable(tf.random_normal([n_layer_1, n_layer_2])), 'b_':tf.Variable(tf.random_normal([n_layer_2]))} # 定义输出层"神经元"的权重和biases layer_3_w_b = {'w_':tf.Variable(tf.random_normal([n_layer_2, n_layer_3])), 'b_':tf.Variable(tf.random_normal([n_layer_3]))} # 定义输出层"神经元"的权重和biases layer_output_w_b = {'w_':tf.Variable(tf.random_normal([n_layer_3, n_output_layer])), 'b_':tf.Variable(tf.random_normal([n_output_layer]))} # w·x+b # data n*1006, layer1 1006*1000, layer2 1000*1000, output, 1000*2 layer_1 = tf.add(tf.matmul(data, layer_1_w_b['w_']), layer_1_w_b['b_']) layer_1 = tf.nn.relu(layer_1) # 激活函数 layer_2 = tf.add(tf.matmul(layer_1, layer_2_w_b['w_']), layer_2_w_b['b_']) layer_2 = tf.nn.relu(layer_2 ) # 激活函数 layer_3 = tf.add(tf.matmul(layer_2, layer_3_w_b['w_']), layer_3_w_b['b_']) layer_3 = tf.nn.relu(layer_3 ) # 激活函数 layer_output = tf.add(tf.matmul(layer_3, layer_output_w_b['w_']), layer_output_w_b['b_']) return layer_output # + # 每次使用128条数据进行训练 batch_size = 64 X = tf.placeholder('float', [None, len(train_dataset[0][0])]) #[None, len(train_x)]代表数据数据的高和宽(矩阵),好处是如果数据不符合宽高,tensorflow会报错,不指定也可以。 Y = tf.placeholder('float') # + # 使用数据训练神经网络 def train_neural_network(X, Y): predict = neural_network(X) cost_func = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(predict, Y)) optimizer = tf.train.AdamOptimizer().minimize(cost_func) # learning rate 默认 0.001 epochs = 20 with tf.Session() as session: session.run(tf.global_variables_initializer()) epoch_loss = 0 i = 0 random.shuffle(train_dataset) train_x = dataset[:, 0] train_y = dataset[:, 1] for epoch in range(epochs): while i < len(train_x): # create batch start = i end = i + batch_size batch_x = train_x[start:end] batch_y = train_y[start:end] _, c = session.run([optimizer, cost_func], feed_dict={X:list(batch_x),Y:list(batch_y)}) epoch_loss += c i += batch_size print(epoch, ' : ', epoch_loss) text_x = test_dataset[: ,0] text_y = test_dataset[:, 1] correct = tf.equal(tf.argmax(predict,1), tf.argmax(Y,1)) accuracy = tf.reduce_mean(tf.cast(correct,'float')) print('Accuracy: ', accuracy.eval({X:list(text_x) , Y:list(text_y)})) train_neural_network(X,Y) # -
tf_practice/1_classify_the_reviews.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: pyspark (Spark 1.4.0) # language: python # name: pyspark-kernel # --- # <img src='https://www.rc.colorado.edu/sites/all/themes/research/logo.png' style="height:75px"> # # Simple Spark wordcount example # # Adapted from example in spark distribution sc from __future__ import print_function from operator import add # + run_control={"marked": true} lines = sc.textFile("Data/Beowulf.txt", 1) # - counts = lines.flatMap(lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add) output = counts.collect() for (word, count) in output: print("%s: %i" % (word, count))
07-spark-example.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 # --- # Install pip packages in the current Jupyter kernel # https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/ # import sys # # !{sys.executable} -m pip install selenium # # !{sys.executable} -m pip install pandas # # !{sys.executable} -m pip install xlml # # !{sys.executable} -m pip install reportlab # Import necessary modules #import modules from selenium import webdriver import pandas as pd from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.lib.units import cm from datetime import datetime # First step is going to the electronic patient file with a web application. We are gonna use selenium and chrome for that. We first a webbrowser with selenium and go to the right page. driver = webdriver.Chrome() driver.get("https://medicalprogress.dev/patient_file/") # Next we are gonna download the html code and read the table with pandas read_html function html = driver.page_source data = pd.read_html(html) #needs lxml to work, make first row the header # Close the browser driver.close() # We have to clean the data a little bit to make it into a dataframe (list->first item list (table)-> pandas dataframe) data = data[0] df = pd.DataFrame(data) # Make a list of variables from the dataframe for printing on pdf name = df.iloc[0,1] first_name = df.iloc[1,1] gender = df.iloc[2,1] birthdate = df.iloc[3,1] birth_date_place = df.iloc[4,1] location = df.iloc[5,1] address = df.iloc[6,1] postal_code = df.iloc[7,1] place = df.iloc[5,1] # Create variables with you personal information MD = "K.H.Kramp" specialty = "Specialty" # Create a marking variable for the answers on the pdf answer = "x" # Get time of death time_value = input("what is the time of death?") # Create a canvas for writing on with the file name "deat_certificate.pdf" canvas = canvas.Canvas path_pdf = "death_certificate.pdf" c = canvas(path_pdf) # Create a background variable with first page of decleration form and draw it on the canvas (try to open de file as a check to see if you get the first page of the death decleration form) background = "https://medicalprogress.dev/patient_file/Form_B1.jpg" draw_width, draw_height = A4 c.drawImage(background, 0, 0, width=draw_width, height=draw_height) # Write text on form B1 c.drawString(1.9 * cm, 25.7 * cm, place) c.drawString(1.9 * cm, 23.3 * cm, answer) c.drawString(1.9 * cm, 20.5 * cm, answer) if gender == "Male": c.drawString(1.9 * cm, 13.3 * cm, answer) else: c.drawString(1.9 * cm, 12.8 * cm, answer) c.drawString(1.9 * cm, 11.3 * cm, answer) birthdate_without_dash = birthdate.replace("-", " ") textobject = c.beginText(4.3 * cm, 10.3 * cm) textobject.setCharSpace(6.3) textobject.textLine(birthdate_without_dash) c.drawText(textobject) textobject = c.beginText(4.3 * cm, 9.0 * cm) textobject.setCharSpace(6.3) textobject.textLine(datetime.now().strftime("%d %m %Y")) c.drawText(textobject) # Go to next page c.showPage() # Write text on form B2 background = "https://medicalprogress.dev/patient_file/Form_B2.jpg" draw_width, draw_height = A4 c.drawImage(background, 0, 0, width=draw_width, height=draw_height) c.drawString(3.0 * cm, 12.6 * cm, MD) c.drawString(3.0 * cm, 11.9 * cm, location) c.drawString(3.0 * cm, 11.1 * cm, specialty) c.drawString(3.0 * cm, 10.4 * cm, address) c.drawString(6.0 * cm, 9.6 * cm, place) c.drawString(2.8 * cm, 7.0 * cm, answer) c.drawString(12.5 * cm, 12.6 * cm, "Specialist") c.drawString(12.5 * cm, 11.9 * cm, "See on the left") textobject = c.beginText(2.9 * cm, 9.6 * cm) textobject.setCharSpace(3.8) textobject.textLine(postal_code) c.drawText(textobject) c.drawString(11.5 * cm, 7.3 * cm, datetime.now().strftime("%d %m %y")) c.showPage() # Write text on form A background = "https://medicalprogress.dev/patient_file/Form_A.jpg" draw_width, draw_height = A4 c.drawImage(background, 0, 0, width=draw_width, height=draw_height) c.drawString(3.5 * cm, 22.9 * cm, MD) c.drawString(3.5 * cm, 21.8 * cm, place) c.drawString(5.3 * cm, 19.5 * cm, name) c.drawString(5.3 * cm, 18.4 * cm, first_name) c.drawString(7.3 * cm, 17.2 * cm, birthdate + " " + birth_date_place) c.drawString(7.3 * cm, 15.5 * cm, datetime.now().strftime("%d-%m-%Y")) c.drawString(10.3 * cm, 15.5 * cm, place) c.drawString(7.3 * cm, 14.4 * cm, time_value) c.drawString(3.5 * cm, 4.0 * cm, datetime.now().strftime("%d-%m-%Y")) # Save forms c.save()
Tutorial filling in death declaration.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 # --- # # Kerja Gaya Gesek # # Sparisoma Viridi<sup>1</sup>, Said Husain<sup>/2</sup> <br> # Program Studi Sarjana Fisika, Institut Teknologi Bandung <br> # Jalan Gensha 10, Bandung 40132, Indonesia <br> # <sup>1</sup><EMAIL>, https://github.com/dudung <br> # <sup>2</sup><EMAIL>, https://github.com/Supermieisidua # # Kerja yang dilakukan oleh gaya gesek merupakan bentuk kerja yang tidak diharapkan karena energi yang dikeluarkan, biasanya dalam bentuk panas atau bunyi yang dilepas ke lingkungan, tidak dapat dimanfaatkan lagi oleh sistem sehingga energi sistem berkurang. # ## Gerak benda di atas lantai mendatar kasar # Sistem yang ditinjau adalah suatu benda yang bergerak di atas lantai mendatar kasar. Benda diberi kecepatan awal tertentu dan bergerak melambat sampai berhenti karena adanya gaya gesek kinetis antara benda dan lantai kasar. # ## Parameter # Beberapa parameter yang digunakan adalah seperti pada tabel berikut ini. # # Tabel <a name='tab1'>1</a>. Simbol beserta satuan dan artinya. # # Simbol | Satuan | Arti # :- | :- | :- # $t$ | s | waktu # $v_0$ | m/s | kecepatan awal # $x_0$ | m | posisi awal # $v$ | m/s | kecepatan saat $t$ # $x$ | m | waktu saat $t$ # $a$ | m/s<sup>2</sup> | percepatan # $\mu_k$ | - | koefisien gesek kinetis # $f_k$ | N | gaya gesek kinetis # $m$ | kg | massa benda # $F$ | N | total gaya yang bekerja # $N$ | N | gaya normal # $w$ | N | gaya gravitasi # # Simbol-simbol pada Tabel [1](#tab1) akan diberi nilai kemudian saat diimplementasikan dalam program. # ## Persamaan # Persamaan-persamaan yang akan digunakan adalah seperti dicantumkan pada bagian ini. # ### Kinematika # Hubungan antara antara kecepatan $v$, kecepatan awal $v_0$, percepatan $a$, dan waktu $t$ diberikan oleh # # <a name='eqn1'></a> # \begin{equation}\label{eqn:kinematics-v-a-t}\tag{1} # v = v_0 + at. # \end{equation} # Posisi benda $x$ bergantung pada posisi awal $x_0$, kecepatan awal $v_0$, percepatan $a$, dan waktu $t$ melalui hubungan # # <a name='eqn2'></a> # \begin{equation}\label{eqn:kinematics-x-v-a-t}\tag{2} # x = x_0 + v_0 t + \tfrac12 at^2. # \end{equation} # # Selain kedua persamaan sebelumnya, terdapat pula persamaan berikut # # <a name='eqn3'></a> # \begin{equation}\label{eqn:kinematics-v-x-a}\tag{3} # v^2 = v_0^2 + 2a(x - x_0), # \end{equation} # # yang menghubungkan kecepatan $v$ dengan kecepatan awal $v_0$, percepatan $a$, dan jarak yang ditempuh $x - x_0$. # ### Dinamika # Hukum Newton I menyatakan bahwa benda yang semula diam akan tetap diam dan yang semula bergerak dengan kecepatan tetap akan tetap bergerak dengan kecepatan tetap bila tidak ada gaya yang bekerja pada benda atau jumlah gaya-gaya yang bekerja sama dengan nol # # <a name='eqn4'></a> # \begin{equation}\label{eqn:newtons-law-1}\tag{4} # \sum F = 0. # \end{equation} # Bila ada gaya yang bekerj pada benda bermassa $m$ atau jumlah gaya-gaya tidak nol # # <a name='eqn5'></a> # \begin{equation}\label{eqn:newtons-law-2}\tag{5} # \sum F = ma, # \end{equation} # # maka keadaan gerak benda akan berubah melalui percepatan $a$, dengan $m > 0$ dan $a \ne 0$. # ### Usaha # Usaha oleh suatu gaya $F$ dengan posisi awal $x_0$ dan posisi akhir $x_0$ dapat diperoleh melalui # # <a name='eqn6'></a> # \begin{equation}\label{eqn:work-1}\tag{6} # W = \int_{x_0}^x F dx # \end{equation} # # atau dengan # # <a name='eqn7'></a> # \begin{equation}\label{eqn:work-2}\tag{7} # W = \Delta K # \end{equation} # # dengan $K$ adalah energi kinetik. Persamaan ([7](#eqn7)) akan memberikan gaya oleh semua gaya. Dengan demikian bila $F$ adalah satu-satunya gaya yang bekerja pada benda, maka persamaan ini akan menjadi Persamaan ([6](#eqn6)). # ## Sistem # Ilustrasi sistem perlu diberikan agar dapat terbayangan dan memudahkan penyelesaian masalah. Selain itu juga perlu disajikan diagram gaya-gaya yang bekerja pada benda. # ### Ilustrasi # Sistem yang benda bermassa $m$ bergerak di atas lantai kasar dapat digambarkan # seperti berikut ini. # + tags=["hide_input"] language="html" # # <svg # width="320" # height="140" # viewBox="0 0 320 140.00001" # id="svg2" # version="1.1" # inkscape:version="1.1.2 (b8e25be833, 2022-02-05)" # sodipodi:docname="mass-horizontal-rough-surface.svg" # xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" # xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" # xmlns="http://www.w3.org/2000/svg" # xmlns:svg="http://www.w3.org/2000/svg" # xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" # xmlns:cc="http://creativecommons.org/ns#" # xmlns:dc="http://purl.org/dc/elements/1.1/"> # <defs # id="defs4"> # <marker # style="overflow:visible" # id="TriangleOutM" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479" /> # </marker> # <marker # style="overflow:visible" # id="marker11604" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="Arrow2Mend" # inkscape:isstock="true"> # <path # transform="scale(-0.6)" # d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:0.625;stroke-linejoin:round" # id="path11602" /> # </marker> # <marker # style="overflow:visible" # id="Arrow2Mend" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="Arrow2Mend" # inkscape:isstock="true"> # <path # transform="scale(-0.6)" # d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:0.625;stroke-linejoin:round" # id="path11361" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-3" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-1" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-35" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-0" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-0" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-4" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-37" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-9" /> # </marker> # </defs> # <sodipodi:namedview # id="base" # pagecolor="#ffffff" # bordercolor="#666666" # borderopacity="1.0" # inkscape:pageopacity="0.0" # inkscape:pageshadow="2" # inkscape:zoom="1.5" # inkscape:cx="173" # inkscape:cy="97.333333" # inkscape:document-units="px" # inkscape:current-layer="layer1" # showgrid="false" # inkscape:snap-bbox="false" # inkscape:snap-global="false" # units="px" # showborder="true" # inkscape:showpageshadow="true" # borderlayer="false" # inkscape:window-width="1366" # inkscape:window-height="705" # inkscape:window-x="-8" # inkscape:window-y="-8" # inkscape:window-maximized="1" # inkscape:pagecheckerboard="0"> # <inkscape:grid # type="xygrid" # id="grid970" /> # </sodipodi:namedview> # <metadata # id="metadata7"> # <rdf:RDF> # <cc:Work # rdf:about=""> # <dc:format>image/svg+xml</dc:format> # <dc:type # rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> # </cc:Work> # </rdf:RDF> # </metadata> # <g # inkscape:label="Layer 1" # inkscape:groupmode="layer" # id="layer1" # transform="translate(0,-732.36216)"> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="120.0725" # y="759.6109" # id="text2711-6-2-9"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2" # x="120.0725" # y="759.6109" # style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '"><tspan # style="font-style:italic" # id="tspan9923">v</tspan><tspan # style="font-size:65%;baseline-shift:sub" # id="tspan1668">0</tspan></tspan></text> # <path # style="fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM)" # d="m 84.656156,757.55169 25.738704,1.3e-4" # id="path11252" /> # <rect # style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:1;stroke-linecap:round;stroke-opacity:1" # id="rect1007" # width="59" # height="59" # x="56.5" # y="772.86218" # rx="0" # ry="0" /> # <path # style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" # d="m 20,832.86218 280,-2e-5" # id="path1386" /> # <rect # style="fill:#ffffff;fill-opacity:1;stroke:#c8c8c8;stroke-width:0.5;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:2, 2;stroke-dashoffset:0;stroke-opacity:1" # id="rect1007-2" # width="59" # height="59" # x="225.16667" # y="772.86218" # rx="0" # ry="0" /> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#c8c8c8;fill-opacity:1;stroke:none" # x="236.05922" # y="759.6109" # id="text2711-6-2-9-9"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-8" # x="236.05922" # y="759.6109" # style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, ';fill:#c8c8c8;fill-opacity:1"><tspan # style="font-style:italic;fill:#c8c8c8;fill-opacity:1" # id="tspan9923-8">v</tspan> = 0</tspan></text> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="149.18359" # y="824.54877" # id="text2711-6-2-9-96"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-6" # x="149.18359" # y="824.54877" # style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '"><tspan # style="font-style:italic" # id="tspan3028">μ<tspan # style="font-size:65%;baseline-shift:sub" # id="tspan3074">k</tspan></tspan> &gt; 0</tspan></text> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="79.505844" # y="806.37714" # id="text2711-6-2-9-2"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-84" # x="79.505844" # y="806.37714" # style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '">m</tspan></text> # <path # style="fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-37)" # d="m 33.785239,770.82609 -1.3e-4,25.7387" # id="path11252-5" /> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="29.173132" # y="759.45776" # id="text2711-6-2-9-8"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-2" # x="29.173132" # y="759.45776" # style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '">g</tspan></text> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="79.368446" # y="849.21539" # id="text2711-6-2-9-23"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-3" # x="79.368446" # y="849.21539" # style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '"><tspan # style="font-style:italic" # id="tspan9923-0">x</tspan><tspan # style="font-size:65%;baseline-shift:sub" # id="tspan1668-9">0</tspan></tspan></text> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="250.91145" # y="849.21539" # id="text2711-6-2-9-23-0"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-3-0" # x="250.91145" # y="849.21539" # style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '"><tspan # style="font-style:italic" # id="tspan9923-0-3">x</tspan><tspan # style="font-size:65%;baseline-shift:sub" # id="tspan1668-9-3" /></tspan></text> # </g> # </svg> # # <br/> # # Gambar <a name='fig1'>1</a>. Sistem benda bermassa $m$ begerak di atas lantai # mendatar kasar dengan koefisien gesek kinetis $\mu_k$. # - # Keadaan akhir benda, yaitu saat kecepatan $v = 0$ diberikan pada bagian kanan Gambar [1](#fig1) dengan warna abu-abu. # ### Diagram gaya # Diagram gaya-gaya yang berja pada benda perlu dibuat berdasarkan informasi dari Gambar [1](#fig1) dan Tabel [1](#tab1), yang diberikan berikut ini. # + language="html" # # <svg # width="320" # height="200" # viewBox="0 0 320 200.00001" # id="svg2" # version="1.1" # inkscape:version="1.1.2 (b8e25be833, 2022-02-05)" # sodipodi:docname="mass-horizontal-rough-surface-fbd.svg" # xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" # xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" # xmlns="http://www.w3.org/2000/svg" # xmlns:svg="http://www.w3.org/2000/svg" # xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" # xmlns:cc="http://creativecommons.org/ns#" # xmlns:dc="http://purl.org/dc/elements/1.1/"> # <defs # id="defs4"> # <marker # style="overflow:visible" # id="TriangleOutM" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479" /> # </marker> # <marker # style="overflow:visible" # id="marker11604" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="Arrow2Mend" # inkscape:isstock="true"> # <path # transform="scale(-0.6)" # d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:0.625;stroke-linejoin:round" # id="path11602" /> # </marker> # <marker # style="overflow:visible" # id="Arrow2Mend" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="Arrow2Mend" # inkscape:isstock="true"> # <path # transform="scale(-0.6)" # d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:0.625;stroke-linejoin:round" # id="path11361" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-3" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-1" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-35" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-0" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-0" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-4" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-37" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-9" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-9" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-8" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-9-3" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-8-3" /> # </marker> # <marker # style="overflow:visible" # id="TriangleOutM-37-5" # refX="0" # refY="0" # orient="auto" # inkscape:stockid="TriangleOutM" # inkscape:isstock="true"> # <path # transform="scale(0.4)" # style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" # d="M 5.77,0 -2.88,5 V -5 Z" # id="path11479-9-9" /> # </marker> # </defs> # <sodipodi:namedview # id="base" # pagecolor="#ffffff" # bordercolor="#666666" # borderopacity="1.0" # inkscape:pageopacity="0.0" # inkscape:pageshadow="2" # inkscape:zoom="1.2079428" # inkscape:cx="159.36185" # inkscape:cy="35.597712" # inkscape:document-units="px" # inkscape:current-layer="layer1" # showgrid="false" # inkscape:snap-bbox="false" # inkscape:snap-global="false" # units="px" # showborder="true" # inkscape:showpageshadow="true" # borderlayer="false" # inkscape:window-width="1366" # inkscape:window-height="705" # inkscape:window-x="-8" # inkscape:window-y="-8" # inkscape:window-maximized="1" # inkscape:pagecheckerboard="0"> # <inkscape:grid # type="xygrid" # id="grid970" /> # </sodipodi:namedview> # <metadata # id="metadata7"> # <rdf:RDF> # <cc:Work # rdf:about=""> # <dc:format>image/svg+xml</dc:format> # <dc:type # rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> # </cc:Work> # </rdf:RDF> # </metadata> # <g # inkscape:label="Layer 1" # inkscape:groupmode="layer" # id="layer1" # transform="translate(0,-732.36216)"> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="148.01953" # y="766.72156" # id="text2711-6-2-9-23"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-3" # x="148.01953" # y="766.72156" # style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '">N</tspan></text> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="251.40584" # y="806.94421" # id="text2711-6-2-9"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2" # x="251.40584" # y="806.94421" # style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '"><tspan # style="font-style:italic" # id="tspan9923">v</tspan><tspan # style="font-size:65%;baseline-shift:sub" # id="tspan1668" /></tspan></text> # <path # style="fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM)" # d="m 215.98949,804.88502 25.7387,1.3e-4" # id="path11252" /> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="153.68098" # y="915.71051" # id="text2711-6-2-9-2"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-84" # x="153.68098" # y="915.71051" # style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '">w</tspan></text> # <path # style="fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-37)" # d="m 31.113403,791.97918 -1.3e-4,25.7387" # id="path11252-5" /> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="26.501303" # y="780.6109" # id="text2711-6-2-9-8"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-2" # x="26.501303" # y="780.6109" # style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '">g</tspan></text> # <rect # style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:1;stroke-linecap:round;stroke-opacity:1" # id="rect1007" # width="59" # height="59" # x="130.5" # y="792.86218" # rx="0" # ry="0" /> # <g # id="g1363" # transform="translate(-6,20)"> # <path # style="fill:none;stroke:#ff0000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-9)" # d="m 161.00001,831.69534 -45.73871,1.3e-4" # id="path11252-4" /> # <path # style="fill:none;stroke:#0000ff;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-9-3)" # d="m 160.79738,832.36215 -1.3e-4,-75.7387" # id="path11252-4-6" /> # </g> # <path # style="fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-37-5)" # d="m 159.99967,822.02879 3.4e-4,75.73871" # id="path11252-5-0" /> # <text # xml:space="preserve" # style="font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none" # x="85.624084" # y="854.51099" # id="text2711-6-2-9-8-4"><tspan # sodipodi:role="line" # id="tspan2709-5-9-2-2-1" # x="85.624084" # y="854.51099" # style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '">f<tspan # style="font-size:65%;baseline-shift:sub" # id="tspan2197">k</tspan></tspan></text> # </g> # </svg> # # <br> # # Gambar <a name='fig2'>2</a>. Diagram gaya-gaya yang bekerja pada benda # bermassa $m$. # - # Terlihat bahwa pada arah $y$ terdapat gaya normal $N$ dan gaya gravitasi $w$, sedangkan pada arah $x$ hanya terdapat gaya gesek kinetis $f_k$ yang melawan arah gerak benda. Arah gerak benda diberikan oleh arah kecepatan $v$. # ## Metode numerik # Interasi suatu fungsi $f(x)$ berbentuk # # <a name='eqn8'></a> # \begin{equation}\label{eqn:integral-1}\tag{8} # A = \int_a^b f(x) dx # \end{equation} # # dapat didekati dengan # # <a name='eqn9'></a> # \begin{equation}\label{eqn:integral-2}\tag{9} # A \approx \sum_{i = 0}^N f\left[ \tfrac12(x_i + x_{i+1}) \right] \Delta x # \end{equation} # # yang dikenal sebagai metode persegi titik tengah, di mana # # <a name='eqn10'></a> # \begin{equation}\label{eqn:integral-3}\tag{10} # \Delta x = \frac{b - a}{N} # \end{equation} # # dengan $N$ adalah jumlah partisi. Variabel $x_i$ pada Persamaan ([9](#eqn9)) diberikan oleh # # <a name='eqn11'></a> # \begin{equation}\label{eqn:integral-4}\tag{11} # x_i = a + i\Delta x # \end{equation} # # dengan $i = 0, \dots, N$. # ## Penyelesaian # Penerapan Persamaan ([1](#eqn1)), ([2](#eqn2)), ([3](#eqn3)), ([4](#eqn4)), dan ([5](#eqn5)) pada Gambar [2](#fig2) akan menghasilkan # # <a name='eqn10'></a> # \begin{equation}\label{eqn:friction}\tag{10} # f_k = \mu_k mg # \end{equation} # # dan usahanya adalah # # <a name='eqn11'></a> # \begin{equation}\label{eqn:friction-work}\tag{11} # \begin{array}{rcl} # W & = & \displaystyle \int_{x_0}^x f_k dx \newline # & = & \displaystyle \int_{x_0}^x \mu_k m g dx \newline # & = & \displaystyle m g \int_{x_0}^x \mu_k dx # \end{array} # \end{equation} # # dengan koefisien gesek statisnya dapat merupakan fungsi dari posisi $\mu_k = \mu_k(x)$. # + import numpy as np import matplotlib.pyplot as plt plt.ion() # set integral lower and upper bounds a = 0 b = 1 # generate x x = [1, 2, 3, 4, 5] # generate y from numerical integration y = [1, 2, 3, 5, 6] ## plot results fig, ax = plt.subplots() ax.scatter(x, y) ax.set_xlabel("$x - x^0$") ax.set_ylabel("y") from IPython import display from IPython.core.display import HTML HTML(''' <div> Gambar <a name='fig3'>3</a>. Kurva antara usaha $W$ dan jarak tempuh $x - x_0$. </div> ''') # - # ## Diskusi # Berdasarkan Gambar [3](#fig3) dapat dijelaskan bahwa dengan $\mu_k = \mu_k(x)$ maka kurva $W(x)$ tidak lagi linier karena dipengaruhi oleh sejauh mana perhitungan kerja dilakukan. # ## Kesimpulan # Perhitungan kerja dengan $\mu_k = \mu_k(x)$ telah dapat dilakukan. # ## Referensi # 1. <NAME>, <NAME>, <NAME>, "A study of static and kinetic friction", International Journal of Engineerting Science, vol 28, no 1, p 29-92, 1990, url <https://doi.org/10.1016/0020-7225(90)90014-A>. # 1. <NAME>, "Friction", HyperPhysics, 2017, url <http://hyperphysics.phy-astr.gsu.edu/hbase/frict.html#fri> [20220419]. # 2. Wikipedia contributors, "Friction", Wikipedia, The Free Encyclopedia, 12 April 2022, 00:33 UTC, url <https://en.wikipedia.org/w/index.php?oldid=1082223658> [20220419]. # 3. <NAME>, <NAME>, "What is friction?", Live Science, 8 Feb 2022, url <https://www.livescience.com/37161-what-is-friction.html> [20220419].
assignments/05/10219048/work_of_friction.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="Y6DyphAUEBOi" # # Lab 05: MobileNet # # Trong bài thực hành này: # - Cài đặt, train MobileNet với data MNIST # # # Reference: # - MobileNet V1: MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications, https://arxiv.org/abs/1704.04861 # + [markdown] id="iWA8vNYyEBOj" # ## 1. Xây dựng MobileNet bằng tf.keras.layers # # Trong phần này chúng ta sẽ xây dựng và huấn luyện model ResNet-34 trên dataset MNIST (ảnh được resize) # + id="o7yiMO-bEBOl" #import thư viện cần thiết ## thư viện machine learning và hỗ trợ import tensorflow as tf from tensorflow import keras import numpy as np ## thư viện để vẽ đồ thị import matplotlib.pyplot as plt # + colab={"base_uri": "https://localhost:8080/"} id="GiL32W9MVMbY" outputId="1c76c5df-74bc-4f87-f3ac-0d1357af5e5d" mobilenet = keras.applications.mobilenet.MobileNet(input_shape=(32,32,1), alpha=1.0, depth_multiplier=1, dropout=1e-3, include_top=True, weights=None, input_tensor=None, pooling=None, classes=10) mobilenet.summary() # + [markdown] id="L2l2tYgIEBOr" # ### 1.1 Depthwise Separable Convolution # # Trong phần này sẽ xây dựng lớp DepthwiseSeparableConvolution gồm # - Depthwise Convolution: tích chập cho từng channel của input, kernel_size=[3,3] # - Pointwise convolution: là lớp convolution thông thường kernel size [1,1] với input từ Depthwise Convolution # # <img src="https://github.com/nhutnamhcmus/lab-deep-learning-solution/blob/main/Lab05/DepthSeparableConvolution.png?raw=1" width="40%" height="40%"> # # Hình trên bên phải vẽ cấu trúc của lớp Depthwise Separable Convolution # + id="aaP1rRKmPMi3" ## Import các layer cần thiết from tensorflow.keras.layers import Input, Dense, DepthwiseConv2D, Convolution2D, MaxPool2D, BatchNormalization, ReLU, GlobalAveragePooling2D from tensorflow.keras.regularizers import l2 ## Định nghĩa 1 Depthwise Separable Convolution class DepthwiseSeparableConvolution(keras.layers.Layer): def __init__(self, n_filters=64, l2_regularizer=0.0, down_sampling=False): ## Gọi hàm khởi tạo của keras.layers.Layer và lưu lại các thông số super(DepthwiseSeparableConvolution, self).__init__() self.n_filters = n_filters self.down_sampling = down_sampling self.l2_regularizer = l2_regularizer def get_config(self): config = super(DepthwiseSeparableConvolution, self).get_config() config.update({ "n_filters": self.n_filters, "down_sampling": self.down_sampling }) return config def build(self, input_shape): ## Nếu cần down sampling thì convolutional layer dùng strides=[2,2] strides = [1,1] if self.down_sampling: strides = [2,2] ##Khai báo các layer self.depthwise_conv = DepthwiseConv2D(kernel_size=[3,3], strides=strides, padding='same', use_bias=False, activation=None) self.depthwise_batch = BatchNormalization() self.depthwise_relu = ReLU() self.pointwise_conv = Convolution2D(filters=self.n_filters, kernel_size=[1,1], strides=[1,1], padding='same', use_bias=False, kernel_regularizer=l2(self.l2_regularizer), activation=None) self.pointwise_batch = BatchNormalization() self.pointwise_relu = ReLU() def call(self, inputs): ## Thiết lập các input cho các layer đã khai báo x = inputs x = self.depthwise_conv(x) x = self.depthwise_batch(x) x = self.depthwise_relu(x) x = self.pointwise_conv(x) x = self.pointwise_batch(x) x = self.pointwise_relu(x) return x # + [markdown] id="6F2ZxxXzT-54" # ### 1.2 Baseline MobileNet # # <img src="https://github.com/nhutnamhcmus/lab-deep-learning-solution/blob/main/Lab05/MobileNETv1.png?raw=1" width="40%" height="40%"> # # Hình trên vẽ các cấu trúc mạng MobileNetV1 # + colab={"base_uri": "https://localhost:8080/"} id="8c6cqf3MEBOr" outputId="bff586ab-3a35-4bd6-b6f0-b09b8d4f14fe" l2_regularizer_rate = 0.0 inputs = keras.layers.Input(shape=(32,32,1)) conv1 = Convolution2D(filters=32, kernel_size=[3,3], strides=[2,2], padding='same', use_bias=False, kernel_regularizer=l2(l2_regularizer_rate), activation=None)(inputs) batch1 = BatchNormalization()(conv1) relu1 = ReLU()(batch1) dw_pw_conv = DepthwiseSeparableConvolution(n_filters=64, l2_regularizer=l2_regularizer_rate, down_sampling=False)(relu1) #### dw_pw_conv = DepthwiseSeparableConvolution(n_filters=128, l2_regularizer=l2_regularizer_rate, down_sampling=True)(dw_pw_conv) dw_pw_conv = DepthwiseSeparableConvolution(n_filters=128, l2_regularizer=l2_regularizer_rate, down_sampling=False)(dw_pw_conv) #### dw_pw_conv = DepthwiseSeparableConvolution(n_filters=256, l2_regularizer=l2_regularizer_rate, down_sampling=True)(dw_pw_conv) dw_pw_conv = DepthwiseSeparableConvolution(n_filters=256, l2_regularizer=l2_regularizer_rate, down_sampling=False)(dw_pw_conv) #### dw_pw_conv = DepthwiseSeparableConvolution(n_filters=512, l2_regularizer=l2_regularizer_rate, down_sampling=True)(dw_pw_conv) dw_pw_conv = DepthwiseSeparableConvolution(n_filters=512, l2_regularizer=l2_regularizer_rate, down_sampling=False)(dw_pw_conv) dw_pw_conv = DepthwiseSeparableConvolution(n_filters=512, l2_regularizer=l2_regularizer_rate, down_sampling=False)(dw_pw_conv) dw_pw_conv = DepthwiseSeparableConvolution(n_filters=512, l2_regularizer=l2_regularizer_rate, down_sampling=False)(dw_pw_conv) dw_pw_conv = DepthwiseSeparableConvolution(n_filters=512, l2_regularizer=l2_regularizer_rate, down_sampling=False)(dw_pw_conv) dw_pw_conv = DepthwiseSeparableConvolution(n_filters=512, l2_regularizer=l2_regularizer_rate, down_sampling=False)(dw_pw_conv) ##### dw_pw_conv = DepthwiseSeparableConvolution(n_filters=1024, l2_regularizer=l2_regularizer_rate, down_sampling=True)(dw_pw_conv) ##### dw_pw_conv = DepthwiseSeparableConvolution(n_filters=1024, l2_regularizer=l2_regularizer_rate, down_sampling=True)(dw_pw_conv) avage_pool = GlobalAveragePooling2D()(dw_pw_conv) softmax = Dense(units=10, activation='softmax')(avage_pool) ## Compile model model = keras.models.Model(inputs=inputs, outputs=softmax) model.compile(optimizer=keras.optimizers.Adam(), loss=tf.keras.losses.sparse_categorical_crossentropy, metrics=["accuracy"]) ## In toàn bộ cấu trúc của model print("Cấu trúc của model: ") model.summary() # + [markdown] id="8hnPV9b7EBOu" # ### 1.3 Resize MNIST # + colab={"base_uri": "https://localhost:8080/"} id="ZzEiSsxeEBOv" outputId="31a4e806-0efc-48b2-f17e-86843292ff54" # Tải dataset MNIST từ tensorflow ## MNIST là bài toán dự đoán một ảnh thể hiện ký tự số nào ## tải MNIST dataset từ keras (X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data() ##resacle ảnh thành ảnh thực trong đoạn [0,1] X_train, X_test = X_train/255.0, X_test/255.0 ##in dataset print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) # + colab={"base_uri": "https://localhost:8080/"} id="rbLofc7iEBOz" outputId="8c6aeac8-ce34-44bc-80dd-058a86756c29" ## import thư viện OpenCV trên python # #!pip3 install opencv-python ### Thử resize một ảnh import cv2 resized_img = cv2.resize(X_train[0], dsize=(32,32)) print("Kích thước ảnh sau resize: ", resized_img.shape) # + colab={"base_uri": "https://localhost:8080/", "height": 549} id="FQNoy_veEBO1" outputId="f7bfa1a0-20e2-4a5f-9719-fdb0a5028afd" ## Resize toàn bộ ảnh train tập train và test X_train = np.array([cv2.resize(img, dsize=(32,32)) for img in X_train]) X_test = np.array([cv2.resize(img, dsize=(32,32)) for img in X_test]) print("Kích thước tập sau khi resize: ", X_train.shape, X_test.shape) ## In xem ảnh còn ổn không sau khi resize plt.imshow(X_train[0]) plt.show() ## Reshape ảnh để phù hợp với input của model (thêm một trục) X_train = np.expand_dims(X_train, axis=-1) X_test = np.expand_dims(X_test, axis=-1) print("Kích thước tập sau khi reshape: ", X_train.shape, X_test.shape) plt.imshow(X_train[0,:,:,0]) plt.show() #Tách một phần tập train thành tập valid from sklearn.model_selection import train_test_split X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=0.1) ## Reshape ảnh để phù hợp với input của model (thêm một trục) # + [markdown] id="klZ7mEYKT-6E" # ### 1.4 Train # + colab={"base_uri": "https://localhost:8080/"} id="OzVdTvPGEBO3" outputId="7f31f799-59ec-434c-8ce8-b06acd254d14" # Checkpoint Callback mc = keras.callbacks.ModelCheckpoint(filepath="mobilenet_mnist.h5", monitor='val_loss', mode='min', verbose=0, save_best_only=True) ## Train ## Khuyến cáo chạy COLAB (hoặc tương tự) history = model.fit(X_train, y_train, batch_size=100, epochs=10, validation_data=(X_valid, y_valid), callbacks=[mc]) ## Load lại model tốt nhất đã lưu print("best model: ") model.load_weights("mobilenet_mnist.h5") valid_loss, valid_acc = model.evaluate(X_valid, y_valid) test_loss, test_acc = model.evaluate(X_test, y_test) print("Valid: loss {} acc {} -- Test: loss {} valid {}".format(valid_loss, valid_acc, test_loss, test_acc)) # + [markdown] id="-DJHprqREBPK" # ## Bài tập # # Reference: MobileNetV2: Inverted Residuals and Linear Bottlenecks, https://arxiv.org/abs/1801.04381 # # Bài tập là xây dựng mạng MobileNetV2 với những cải tiến dựa trên bottleneck và residual. # 1. Xây dựng lớp Bottleneck DepthSeparable Convolution with Residuals: # ```python # class BottleneckDepthSeparableConvolutionWithResiduals(keras.layers.Layer): # # def __init__(self, n_filters=64, expansion_factor=6, l2_regularizer=0.0, down_sampling=False): # pass # ``` # # <img src="https://github.com/nhutnamhcmus/lab-deep-learning-solution/blob/main/Lab05/MobileNetv2-block.png?raw=1" width="40%" height="40%"> # # 2. Xây dựng mạng MobileNetV2: # # <img src="https://github.com/nhutnamhcmus/lab-deep-learning-solution/blob/main/Lab05/MobileNETv2.png?raw=1" width="40%" height="40%"> # # # + id="W3RDlxpP6dO8"
Lab05/Lab05.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.12 64-bit (windows store) # language: python # name: python3 # --- # + import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import Arrow from typing import Callable, Union # include the path to the src. module import sys sys.path.append('../src') from algebraic import VectorSpace, AffineSpace from elements import Vector as V, Field as F, Group as G, Module as M fig = plt.figure() ax = plt.axes(projection='3d') ax.view_init(elev=30, azim=60) base = [V(1, 2, 0), V(0, 1, 4)] # Vector space with modulo 4 field and vectors with the modulo 5 group defined by vector addition F4 = F({0, 1, 2, 3}, [lambda x, y: (x + y) % 4, lambda x, y: (x * y) % 4]) G5 = G({V(1, 2, 0), V(0, 1, 4)}, lambda u, v: (u + v) % 5).abelian() FM5 = M(F4, G5, lambda a, v: (a * v) % 5) VS = VectorSpace(FM5, base) AS = AffineSpace(VS, V(10, 10, 0)) x, y = np.linspace(-16, 16, 30), np.linspace(-16, 16, 30) X, Y = np.meshgrid(x, y) Z1 = (VS.parametricEquation())([X, Y]) Z2 = (AS.parametricEquation())([X, Y]) ax.plot_surface(X, Y, Z1, rstride=1, cstride=1, cmap='viridis', edgecolor='none', alpha=0.5) ax.plot_surface(X, Y, Z2, rstride=1, cstride=1, cmap='viridis', edgecolor='none', alpha=0.5) ax.quiver(0, 0, 0, 10, 10, 0, color = 'red') plt.show() # + import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from typing import Callable, Union # include the path to the src. module import sys sys.path.append('../src') from algebraic import VectorSpace, AffineSpace, AffineVariety from elements import Vector as V, Field as F fig = plt.figure() ax = plt.axes(projection='3d') F4 = F({0, 1, 2, 3}, [lambda x, y: (x + y) % 4, lambda x, y: (x * y) % 4]) AV = AffineVariety(F4, [lambda x, y: x*x + y*y - 4, lambda x, y: x**3 - 4*x*y]) X = np.linspace(-3, 3, 30) Y = np.linspace(-3, 3, 30) X, Y = np.meshgrid(X, Y) ax.contour(X, Y, AV.equations[0](X, Y), zdir='z', offset=0, levels = [0]) ax.contour(X, Y, AV.equations[1](X, Y), zdir='z', offset=0, levels = [0], colors = 'red') ax.set_zlim(zmin = -2) # + import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from typing import Callable, Union # include the path to the src. module import sys sys.path.append('../src') from algebraic import VectorSpace, AffineSpace, AffineVariety, Monomial from elements import Vector f = Monomial({0, 1, 2}, [1, 3, 2], 1) fig = plt.figure() ax = plt.axes() f.plot2d([-5, 5], [-5, 5])
tests/Note.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 # --- # # Otter-Grader Tutorial # # This notebook is part of the Otter-Grader tutorial. For more information about Otter, see our [documentation](https://otter-grader.rtfd.io). import pandas as pd import numpy as np # %matplotlib inline import otter grader = otter.Notebook() # **Question 1:** Write a function `square` that returns the square of its argument. def square(x): return x**2 grader.check("q1") # **Question 2:** Write an infinite generator of the Fibonacci sequence `fibferator` that is *not* recursive. def fiberator(): yield 0 yield 1 x, y = 0, 1 while True: x, y = y, x + y yield y grader.check("q2") # **Question 3:** Create a DataFrame mirroring the table below and assign this to `data`. Then group by the `flavor` column and find the mean price for each flavor; assign this **series** to `price_by_flavor`. # # | flavor | scoops | price | # |-----|-----|-----| # | chocolate | 1 | 2 | # | vanilla | 1 | 1.5 | # | chocolate | 2 | 3 | # | strawberry | 1 | 2 | # | strawberry | 3 | 4 | # | vanilla | 2 | 2 | # | mint | 1 | 4 | # | mint | 2 | 5 | # | chocolate | 3 | 5 | data = pd.DataFrame({ "flavor": ["chocolate", "vanilla", "chocolate", "strawberry", "strawberry", "vanilla", "mint", "mint", "chocolate"], "scoops": [1, 1, 2, 1, 3, 2, 1, 2, 3], "price": [2, 1.5, 3, 2, 4, 2, 4, 5, 5] }) price_by_flavor = data.groupby("scoops").mean()["price"] price_by_flavor grader.check("q3") # <!-- BEGIN QUESTION --> # # **Question 1.4:** Create a barplot of `price_by_flavor`. price_by_flavor.plot.bar() # <!-- END QUESTION --> # <!-- BEGIN QUESTION --> # # **Question 1.5:** What do you notice about the bar plot? # _Type your answer here, replacing this text._ # <!-- END QUESTION --> # The cell below allows you run all checks again. grader.check_all()
docs/tutorial/demo-fails3.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Sparkmagic # # (SparkR)' # language: '' # name: sparkrkernel # --- # # Sparkmagic SparkR Example # # 由于腾讯云弹性 MapReduce服务(EMR, https://cloud.tencent.com/product/emr )暂不支持 livy 组件,我们先使用本地 Spark 和 livy 服务做案例 # # 打开 notebook 的 console,输入 /opt/apache-livy-0.7.0-incubating-bin/bin/livy-server,将在本地 8998 端口启动 livy 服务 # # 打开 /home/tione/.sparkmagic/config.json,确认下 sparkmagic 的配置 (可以根据 notebook 的资源调整 executorCores 等参数,防止请求过多资源影响 notebook 运行),可以直接使用默认参数 # 输入 %%info,确认当前的 session 语言配置,应为 sparkr,并且可以查看当前活跃的 session # %%info # 输入 spark 的测试代码, 使用 kmeans 做数据分析 # + t <- as.data.frame(Titanic) training <- createDataFrame(t) df_list <- randomSplit(training, c(7,3), 2) kmeansDF <- df_list[[1]] kmeansTestDF <- df_list[[2]] kmeansModel <- spark.kmeans(kmeansDF, ~ Class + Sex + Age + Freq, k = 3) # Model summary summary(kmeansModel) # Get fitted result from the k-means model head(fitted(kmeansModel)) # Prediction kmeansPredictions <- predict(kmeansModel, kmeansTestDF) head(kmeansPredictions) # -
introduction_to_applying_machine_learning/sparkmagic_sparkr/sparkmagic_sparkr.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- # # R Bootcamp Part 5 # # ## stargazer, xtable, and fixed effects regressions # # # This bootcamp will help us get more comfortable using **stargazer** and **xtable** to produce high-quality results and summary statistics tables, and using `felm()` from the **lfe** package for regressions (both fixed effects and regular OLS). # # # For today, let's load a few packages and read in a dataset on residential water use for residents in Alameda and Contra Costa Counties. # ## Preamble # Here we'll load in our necessary packages and the data file # + library(tidyverse) library(haven) library(lfe) library(lmtest) library(sandwich) library(stargazer) library(xtable) # load in wateruse data, add in measure of gallons per day "gpd" waterdata <- read_dta("wateruse.dta") %>% mutate(gpd = (unit*748)/num_days) head(waterdata) # - # # xtable # # `xtable` is a useful package for producing custom summary statistics tables. let's say we're interested in summarizing water use ($gpd$) and degree days ($degree\_days$) according to whether a lot is less than or greater than one acre ($lotsize_1$) or more than 4 acres ($lotsize_4$): # # `homesize <- waterdata %>% # select(hh, billingcycle, gpd, degree_days, lotsize) %>% # drop_na() %>% # mutate(lotsize_1 = ifelse((lotsize < 1), "< 1", ">= 1"), # lotsize_4 = ifelse((lotsize > 4), "> 4", "<= 4")) # head(homesize)` # # We know how to create summary statistics for these two variables for both levels of $lotsize\_1$ and $lotsize\_4$ using `summarise()`: # # `sumstat_1 <- homesize %>% # group_by(lotsize_1) %>% # summarise(mean_gpd = mean(gpd), # mean_degdays = mean(degree_days)) # sumstat_1` # # `sumstat_4 <- homesize %>% # group_by(lotsize_4) %>% # summarise(mean_gpd = mean(gpd), # mean_degdays = mean(degree_days)) # sumstat_4` # And now we can use `xtable()` to put them into the same table! # # `full <- xtable(cbind(t(sumstat_1), t(sumstat_4))) # rownames(full)[1] <- "Lotsize Group" # colnames(full) <- c("lotsize_1 = 1", "lotsize_1 = 0", "lotsize_4 = 0", "lotsize_4 =1") # full` # We now have a table `full` that is an xtable object. # # We can also spit this table out in html or latex form if needed using the `print.xtable()` function on our xtable `full`. To get the html code for the table, specify `type = "html"`: # # `print.xtable(full, type = "html")` # Copy and paste the html code here to see how it appears # # Stargazer # # `stargazer` is a super useful package for producing professional-quality regression tables. While it defaults to producing LaTeX format tables (a typesetting language a lot of economists use), for use in our class we can also produce html code that can easily be copied into text cells and formatted perfectly. # # ## Stargazer for Summary Statistics Tables # # Like `xtable`, we can use `stargazer` to produce attractive summary statistics tables. # # To produce the basic summary statistic table, we can just run `stargazer()` on our data frame in the following way: # # `stargazer(as.data.frame(waterdata), type = "text")` # Note that we need to include the `as.data.frame()` around our dataset to make sure stargazer reads it in properly (if you forget this you'll get column names but no rows in the table). # # By default, we get the number of observations, the mean, standard deviation, minimum, 25th and 27th percentiles, and max for each variable. # # You can change which statistics get displayed by including the `summary.stat` argument to specify the statistics we want, or using `omit.summary.stat` to hide the ones we don't want. For example, we can omit the 25th and 75th percentiles with the following two ways (and include the median in the first): # # `stargazer(as.data.frame(waterdata), type = "text", summary.stat = c("n", "mean", "median", "sd", "min", "max"))` # `stargazer(as.data.frame(waterdata), type = "text", omit.summary.stat = c("p25", "p75"))` # You can also obtain the corresponding html code by specifying `type = "html"` and then copying + pasting the code into a markdownd cell: # # `stargazer(as.data.frame(waterdata), type = "html", # summary.stat = c("n", "mean", "median", "sd", "min", "max"))` # Copy and paste the html code here! # ## Stargazer for Regression Tables # # We can also use `stargazer to produce high-quality regression tables. If we run the following three regressions: # # \begin{align*} GPD_{it} &= \beta_0 + \beta_1 degree\_days_{it} + \beta_2 precip_{it} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(1)\\ # GPD_{it} &= \beta_0 + \beta_1 degree\_days_{it} + \beta_2 precip_{it} + \beta_3 lotsize_{i}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(2)\\ # GPD_{it} &= \beta_0 + \beta_1 degree\_days_{it} + \beta_2 precip_{it} + \beta_3 lotsize_{i} + \beta_4 Homeval_i~~~~~~~~~~~~~~~~~~(3) # \end{align*} # # We might want to present the results side by side in the same table so that we can easily compare coefficients from one column to the other. To do that with `stargazer`, we can # # 1. Run each regression, storing them in memory (here we'll use `felm()` to run OLS without fixed effects) # 2. Run `stargazer(reg1, reg2, reg3, ..., type )` where the first arguments are all the regression objects we want in the table, and telling R what type of output we want # # If we specify `type = "text"`, we'll get the table displayed directly in the output window: # # `reg_a <- felm(gpd ~ degree_days + precip, waterdata) # reg_b <- felm(gpd ~ degree_days + precip + lotsize, waterdata) # reg_c <- felm(gpd ~ degree_days + precip + lotsize + homeval, waterdata)` # # `stargazer(reg_a, reg_b, reg_c, type = "text")` # And if we specify `type = "html"`, we'll get html code that we need to copy and paste into a text/markdown cell: # # `stargazer(reg_a, reg_b, reg_c, type = "html")` # Now all we need to do is copy and paste that html code from the output into a text cell and we've got our table! # (copy your code here) # And we get a nice looking regression table with all three models side by side! This makes it easy to see how the coefficient on lot size falls when we add in home value, letting us quickly figure out the sign of correlation between the two. # ## Stargazer and Heteroskedasticity-Robust Standard Errors # # There are often times where you want to use heteroskedasticity-robust standard errors in place of the normal kind to account for situations where we might be worried about violating our homoskedasticity assumption. To add robust standard errors to our table, we'll need to access them from the felm object with `$rse` and add them to stargazer() with the `se` argument as a list: # # `stargazer(reg_a, reg_b, reg_c, # type = "html", # se = list(reg_a$rse, reg_b$rse, reg_c$rse), # omit.stat = "f")` # # Here we're adding the robust standard errors to `stargazer()` with the `se =` argument (combining them together in the right order as a list). I'm also omitting the overall F test at the bottom with `omit.stat = "f"` since we'd need to correct that too for heteroskedasticity. # # Try copying the code below to see how the standard errors change when we use robust standard errors: # Copy and paste the updated table code here. # # Now that looks pretty good, though note that the less than signs in the note for signifcance labels don't appear right. This is because html is reading the < symbol as a piece of code and not the math symbol. To get around this, you can add dollar signs around the < signs in the html code for the note to have the signs display properly: # # `<sup>*</sup>p $<$ 0.1; <sup>**</sup>p $<$ 0.05; <sup>***</sup>p $<$ 0.01</td>` # ## Table Options # # Stargazer has a ton of different options for customizing the look of our table with optional arguments, including # * `title` lets us add a custom title # * `column.labels` lets you add text labels to the columns # * `covariate.labels` lets us specify custom labels for all our variables other than the variable names. Specify each label in quotations in the form of a vector with `c()` # * `ci = TRUE` adds in confidence intervals (by default for the 10\% level, but you can change it to the 1\% level with `ci.level = 0.99` # * `intercept.bottom = FALSE` will move the constant to the top of the table # * `digits` lets you choose the number of decimal places to display # * `notes` lets you add some notes at the bottom # * `order` lets you change the order in which the independent variables appear in the table. This expects a numeric vector with the new ordering # * `dep.var.caption` lets you change the text of `Dependent variable:` at the top. If you set it to the empty character string `""` it will remove the caption entirely. # # For example, we could customize the above table as # # `stargazer(reg_a, reg_b, reg_c, type = "text", # title = "Water Use, Weather, and Home Characteristics", # column.labels = c("Weather", "With Lotsize", "With HomeVal"), # order = c(1,5,4,3,2), # intercept.bottom = FALSE, # dep.var.caption = "", # digits = 2, # note = "Isn't stargazer neat?" # )` # # # Fixed Effects Regression # # # Today we will practice with fixed effects regressions in __R__. We have two different ways to estimate the model, and we will see how to do both and the situations in which we might favor one versus the other. # # Let's give this a try using the dataset `wateruse.dta`. The subset of households are high water users, people who used over 1,000 gallons per billing cycle. We have information on their water use, weather during the period, as well as information on the city and zipcode of where the home is located, and information on the size and value of the house. # # Suppose we are interested in running the following panel regression of residential water use: # # $$ GPD_{it} = \beta_0 + \beta_1 degree\_days_{it} + \beta_2 precip_{it} ~~~~~~~~~~~~~~~~~~~~~~~(1)$$ # # Where $GPD$ is the gallons used per day by household $i$ in billing cycle $t$, $degree\_days$ the count of degree days experienced by the household in that billing cycle (degree days are a measure of cumulative time spent above a certain temperature threshold), and $precip$ the amount of precipitation in millimeters. # # `reg1 <- lm(gpd ~ degree_days + precip, data = waterdata) # summary(reg1)` # Here we obtain an estimate of $\hat\beta_1 = 0.777$, telling us that an additional degree day per billing cycle is associated with an additional $0.7769$ gallon used per day. These billing cycles are roughly two months long, so this suggests an increase of roughly 47 gallons per billing cycle. Our estimate is statistically significant at all conventional levels, suggesting residential water use does respond to increased exposure to high heat. # # We estimate a statistically insignificant coefficient on additional precipitation, which tells us that on average household water use in our sample doesn't adjust to how much it rains. # # We might think that characteristics of the home impact how much water is used there, so we add in some home controls: # # # $$ GPD_{it} = \beta_0 + \beta_1 degree\_days_{it} + \beta_2 precip_{it} + \beta_3 lotsize_{i} + \beta_4 homesize_i + \beta_5 num\_baths_i + \beta_6 num\_beds_i + \beta_7 homeval_i~~~~~~~~~~~~~~~~~~~~~~~(2)$$ # # `reg2 <- lm(gpd ~ degree_days + precip + lotsize + homesize + num_baths + num_beds + homeval, data = waterdata) # summary(reg2)` # Our coefficient on $degree\_days$ remains statistically significant and doesn't change much, so we find that $\hat\beta_1$ is robust to the addition of home characteristics. Of these characteristics, we obtain statistically significant coefficients on the size of the lot in acres ($lotsize$), the size of the home in square feet ($homesize$), and the number of bedrooms in the home ($num_beds$). # # We get a curious result for $\hat\beta_6$: for each additional bedroom in the home we predict that water use will *fall* by 48 gallons per day. # # ### Discussion: what might be driving this effect? # Since there are likely a number of sources of omitted variable bias in the previous model, we think it might be worth including some fixed effects in our model. These will allow us to control for some of the unobserved sources of OVB without having to measure them directly! # # ## Method 1: Fixed Effects with lm() # # Up to this point we have been running our regressions using the `lm()` function. We can still use `lm()` for our fixed effects models, but it takes some more work and gets increasingly time-intensive as datasets get large. # # Recall that we can write our general panel fixed effects model as # # $$ y_{it} = \beta x_{it} + \mathbf{a}_i + \mathbf{d}_t + u_{it} $$ # # * $y$ our outcome of interest, which varies in both the time and cross-sectional dimensions # * $x_{it}$ our set of time-varying unit characteristics # * $\mathbf{a}_i$ our set of unit fixed effects # * $\mathbf{d}_t$ our time fixed effects # # We can estimate this model in `lm()` provided we have variables in our dataframe that correspond to each level of $a_i$ and $d_t$. This means we'll have to generate them before we can run any regression. # # ### Generating Dummy Variables # # In order to include fixed effects for our regression, we can first generate the set of dummy variables that we want. For example, if we want to include a set of city fixed effects in our model, we need to generate them. # # We can do this in a few ways. # # 1. First, we can use `mutate()` and add a separate line for each individual city: # # `fe_1 <- waterdata %>% # mutate(city_1 = as.numeric((city==1)), # city_2 = as.numeric((city ==2)), # city_3 = as.numeric((city ==3))) %>% # select(hh, city, city_1, city_2, city_3) # head(fe_1)` # This can be super tedious though when we have a bunch of different levels of our variable that we want to make fixed effects for. In this case, we have 27 different cities. # # 2. Alternatively, we can use the `spread()` function to help us out. Here we first group our data by household and billing cycle (our level of identification). Then we add in a constant variable `v` that is equal to one in all rows, and a copy of city that adds "city_" to the front of the city number. Then we pass the data to `spread`, telling it to split the variable `cty` into dummy variables for all its levels, with all the "false" cases filled with zeros. # # `fe_2 <- waterdata %>% # select(city, billingcycle)` # # # `fe_2 <- group_by(fe_2, hh, billingcycle) %>% # mutate(v = 1, cty = paste0("city_", city)) %>% # spread(cty, v, fill = 0) # head(fe_2)` # That is much easier! # # This is a useful approach if you want to produce summary statistics for the fixed effects (i.e. what share of the sample lives in each city), but isn't truly necessary. # # Alternatively, we can tell R to read our fixed effects variables as factors: # # `lm(gpd ~ degree_days + precip + factor(city), data = waterdata)` # # `factor()` around $city$ tells R to split city into dummy variables for each unique value it takes. R will then drop the first level when we run the regression - in our case making the first city our omitted group. # # # `reg3 <- lm(gpd ~ degree_days + precip + factor(city), data = waterdata) # summary(reg3)` # Now we have everything we need to run the regression # # # $$ GPD_{it} = \beta_0 + \beta_1 degree\_days_{it} + \beta_2 precip_{it} + \mathbf{a}_i + \mathbf{d}_t~~~~~~~~~~~~~~~~~~~~~~~(2)$$ # # Where $\mathbf{a}_i$ are our city fixed effects, and $\mathbf{d}_t$ our billing cycle fixed effects: # # `fe_reg1 <- lm(gpd ~ degree_days + precip + factor(city) + factor(billingcycle), data = waterdata) # summary(fe_reg1)` # __R__ automatically chose the first dummy variable for each set of fixed effect (city 1 and billing cycle 1) to leave out as our omitted group. # # Now that we account for which billing cycle we're in (i.e. whether we're in the winter or whether we're in the summer), we find that the coefficient on $degree\_days$ is now much smaller and statistically insignificant. This makes sense, as we were falsely attributing the extra water use that comes from seasonality to temperature on its own. Now that we control for the season we're in via billing cycle fixed effects, we find that deviations in temperature exposure during a billing cycle don't result in dramatically higher water use within the sample. # # ### Discussion: Why did we drop the home characteristics from our model? # ## Method 2: Fixed Effects with felm() # # Alternatively, we could do everything way faster using the `felm()` function from the package __lfe__. This package doesn't require us to produce all the dummy variables by hand. Further, it performs the background math way faster so will be much quicker to estimate models using large datasets and many variables. # # The syntax we use is now # # `felm(y ~ x1 + x2 + ... + xk | FE_1 + FE_2 + ..., data = df)` # # * The first section $y \sim x1 + x2 +... xk$ is our formula, written the same way as with `lm()` - but omitting the fixed effects # * We now add a `|` and in the second section we specify our fixed effects. Here we say $FE\_1 + FE\_2$ which tells __R__ to include fixed effects for each level of the variables $FE\_1$ and $FE\_2$. # * we add the data source after the comma, as before. # # Let's go ahead and try this now with our water data model: # # `fe_reg2 <- felm(gpd ~ degree_days + precip | city + billingcycle, data = waterdata) # summary(fe_reg2)` # And we estimate the exact same coefficients on $degree\_days$ and $precip$ as in the case where we specified everything by hand! We didn't have to mutate our data or add any variables. The one potential downside is that this approach doesn't report the fixed effects themselves by default. The tradeoff is that `felm` runs a lot faster than `lm`, especially with large datasets. # # We can also recover the fixed effects with getfe(): # # `getfe(fe_reg2, se = TRUE, robust = TRUE)` # the argument `se = TRUE` tells it to produce standard errors too, and `robust = TRUE` further indicates that we want heteroskedasticity-robust standard errors. # # # Note that this approach doesn't give you the same reference groups as before, but we get the same relative values. Note that before the coefficient on $city2$ was 301.7 and now is 73.9. But the coefficient on $city1$ is -227.8, and if we subtract $city1$ from $city2$ to get the difference in averages for city 2 relative to city 1 we get $73.9 - (-227.8) = 301.7$, the same as before! # # Fixed Effects Practice Question #1 # # #### From a random sample of agricultural yields Y (1000 dollars per acre) for region $i$ in year $t$ for the US, we have estimated the following eqation: # # \begin{align*} \widehat{\log(Y)}_{it} &= 0.49 + .01 GE_{it} ~~~~ R^2 = .32\\ # &~~~~~(.11) ~~~~ (.01) ~~~~ n = 1526 \end{align*} # # #### (a) Interpret the results on the Genetically engineered ($GE$) technology on yields. (follow SSS= Sign Size Significance) # # #### (b) Suppose $GE$ is used more on the West Coast, where crop yields are also higher. How would the estimated effect of GE change if we include a West Coast region dummy variable in the equation? Justify your answer. # # #### (c) If we include region fixed effects, would they control for the factors in (b)? Justify your answer. # # #### (d) If yields have been generally improving over time and GE adoption was only recently introduced in the USA, what would happen to the coefficient of GE if we included year fixed effects? # # # # # Fixed Effects Practice Question #2 # # #### A recent paper investigates whether advertisement for Viagra causes increases in birth rates in the USA. Apparently, advertising for products, including Viagra, happens on TV and reaches households that have a TV within a Marketing region and does not happen in areas outside a designated marketing region. What the authors do is look at hospital birth rates in regions inside and near the advertising region border and collect data on dollars per 100 people (Ads) for a certain time, and compare those to the birth rates in hospitals located outside and near the advertising region designated border. They conduct a panel data analysis and estimate the following model: # # $$ Births_{it} = \beta_0 + \beta_1 Ads + \beta_2 Ads^2 + Z_i + M_t + u_{it}$$ # # #### Where $Z_i$ are zipcode fixed effects and $M_t$ monthly fixed effects. # # #### (a) Why do the authors include Zip Code Fixed Effects? In particular, what would be a variable that they are controlling for when adding Zip Code fixed effects that could cause a problem when interpreting the marginal effect of ad spending on birth rates? What would that (solved) problem be? # # #### (b) Why do they add month fixed effects? # #
Spring2020-J/Sections/Coding Bootcamp/Coding Bootcamp Session Part 5.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- # # Logistic Regression # * author: "<NAME>" # * date: "11/7/2017" # ## Table of content # # * Logistics Regression # * The idea behind logistics regression model # * The interpretaion of $\beta_1$ in logistics regression # * Estimating the regression coefficients # * # * Multinomial Logistics Regression # * Logistics Regression for Nominal Response # * Bayes Classification # * Logistics Regression for Ordinal Response # # # --- # ## Logistics Regression # # ### • The idea behind logistics regression model # # Logistic Regression is useful when the outcome of our regression model is categorical. # Instead of using y, which we assume the value of it is categorical like {0,1}, {yes, no}, directly as our response variable, we models the probability that y belongs to a particular category. In other words, we build up a linear model on the log-odds (or logit). In the following paragraph, we denote the probability that y belongs to a particular category as $p(X) = Pr(Y=1|X)$ # # Since $p(X)$ is the probability that y belongs to a particular category, the value of it should be between 0 and 1. Therefore, we must model p(X) using a function that gives outputs between 0 and 1. Many functions meet this description. In logistic regression, we use the logistic function: # # $$ p(X)= \frac{e^{\beta_0+\beta_1X}}{1+e^{\beta_0+\beta_1X}} $$ # # We can easily see that the output value of this model is within 0 and 1. When $\beta_0+\beta_1X$ goes to $\infty$, $p(X)$ will be 1; When $\beta_0+\beta_1X$ goes to -$\infty$, $p(X)$ will be 0. # # This is the model that we are going to use to build up our regression model on. To make the equation to become more interpretable, after a bit of manipulation, we can get the following one: # # $$ log(\frac{p(X)}{1-p(X)})= \beta_0+\beta_1X $$ # # In the left hand side of the equation, it is the log odd of the probability that y belongs to a particular category. For example, if the probability of a success event is 0.8, then the odd ratio will be 4. The higher odds we get, the more likely we will get a success event. # # The left-hand side is called the log-odds or logit, which is also the link function of logistics regression. We see that the logistic regression has a logit that is linear in $X$. # # For the illustration purpose, we can see the Example 6.3 from the textbook *Predictive Analytics: Paramertic Models for Regression and Classificantion* # # We can see that the model is fitted using the log odd as y and the Eduation level as x. When eduation level increase from 1 to 2, then the log odd of visit is increased by $\beta_1$. # ![](_pic/example_6.3_1.png) # ![](_pic/example_6.3_2.png) # ![](_pic/example_6.3_3.png) # ### • The interpretaion of $\beta_1$ in logistics regression # # The above equation also equals: # # $$ \frac{p(X)}{1-p(X)}= e^{\beta_0+\beta_1X} $$ # # Here we assume that the $beta_1$ we get is 0.3. From the above equation, we can see that when $x$ is increased by 1 unit, the odd ratio will increase by $e^{\beta_1}$=`r exp(0.3)`. $\beta_1$ means how much the log odd ratio will increase if our predictor $x$ is increased by 1 unit. In other words, if $x$ is increased by 1 unit, then the odds ratio will increase by $e^{\beta_1}$. We can also get the increased probability of success from the increased odd ratio we get. For example, if the original $p(X)$ is 0.8, then our odds ratio is 4. When we increased x by 1, the odds ratio increased by $e^{\beta_1}$=`r exp(0.3)`. Therefore, the increased odd ratio is `r 4*exp(0.3)`. We can then get that our increased $p(X)$ is `r 4*exp(0.3)/(1+4*exp(0.3))`. # ### • Estimating the regression coefficients # # ***Why can't we use least square method to estimate the coefficient for logistic regression?*** # # If we follow the same formula as linear regression, then the cost function is # # $$\sum_{i=1}^{n} \Big( y_i - log(\frac{y_i}{1-y_i}) \Big)^2$$ # # The log term is either -$\infty$ if $y_i=0$ or $\infty$ if $y_i=1$. Even in the case that the response y is grouped, which means that we are trying to predict the success probability for each group, if the response for all the observations of $x_i$ within the group goes to 1, then log term will still be $\infty$. Therefore, least square method cannot be used. To estimate the coefficient, we will need to use MLE method introduce as follows. # # ***What is Maximum Likelihood Estimation(MLE)?*** # # To explain MLE intuitively, we can think of it as this way: # According to the observed fact, what is the process(or parameters) that will maximize the probability for us to get this outcome? # There is one explaination from Quora that explain it very well: # # *You only get to see what the nature wants you to see. Things you see are facts. These facts have an underlying process that generated it. These process are hidden, unknown, needs to be discovered. Then the question is: Given the observed fact, what is the likelihood that process P1 generated it? What is the likelihood that process P2 generated it? And so on... One of these likelihoods is going to be max of all. MLE is a function that extracts that max likelihood.* # # *Think of a coin toss; coin is biased. No one knows the degree of bias. It could range from o(all tails) to 1 (all heads). A fair coin will be 0.5 (head/tail equally likely). When you do 10 tosses, and you observe 7 Heads, then the MLE estimator for the prob of head of this coin is 0.7.* # # *Think of a stock price of say, British Petroleum. BP was selling at \$59.88 on April 23, 2010. By June 25, 2010 the price was down to \$27.02. There could be several reasons for this fall. But the most likely reason could be the BP oil spill and the public sentiment. Stock price is the observed fact. The MLE will estimate the most likely underlying reason.* # # For example, if we have drawn 5 samples from a population, assume all the 5 samples are drawn from normal independent distribution, i.e., $Y_i ~ NID(\mu, \alpha^2)$, then the joint p.d.f. of $Y_1, \dots, Y_n$ is the multiply of the five p.d.f. When we view the joint pdf of $Y_1, \dots, Y_n$ as a function of $\mu$ and $\alpha$, it's actually the likelihood function, which is the probabilty that these 5 samples are drawn from the normal distribution with some certain $\mu$ and $\alpha$. # # Another example is that when we flip a coin for 4 times, with 3 head and 1 tail. What is the MLE estimator for the probabilty that the coin will show us head? The marginal distribution of $Y_i$ is $p_i$ when $y_i=head$ and $1-p_i$ when $y_i=tail$. Therefore, the joint pdf(aka likelihood function) is $p^3(1-p)$. By taking partial derivative and set it to 0 with respect to p, we can get our MLE of p to be 3/4. # # ***How to use MLE to estimate the coefficient of logistic regression?*** # # We are trying to find estimtaes for $\beta_0$ and $\beta_1$, when we plug in these estimators into the our first equation above, yields a number close to 1 for all the observed y equals to 1; close to 0 for all observed y equals to 0. We can formulized the likelehood function $L$ as following: # # $$ L = L(\beta_0, \beta_1) = \displaystyle\prod_{i=1}^{n} \Big[ (p_i)^{y_i}(1-p_i)^{1-y_i} \Big] = \displaystyle\prod_{i=1}^{n} \Big( \frac{p_i}{1-p_i} \Big)^{y_i} \times \prod_{i=1}^{n} (1-p_i)$$ # # By taking log from both side # $$ ln(L) = \displaystyle\sum_{i=1}^{n} y_i ln\Big( \frac{p_i}{1-p_i}\Big) + \sum_{i=1}^{n} ln(1-p_i) = \displaystyle\sum_{i=1}^{n} y_i(\beta_0+\beta_1 x_i) - \sum_{i=1}^{n} ln(1+ exp(\beta_0+\beta_1x_i)) $$ # # The maximizing values can be found by setting the partial derivatives of $ln(L)$ with respect to $\beta_0$ and $\beta_1$. # # The main idea behind it is that for each observation, we are estimating a probability using the logistic function. Therefore, we can get an estimated probabilty for each observation. If the observed response for the observation is 1, then the estimated probabilty is $logisticFunction(x_i)$, where $\beta_0$ and $\beta_1$ is used in the logistic function. The likelihood of the observation will be the product of every observation. By taking the log of the likelihood function, it will be easier for us to do partial derivative and get the estimated $\beta$s. # ### • Evaluating the correctness of the model # # ***What are sensitivity, specifity, recall, precision and what is the rationale behind it?*** # ![](_pic/precision_recall.png) # # * **Precision**: tp/(predicted positive) = tp/(tp + fp) # * **Recall, Sensitivity**: tp/(real positive) = tp/(tp + fn) # * **Specificity**: tn/(real negative) # * **F1 score**: $\frac{2PR}{P+R}$ # # There is usually a tradeoff between precision and recall. Since if we want to get as much people as possible from the real positive cases, we can just predict everyone to be +. The recall will be 1. However, the precision will be low. Since out of the total predictive +, the true positive will be only small proportion of it. In other words, there will be lots of False positive. # # Let's take a typical cancer screening for example. When will we want to use Recall or Precision as our measure metric? # If we have very expensive secondary cancer test, we would probably prefer precision to recall. When precision is high, it means that when I predict a patient has cancer, then the result is highly reliable(False positive is low). The tradeoff is that we may have chances that a person has cancer but we don’t predict it(We may have a high false negative). That’s why in this case, we may prefer precision to recall. # # If we have cheap secondary cancer test, and we can afford send lots of people to do this test. Then we would probably like our model to predict as more suspicious people as possible, and send them to do this test. In other words, we want high Recall, we want to get as much people as possible out of the real + cases(We may have a high false postive, but it's ok, since the cancer test is cheap and we can afford it). # # To sum up, when we use Recall as the measure, we prefer low false negative than high false positive, i.e, we prefer to get as many people to get the cancer test than ignore anyone who might have a cancer but we don't test it; when we use Precision as the measure, we prefer low false positive than high falsh negative, i.e., we prefer whenever we say a patient has cancer, we say it with high confidence, and there may be a lot of potential having cancer patient that we do not test on them. # # # # ***What is ROC curve?*** # # The ROC curve is created by plotting the true positive rate (TPR=$\frac{tp}{\text{#real positive cases}}$, i.e. Sensitivity) against the false positive rate (FPR=$\frac{fp}{\text{#real negative cases}}$, i.e. 1-Specificity) at various threshold settings. # # In the perfect case, where the distribution is perfectly separate for positve and negative cases, the Area under curve(AUC) is 1. In the case that the two distribution is overlapping, the curve will be a straight line with AUC 0.5. # ### • An example of building binary logistic regression # ![](_pic/binary_logistic_example.png) # ***Answer(1)*** # + # Make Dataframe df = data.frame(days=c(21,24,25,26,28,31,33,34,35,37,43,49,51,55,25,29,43,44,46,46,51,55,56,58), response=c(rep(1,14),rep(0,10))) # Fit binary logistic regression fit = glm(response ~ days, family=binomial, data=df) summary(fit) # - # ***Answer(2)*** # # From the result of our model, we can see that the 95% CI for $\beta_{days}$= # # $$ -0.08648 \pm 1.96 \times 0.04322 = [-0.1711912, -0.0017688] $$ # Therefore, a 95% CI on the odds ratio equals the exponential of it, which is # $$[exp(-0.1711912), exp(-0.0017688)] = [0.8426604, 0.9982328] $$ # ***Answer(3)*** # + predict_response = predict(fit, newdata=df, type='response') real_response = df$response compare_df = data.frame(real = real_response, predict = predict_response) head(compare_df) # - # The predicted value for the 24 patients in the sample is shown in the table above in the predict column get_optimal_p <- function(real_response, predict_response, p_threshold_list){ max_ccr= 0 optimal_p = 0 for (p in p_threshold_list){ pred = rep(0, 24) pred[predict_response > p]=1 ccr = sum(diag(table(real=real_response, pred)))/ 24 if (ccr > max_ccr){ max_ccr= ccr optimal_p = p } } pred = rep(0, 24) pred[predict_response > optimal_p]=1 confusion_table=table(real=real_response, pred) confusion_table=table(real=real_response, pred) sensitivity=confusion_table[2,2]/(confusion_table[2,1]+confusion_table[2,2]) specificity=confusion_table[1,1]/(confusion_table[1,1]+confusion_table[1,2]) precision=confusion_table[2,2]/(confusion_table[1,2]+confusion_table[2,2]) f1_score=2*precision*sensitivity/(precision+sensitivity) return(data.frame(p=optimal_p, ccr=max_ccr, sensitivity=sensitivity, specificity=specificity, f1_score=f1_score)) } # The sensitivity, specificity and the F1 score fo the optimal p∗ is shown in the table below # + library(knitr) optimal = get_optimal_p(real_response, predict_response, seq(0.3,0.7,0.01)) kable(optimal) # - # ***Answer(4)*** # + library(pROC) summary(fit) plot.roc(real_response, fit$fitted.values, xlab="1-Specificity") my_auc = auc(real_response, fit$fitted.values) my_auc # - # The AUC is **0.75** # --- # # ## Multinomial Logistics Regression # For the data that the outcome is nominal or ordinal, we cannot apply binary logistic regression to our data anymore. One reason is that usually both types of data have more than 2 categories, and ordinal data is a categorical, statistical data type where the variables have natural, ordered categories and the distances between the categories is not known. # # Let's see how we can build a regression model on these types of data. # ### • Logistics Regression for Nominal Response # Let's assume that we have 3 categorical responses(A,B,C) and 6 predictors including the intercept now. How do we build up a logistic regression model on it? One way to do it is to set one response category as reference and compare the probabilities of the remaining 2 responses to it. Let's denote the probability of response $y=k$ by $p_k=p_k(x)$, and set category $C$ as the reference. Then we have the following equations # # $$ # \begin{cases} # ln(\frac{p_a}{p_c})=\beta_{0a}+\beta_{1a}x_1+ \beta_{2a}x_2 + \beta_{3a}x_3 + \beta_{4a}x_4 + \beta_{5a}x_5 & \quad \text{for category A}\\ # ln(\frac{p_b}{p_c})=\beta_{0b}+\beta_{1b}x_1+ \beta_{2b}x_2 + \beta_{3b}x_3 + \beta_{4b}x_4 + \beta_{5b}x_5 & \quad \text{for category B } # \end{cases} # $$ # More generally, we can rewrite it as: # # $$ ln(\frac{p_k}{p_c})=\beta_{0k}+\beta_{1k}x_1+ \beta_{2k}x_2 + \beta_{3k}x_3 + \beta_{4k}x_4 + \beta_{5k}x_5 \quad \text{for k = a, b} $$ # Therefore, in our example, we will need to estimate $(3-1)*6=12$ different $\beta$'s to build up a model. # # ***How do we interpret the meaning of all the $\beta_{ik}$ in the nominal logistic regression model?*** # # The explanation is quoted from the textbook *Predictive Analytics: Paramertic Models for Regression and Classificantion* explain it very well: # # "The interpretation of the coefficient $\beta_{ik}$ is similar to that of the $\beta_1$ coefficient for binary logistic regression. It is the change in the log-odds of response $k$={a or b} relative to that of the regerence category c when the predictor variable $x_{i}$ is increased by one unit keeping all other variables fixed. # # As an example, suppose $\beta_{ik}$ then $exp(0.5)=1.649$. Hence the odds of outcome $k$ vesus outcome $c$ increased by a factor of $1.649$ if $x_i$ is increased by one unit" # # ***How to get the predicted probability for different category responses?*** # # From the above equation, it follows that # $$ p_k = p_c e^{\beta_{0k}+\beta_{1k}x_1+ \beta_{2k}x_2 + \beta_{3k}x_3 + \beta_{4k}x_4 + \beta_{5k}x_5} $$ # If we denote category {A,B,C} as {1,2,3}, since $\displaystyle\sum_{k=1}^{3} p_k = 1$, we can see that # # $$ \displaystyle\sum_{k=1}^{3} p_k = p_a + p_b + p_c = p_c e^{\beta_{0a}+\beta_{1a}x_1+ \beta_{2a}x_2 + \beta_{3a}x_3 + \beta_{4a}x_4 + \beta_{5a}x_5} +p_c e^{\beta_{0b}+\beta_{1b}x_1+ \beta_{2b}x_2 + \beta_{3b}x_3 + \beta_{4b}x_4 + \beta_{5b}x_5} + p_c = 1 $$ # By solving $p_c$, we can get # # $$ p_c = \frac{1}{1+ e^{\beta_{0a}+\beta_{1a}x_1+ \beta_{2a}x_2 + \beta_{3a}x_3 + \beta_{4a}x_4 + \beta_{5a}x_5} + e^{\beta_{0b}+\beta_{1b}x_1+ \beta_{2b}x_2 + \beta_{3b}x_3 + \beta_{4b}x_4 + \beta_{5b}x_5}} = \frac{1}{1+ \sum_{j=1}^{2}e^{\beta_{0j}+\beta_{1j}x_1+ \beta_{2j}x_2 + \beta_{3j}x_3 + \beta_{4j}x_4 + \beta_{5j}x_5}} =$$ # # $$ \frac{1}{1+ \sum_{j=1}^{2} exp(x' \beta_j)} $$ # where $x' = (1, x_1, x_2, x_3, x_4, x_5)$ and $\beta_j = \beta_{0j} + \beta_{1j} + \beta_{2j}+ \beta_{3j}+ \beta_{4j} + \beta_{5j}$ # # Also, it follows that # # $$ # \begin{cases} # p_a=\frac{exp(x' \beta_a)}{1+ \sum_{j=1}^{2} exp(x' \beta_j)} & \quad \text{for category A}\\ # p_b=\frac{exp(x' \beta_b)}{1+ \sum_{j=1}^{2} exp(x' \beta_j)} & \quad \text{for category B } # \end{cases} # $$ # # To sum up, for given $x$ vector, we can then calculate the probability of it for category {A,B,C}, and use the category with the highest predicted probability as the predicted category. We refer to the predicted value we get here as **Maximum probability classifier** # ### • Bayes Classification # To go further, we can also use *prior probabilities* as the weight to the predicted probability that we calculate previous to get our bayes predicted probability. Suppose we have available prior probabilities, $\pi_a, \pi_b, \pi_c = (0.2, 0.3, 0.5)$. Then by using the follow equation derived from *bayes formula*, we can get the *posterior probabilities* # $$ \hat{p_k}^*(x) = \frac{\pi_k \hat{p_k}(x)}{\sum_{j=1}^{m} \pi_j \hat{p_j}(x)} $$ # # where $\hat{p_k}(x)$ is the Maximum probability classifier we calculate previously. # # In our example, we can get the posterior probabilities as # # $$ \hat{p_a}^*(x) = \frac{0.2 \times \hat{p_a}(x)}{0.2 \times \hat{p_a}(x)+ 0.3 \times \hat{p_b}(x)+ 0.5 \times \hat{p_c}(x)} $$ # $$\hat{p_b}^*(x) = \frac{0.3 \times \hat{p_b}(x)}{0.2 \times \hat{p_a}(x)+ 0.3 \times \hat{p_b}(x)+ 0.5 \times \hat{p_c}(x)} $$ # $$\hat{p_c}^*(x) = \frac{0.5 \times \hat{p_c}(x)}{0.2 \times \hat{p_a}(x)+ 0.3 \times \hat{p_b}(x)+ 0.5 \times \hat{p_c}(x)} $$ # # We refer to the predicted value we get here as **Bayes classifier**. One thing worth mention is that if the prior probabilities are equal, then the Bayes classifier is actually reduce to the maximum probability classifier. # ### • Logistics Regression for Ordinal Response # # For the categorical response that is ordinal, we build up our linear model on cumulative logits to capture the intrinsically ranked feature of it. The equation is shown as follows: # # $$ ln \Big[\frac{P(y \le k)}{P(y > k)} \Big]= \beta_{0k}+ x'\beta, \text{k=1, ... , m-1} $$ # Note that $P(y \le m)=1$, and the equation can also be rewrite as # $$ P(y \le k) = \frac{exp(\beta_{0k}+ x'\beta)}{1+exp(\beta_{0k}+ x'\beta)} $$ # # # If the category response in our preivous example {A,B,C} is ordinal, then the response value of the model we build is # $$ # \begin{cases} # ln \Big[\frac{P(y \le a)}{P(y > a)} \Big] = ln\Big[\frac{P(a)}{P(b \text{ or } c)} \Big] \\ # ln \Big[\frac{P(y \le b)}{P(y > b)} \Big] = ln\Big[\frac{P(a \text{ or } b)}{P(c)} \Big] # \end{cases} # $$ # # Therefore, we can get that # # $$ # \begin{cases} # P(y \le a) = \frac{exp(\beta_{0a}+ x'\beta)}{1+exp(\beta_{0a}+ x'\beta)} \\ # P(y \le b) = \frac{exp(\beta_{0b}+ x'\beta)}{1+exp(\beta_{0b}+ x'\beta)} \\ # P(y \le c) = \frac{exp(\beta_{0c}+ x'\beta)}{1+exp(\beta_{0c}+ x'\beta)} # \end{cases} # $$ # $$ # \begin{cases} # p_a = P(y \le a)\\ # p_b = P(y \le b) - P(y \le a) \\ # p_c = P(y \le c) - P(y \le b) # \end{cases} # $$ # We can also build up it and apply prior probability to make it into a Bayes classifier. # ### • An example of building logistic regression for nomimal and ordinal response # ![](_pic/Exercise_6.5.png) # ***Answer(a)*** # # The total *True Positive* number is 29, and we have 51 observations in our test dataset. Therefore, the overall correct classification rate is approximately **0.5686**. # + library(mlogit) # Read Data pregnancy_df = read.csv('_data/Pregnancy.csv', colClasses=c('factor','integer','factor','factor','factor')) # Transform Data pregnancy_df$Age <- relevel(pregnancy_df$Age, ref = "2") # Make train and test data train_indices <- seq(1, nrow(pregnancy_df), by=2) pregnancy_train <- pregnancy_df[train_indices,] pregnancy_test <- pregnancy_df[-train_indices,] # Build multinominal logistic regression pregnancy_train_mlogit = mlogit.data(data=pregnancy_train, choice='Duration', shape='wide') model_65_1 = mlogit(Duration ~ 0 | Nutrition+Alcohol+Smoking+Age, data=pregnancy_train_mlogit) # Make prediction for pregnancy_test pregnancy_test_mlogit = mlogit.data(data=pregnancy_test, choice='Duration', shape='wide') pregnancy_prediction_df = data.frame(predict(model_65_1, newdata = pregnancy_test_mlogit)) colnames(pregnancy_prediction_df) = c(1,2,3) pregnancy_prediction = as.integer(colnames(pregnancy_prediction_df)[apply(pregnancy_prediction_df,1,which.max)]) # make confusion table pregnancy_acutal = pregnancy_test$Duration print(table(actual = pregnancy_acutal, prediction = pregnancy_prediction)) # calculate the correct classification rate sum(diag(table(pregnancy_prediction, pregnancy_acutal)))/ dim(pregnancy_test)[1] # - # From the confusion table above, we can see that the correct classification rate for each category is library(knitr) table_65 <- data.frame(Category=c(1,2,3), Rate=c(4/13,9/17,16/21)) kable(table_65) # ***Answer(b)*** # # The total *True Positive* number is 34, and we have 51 observations in our test dataset. Therefore, the overall correct classification rate is approximately **0.6667**, which is higher than the result of multinominal logistic regression. # + library(ordinal) # Transform Data pregnancy_train$Duration = as.ordered(pregnancy_train$Duration) # Build ordinal logistic regression model_65_2 = clm(Duration~ . ,data=pregnancy_train) # Make prediction for pregnancy_test (https://www.rdocumentation.org/packages/ordinal/versions/2015.6-28/topics/predict.clm) pregnancy_prediction_2 = predict(model_65_2, newdata = pregnancy_test, type="class")$fit # make confusion table pregnancy_acutal = pregnancy_test$Duration print(table(actual = pregnancy_acutal, prediction = pregnancy_prediction_2)) # calculate the correct classification rate sum(diag(table(actual = pregnancy_acutal, prediction = pregnancy_prediction_2))) / dim(pregnancy_test)[1] # - # --- # # ## Reference # # * [How do you explain MLE intuitively from Quora](https://www.quora.com/How-do-you-explain-maximum-likelihood-estimation-intuitively) # * [An Introduction to Statistical Learning # with Applications in R](http://www-bcf.usc.edu/~gareth/ISL/) # * Predictive Analytics: Paramertic Models for Regression and Classificantion by <NAME> and <NAME>
LogisticRegression/logisticRegression.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 seaborn as sns import matplotlib.pyplot as plt import seaborn as sns dataset=pd.read_csv('daily kawish article dataset.csv') dataset.head() print("-------------Column count-------------") print(dataset.count()) print("----------Check for null values -----------") print(dataset.isnull().values.any()) dataset.dropna(axis = 0 , inplace = True) print("-----------Column count after removing null values----------") print(dataset.shape) top_10_authors=dataset.author.value_counts().iloc[:10] print("----------Top 10 author with more number of articles----------") print(top_10_authors) plt.figure(figsize=(10,10)) plt.xticks(rotation=90) ax = sns.countplot(x=dataset["author"], data=dataset, order = dataset["author"].value_counts().index[:10]) for p, label in zip(ax.patches, dataset["author"].value_counts()): ax.annotate(label, (p.get_x()+0.25, p.get_height()+0.5))
daily kawish articles/Sample Notebook for Sindhi Kawish Articles.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- load('../data_application/88soils/filter_onepercent/soils_ph_compLasso.RData') load('../data_application/88soils/filter_onepercent/soils_ph_elnet.RData') load('../data_application/88soils/filter_onepercent/soils_ph_lasso.RData') load('../data_application/88soils/filter_onepercent/soils_ph_rf.RData') c(out_compLasso$stab_index, out_compLasso$MSE_mean) c(out_lasso$stab_index, out_lasso$MSE_mean) c(out_elnet$stab_index, out_elnet$MSE_mean) c(out_rf$stab_index, out_rf$MSE_mean) # combine and export results soil_88 = as.data.frame(matrix(NA, nrow=4, ncol=4)) colnames(soil_88) = c('dataset', 'method', 'mse', 'stability') soil_88$dataset = 'soil_88' soil_88$method = c('lasso', 'elent', 'rf', 'compLasso') soil_88$mse = c(out_lasso$MSE_mean, out_elnet$MSE_mean, out_rf$MSE_mean, out_compLasso$MSE_mean) soil_88$stability = c(out_lasso$stab_index, out_elnet$stab_index, out_rf$stab_index, out_compLasso$stab_index) soil_88 #write.table(soil_88, file='../data_application/88soils/filter_onepercent/table_soil_88.txt', sep='\t', row.names=F) # ### add selection probability for each feature selection methods load('../data_application/88soils/filter_onepercent/soils_ph.RData') dim(taxa) # correct dimension prob_compLasso = colSums(out_compLasso$stab_table)/dim(out_compLasso$stab_table)[1] prob_lasso = colSums(out_lasso$stab_table)/dim(out_lasso$stab_table)[1] prob_elnet = colSums(out_elnet$stab_table)/dim(out_elnet$stab_table)[1] prob_rf = colSums(out_rf$stab_table)/dim(out_rf$stab_table)[1] feature_prob = t(data.frame(rbind(prob_compLasso, prob_lasso, prob_elnet, prob_rf))) rownames(feature_prob) = colnames(taxa) head(feature_prob[order(-feature_prob[, 1]), ], 10) # descending order write.table(feature_prob, file='../data_application/88soils/filter_onepercent/soils_slection_prob.txt', sep='\t', col.names=NA) # + # top 5 from compLasso # p__Actinobacteria.c__Rubrobacteria.o__Rubrobacterales.f__Rubrobacteraceae.g__Rubrobacter: 0.96 # p__Proteobacteria.c__Alphaproteobacteria.o__Rhizobiales.f__Hyphomicrobiaceae.g__Rhodoplanes: 0.91 # p__Proteobacteria.c__Alphaproteobacteria.o__Rhizobiales.f__Bradyrhizobiaceae.g__Balneimonas: 0.9 # p__Acidobacteria.c__Solibacteres.o__Solibacterales.f__Solibacteraceae.g__Candidatus.Solibacter: 0.88 # p__Proteobacteria.c__Alphaproteobacteria.o__Rhizobiales.f__Hyphomicrobiaceae.g__Rhodoplanes: 0.8 # + # from Jamie's paper: Acidobacteria, Actinobacteria, Bacteroidetes, alpha-, beta-, and gammaproteobacteria # are all associated with ph ## summary: what been selected by compLasso all belong to above ranges
data_application/notebooks_application/4.2 88soils_results_filter1%.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: feml # language: python # name: feml # --- # + import pandas as pd # for plotting import matplotlib.pyplot as plt # the dataset for the demo from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split # from feature-engine from feature_engine.discretisers import EqualFrequencyDiscretiser from feature_engine.categorical_encoders import OrdinalCategoricalEncoder # + # load the the Boston House price data from Scikit-learn boston_dataset = load_boston() # create a dataframe with the independent variables data = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names) # add the target data['MEDV'] = boston_dataset.target data.head() # + # let's separate into training and testing set X_train, X_test, y_train, y_test = train_test_split( data.drop('MEDV', axis=1), data['MEDV'], test_size=0.3, random_state=0) X_train.shape, X_test.shape # - # ## Equal-frequency discretization with Feature-engine # + # let's separate into training and testing set X_train, X_test, y_train, y_test = train_test_split( data.drop('MEDV', axis=1), data['MEDV'], test_size=0.3, random_state=0) X_train.shape, X_test.shape # + # with feature engine we can automate the process for many variables # in one line of code disc = EqualFrequencyDiscretiser( q=10, variables=['LSTAT', 'DIS', 'RM'], return_object=True) disc.fit(X_train) # + # transform train and test train_t = disc.transform(X_train) test_t = disc.transform(X_test) # + # let's explore if the bins have a linear relationship # with the target: we see they don't pd.concat([train_t, y_train], axis=1).groupby('DIS')['MEDV'].mean().plot() plt.ylabel('mean of survived') # + # let's order the bins enc = OrdinalCategoricalEncoder(encoding_method = 'ordered') enc.fit(train_t, y_train) # - # we can fnd the list of encoded variables here enc.variables # we can find a list of the re-ordered bins mappings here enc.encoder_dict_ # let's transformt the data sets train_t = enc.transform(train_t) test_t = enc.transform(test_t) # + # let's explore the monotonic relationship between bins and target pd.concat([train_t, y_train], axis=1).groupby('DIS')['MEDV'].mean().plot() plt.ylabel('mean of survived') # -
Chapter05/Recipe-3-Discretisation-plus-categorical-encoding.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 # --- # + colab={"base_uri": "https://localhost:8080/"} id="vAgHg4cvmIDO" outputId="b05fb082-33b4-46b1-9ba0-9a4a5813d98d" # !pip install pytrends # + colab={"base_uri": "https://localhost:8080/", "height": 450} id="vxsAyY6Gmabm" outputId="d272cfd7-c058-43df-8137-c0c5a7089a3e" from pytrends.request import TrendReq pytrends = TrendReq(hl='en-US', tz=360) from pytrends.request import TrendReq kw_list = ["Blockchain"] pytrends.build_payload(kw_list, cat=0, timeframe='today 5-y', geo='', gprop='') pytrends.interest_over_time()
crypto_trend_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 # --- # <a href="https://githubtocolab.com/giswqs/geemap/blob/master/examples/notebooks/56_local_data.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a> # # Uncomment the following line to install [geemap](https://geemap.org) if needed. # # How to add local vector and raster data to the map with a few clicks # + # # !pip install geemap # - import os import geemap # + # geemap.update_package() # - # ## Create an interactive map Map = geemap.Map() Map # ## Download sample daatasets # # Note that geemap only supports vector data using WGS84 (EPSG:4326). out_dir = os.getcwd() countries_url = "https://github.com/giswqs/data/raw/main/world/countries.zip" us_states_url = ( "https://raw.githubusercontent.com/giswqs/data/main/us/us_states.geojson" ) dem_url = ( 'https://drive.google.com/file/d/1vRkAWQYsLWCi6vcTMk8vLxoXMFbdMFn8/view?usp=sharing' ) landsat_url = ( 'https://drive.google.com/file/d/1EV38RjNxdwEozjc9m0FcO3LFgAoAX1Uw/view?usp=sharing' ) geemap.download_from_url(countries_url) geemap.download_from_url(us_states_url) geemap.download_from_gdrive(dem_url, 'dem.tif', unzip=False) geemap.download_from_gdrive(landsat_url, 'landsat.tif', unzip=False) # ## Add data to the map using the toolbar Map
examples/notebooks/56_local_data.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 (''base'': conda)' # name: python3 # --- # + import os import numpy as np import h5py from fancy import Data, Model, Analysis from fancy.interfaces.stan import coord_to_uv from astropy import units as u from astropy.coordinates import SkyCoord # + '''Setting up''' # Define location of Stan files stan_path = '../../stan/' # Define file containing source catalogue information source_file = '../../data/sourcedata.h5' uhecr_file = '../../data/UHECRdata.h5' # make output directory if it doesnt exist if not os.path.isdir("output"): os.mkdir("output") # source_types = ["SBG_23", "2FHL_250Mpc", "swift_BAT_213"] source_types = ["SBG_23"] # detector_types = ["auger2010", "auger2014", "TA2015"] detector_type = "TA2015" detector_type = "auger2014" # set random seed random_seed = 19990308 # flag to control showing plots or not show_plot = True # - '''set detector and detector properties''' if detector_type == "TA2015": from fancy.detector.TA2015 import detector_properties, alpha_T, M, Eth elif detector_type == "auger2014": from fancy.detector.auger2014 import detector_properties, alpha_T, M, Eth elif detector_type == "auger2010": from fancy.detector.auger2010 import detector_properties, alpha_T, M, Eth else: raise Exception("Undefined detector type!") # + '''Fit arrival model''' from astropy.coordinates import SkyCoord uhecr_coord_rands = [] for source_type in source_types: # table file table_file = '../../tables/tables_{0}_{1}.h5'.format(source_type, detector_type) # define output files arrival_output_file = 'output/arrival_fit_data_{0}_{1}.h5'.format(source_type, detector_type) # construct Dataset data = Data() data.add_source(source_file, source_type) data.add_uhecr(uhecr_file, detector_type) data.add_detector(detector_properties) # modify the right ascensions of uhecr data uhecr_coord = data.uhecr.coord uhecr_coord_icrs = uhecr_coord.icrs # convert to icrs frame # right ascension and declination uhecr_ra = uhecr_coord_icrs.ra.deg uhecr_dec = uhecr_coord_icrs.dec.deg # randomize right ascension uhecr_ra_rand = (uhecr_ra + np.random.rand(len(uhecr_ra)) * 360.) % 360. uhecr_coord_rand = SkyCoord(ra=uhecr_ra_rand, dec=uhecr_dec, frame="icrs", unit="deg") data.uhecr.coord = uhecr_coord_rand.galactic # also set unit vector data.uhecr.unit_vector = coord_to_uv(data.uhecr.coord) uhecr_coord_rands.append(uhecr_coord_rand) # construct arrival model obejct arrival_model = stan_path + 'arrival_direction_model.stan' model = Model(model_filename = arrival_model, include_paths = stan_path) model.compile() model.input(Eth = Eth) # EeV # What is happening # summary = b'Fit of the joint model to the Auger data' summary = b'Fit of the arrival direction model to data' # Define an Analysis object to bring together Data and Model objects analysis = Analysis(data, model, analysis_type = 'joint', filename = arrival_output_file, summary = summary) # Define location of pre-computed values used in fits # (see relevant notebook for how to make these files) # Each catalogue has a file of pre-computed values analysis.use_tables(table_file) # Fit the Stan model fit = analysis.fit_model(chains = 16, iterations = 500, seed = random_seed) # Save to analysis file analysis.save() # - '''Fit joint model''' for i, source_type in enumerate(source_types): # table file table_file = '../../tables/tables_{0}_{1}.h5'.format(source_type, detector_type) # define output files joint_output_file = 'output/joint_fit_data_{0}_{1}.h5'.format(source_type, detector_type) # construct Dataset data = Data() data.add_source(source_file, source_type) data.add_uhecr(uhecr_file, detector_type) data.add_detector(detector_properties) # modify right ascension data.uhecr.coord = uhecr_coord_rands[i] data.uhecr.unit_vector = coord_to_uv(data.uhecr.coord) if show_plot: data.show() joint_model = stan_path + 'joint_model.stan' model = Model(model_filename = joint_model, include_paths = stan_path) model.compile() model.input(Eth = Eth) # EeV # What is happening # summary = b'Fit of the joint model to the Auger data' summary = b'Fit of the joint model to data' # Define an Analysis object to bring together Data and Model objects analysis = Analysis(data, model, analysis_type = 'joint', filename = joint_output_file, summary = summary) # Define location of pre-computed values used in fits # (see relevant notebook for how to make these files) # Each catalogue has a file of pre-computed values analysis.use_tables(table_file) # Fit the Stan model fit = analysis.fit_model(chains = 16, iterations = 500, seed = random_seed) # Save to analysis file analysis.save()
uhecr_model/checks/random_ra/run_simulation_data.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 # --- # # FINAL PROJECT for CS 634 # ## Name: <NAME> # ## Topic: Predicting whether an individual is obese or not based on their eating habits and physical condition # Github link: https://github.com/vac38/Classification_of_obesity.git # # # Link to dataset: https://archive.ics.uci.edu/ml/datasets/Estimation+of+obesity+levels+based+on+eating+habits+and+physical+condition+ # # + # Importing libraries import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import scipy.stats as stats from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MinMaxScaler # - # Storing data in a pandas dataframe ObesityData = pd.read_csv("/Users/veena/Desktop/DM_final_project/ObesityDataSet.csv") # ## Exploratory Data analysis # To display the data type for each feature/Atrribute ObesityData.info() ObesityData # ### 1) Renaming columns in data #Renaming columns in data ObesityData.columns = ['Gender', 'Age', 'Height', 'Weight', 'family_history_with_overweight', 'high_caloric_food', 'vegetables_consumption', 'main_meals', 'food_between_meals', 'SMOKE', 'Daily_water', 'Calories_consumption', 'physical_activity', 'technology_devices', 'Alcohol_consumption', 'Transportation_used', 'Obesity'] # ### 2) converting label values to binary # # Since the task for this project is to perform binary classification , the labels were categorized in to Normal or Obese using the following distinction: # # Insufficient Weight, Normal Weight, Overweight Level I, Overweight Level II → Categorized as ‘NORMAL’ # # Obesity Type II and Obesity Type III → categorized as ‘OBESE’ # # Get all values present in the label column of dataset ObesityData['Obesity'].unique() # convert to labels to Normal and Obese ObesityData['Obesity'].replace({'Normal_Weight': 'Normal','Overweight_Level_I':'Normal' , 'Overweight_Level_II':'Normal', 'Insufficient_Weight':'Normal', 'Obesity_Type_I':'Obese','Obesity_Type_II':'Obese','Obesity_Type_III':'Obese'}, inplace= True) # Only two labels: Normal and Obese ObesityData['Obesity'].unique() # Checking for imbalance in data ObesityData['Obesity'].value_counts() # The distribution of each class with the labels shows that the data is not balanced since 1139 records belong to ‘Normal’ class and 972 to ‘Obese’ class and their ratio is ~1.17 # ### 3) Shape of Data ObesityData.shape # ### 4) Check for null values #Check if there are any missing values print("Column wise missing values in Data\n",ObesityData.isnull().sum()) sns.heatmap(ObesityData.isnull(), yticklabels=False) # ### 5) Age group of people in Dataset sns.displot(ObesityData['Age'] , bins = 20, kde=True) print('Average age: ',ObesityData['Age'].mean()) # The Age group of most of the participants in this study is 15 to 28 years with average age of 24 years # ### 6) Average height and weight for the males and females sns.set() fig = plt.figure(figsize=(20,10)) plt.subplot(1, 2, 1) sns.boxplot(x='Gender', y='Height', data=ObesityData) plt.subplot(1,2, 2) sns.boxplot(x='Gender', y='Weight', data=ObesityData) # The above box plots show that average height for males is more than females. # # Average weight of males is more than that of females # ### 7) Relation plot for weight ,height , genders and obesity subdf1 = ObesityData.iloc[:,[0,2,3,16]] sns.relplot(x="Height", y="Weight", hue="Obesity",style="Gender", data=subdf1) # Th above plot shows how height and weight influence obesity. # 1) People with higher weights tend to be more obese # # 2) Obesity does determined by ratio of height and weight. # ## Data Preprocessing # ### 1) Label Encoding # Since Classifiers cannot handle label data directly, label encoding is used. ObesityData.head(10) lenc = LabelEncoder() ObesityData['food_between_meals'] = lenc.fit_transform(ObesityData['food_between_meals']) ObesityData['SMOKE'] = lenc.fit_transform(ObesityData['SMOKE']) ObesityData['Calories_consumption'] = lenc.fit_transform(ObesityData['Calories_consumption']) ObesityData['Alcohol_consumption'] = lenc.fit_transform(ObesityData['Alcohol_consumption']) ObesityData['Gender'] = lenc.fit_transform(ObesityData['Gender']) ObesityData['family_history_with_overweight'] = lenc.fit_transform(ObesityData['family_history_with_overweight']) ObesityData['high_caloric_food'] = lenc.fit_transform(ObesityData['high_caloric_food']) ObesityData['Transportation_used'] = lenc.fit_transform(ObesityData['Transportation_used']) ObesityData['Obesity'] = lenc.fit_transform(ObesityData['Obesity']) ObesityData.head(10) # ### 2) Correlation between different features # + #Correlation matrix ObesityData.corr() #Correlation heatmap plt.figure(figsize=(15,10)) sns.heatmap(ObesityData.corr(), annot = True) # No two features are highly correlated # - # ### 3) Splitting the data in to features(X) and Labels(Y) X_n = ObesityData[['Gender', 'Age', 'Height', 'Weight', 'family_history_with_overweight', 'high_caloric_food', 'vegetables_consumption', 'main_meals', 'food_between_meals', 'SMOKE', 'Daily_water', 'Calories_consumption', 'physical_activity', 'technology_devices', 'Alcohol_consumption','Transportation_used']].values Y = ObesityData['Obesity'] # ### 4) Normalization of Data # The range of values for each feature are different. For example weight ranges from 39 kgs to 173 kgs and gender has only two values: 0 and 1. Therefore to convert all feature values between 0 and 1 , normalization is performed. #returns a numpy array with normalized values for X min_max_scaler = MinMaxScaler() X = min_max_scaler.fit_transform(X_n) # # Machine Learning models from sklearn.model_selection import KFold from sklearn.metrics import confusion_matrix from sklearn import linear_model from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from numpy import mean def calc_evaluation_metrics(TN,FP,FN,TP): # Sensitivity (recall o true positive rate) Sensitivity = TP/(TP+FN) # Specificity(true negative rate) Specificity = TN/(TN+FP) # Precision(positive predictive value) Precision = TP/(TP+FP) # Error Rate Err = (FP + FN)/(TP + FP + FN + TN) # Negative predictive value NPV = TN/(TN+FN) # False positive rate FPR = FP/(FP+TN) # False Discovery Rate FDR = FP / (FP + TP) # False negative rate FNR = FN/(TP+FN) # Overall accuracy Accuracy = (TP+TN)/(TP+FP+FN+TN) #F1_score F1_score = (2 * TP)/(2 *( TP + FP + FN)) #Balanced Acuuracy(BACC) BACC = (Sensitivity + Specificity)/2 #True Skills Statistics(TSS) TSS = (𝑇𝑃/(𝑇𝑃+𝐹𝑁)) - (𝐹𝑃/(𝐹𝑃+𝑇𝑁)) #Heidke Skill Score (HSS) num = 2 * ((TP*TN)-(FP*FN)) denom = ((𝑇𝑃 + 𝐹𝑁) * ((𝐹𝑁+𝑇𝑁)+(TP+FP))* (𝐹𝑃+𝑇𝑁)) HSS = num / denom return Accuracy,Sensitivity, Specificity, Precision,F1_score, Err, NPV, FPR,FDR,FNR,BACC,TSS,HSS # + def kfold_split(X,Y,train_index, test_index): X_train, X_test = X[train_index], X[test_index] y_train, y_test = Y[train_index], Y[test_index] return X_train, X_test,y_train, y_test def c_matrix (y_test, LR_pred, m, i): c_matrix=confusion_matrix(y_test, LR_pred).ravel() TN, FP, FN, TP = c_matrix[0],c_matrix[1], c_matrix[2],c_matrix[3] Accuracy,Sensitivity, Specificity, Precision,F1_score, Err, NPV, FPR,FDR,FNR,BACC,TSS,HSS = calc_evaluation_metrics(TN,FP,FN,TP) metrics = [m,i, Accuracy,Sensitivity, Specificity, Precision,F1_score, Err, NPV, FPR,FDR,FNR,BACC,TSS,HSS] return metrics def logistic(X_train, X_test,y_train, y_test): model_LR = linear_model.LogisticRegression(multi_class='ovr', solver='liblinear') model_LR.fit(X_train, y_train) LR_pred = model_LR.predict(X_test) return LR_pred def decision_tree(X_train, X_test,y_train, y_test): decisiontree_model = DecisionTreeClassifier(random_state=0) decisiontree_model.fit(X_train,y_train) dt_pred = decisiontree_model.predict(X_test) return dt_pred def random_forest(X_train, X_test,y_train, y_test): randomforest_model = RandomForestClassifier(max_depth = 100, max_features= 3, min_samples_leaf= 3) randomforest_model.fit(X_train,y_train) rt_pred = randomforest_model.predict(X_test) return rt_pred # - # ### Training and testing three diffrent machine learning models: Logistic Reression, Decision Tree and Random Forest # + kf = KFold(n_splits=10,random_state=None, shuffle = True) model_acc_LR = [] model_acc_DT = [] model_acc_RF = [] # LR = pd.DataFrame(columns =['model','fold','Accuracy','Sensitivity', 'Specificity', 'Precision', 'F1_score','Error rate', 'Negative predictive value', 'False positive rate', 'False Discovery Rate', 'False negative rate', 'Balanced Accuracy', 'True Skill Statistics','Heidke Skill Score']) i = 1 for train_index, test_index in kf.split(X): # Sets of train and test X_train, X_test,y_train, y_test = kfold_split(X,Y, train_index, test_index) # models and prediction LR_pred = logistic(X_train, X_test,y_train, y_test) DT_pred = decision_tree(X_train, X_test,y_train, y_test) RF_pred = random_forest(X_train, X_test,y_train, y_test) #Evaluation : Logistic regression metric_LR = c_matrix(y_test, LR_pred, 'Logistic Regression', i) model_acc_LR.append(metric_LR) #Evaluation : Decision Tree metric_DT = c_matrix(y_test, DT_pred, 'Decision Tree', i) model_acc_DT.append(metric_DT) #Evaluation : Random Forest metric_RF = c_matrix(y_test, RF_pred, 'Random Forest', i) model_acc_RF.append(metric_RF) i += 1 # Storing Data in Datframe LR_metrics = pd.DataFrame(model_acc_LR, columns =['model','fold','Accuracy','Sensitivity', 'Specificity', 'Precision', 'F1_score','Error rate', 'Negative predictive value', 'False positive rate', 'False Discovery Rate', 'False negative rate', 'Balanced Accuracy', 'True Skill Statistics','Heidke Skill Score']) LR_metrics.loc['Mean'] = LR_metrics.mean() DT_metrics = pd.DataFrame(model_acc_DT, columns =['model','fold','Accuracy','Sensitivity', 'Specificity', 'Precision', 'F1_score','Error rate', 'Negative predictive value', 'False positive rate', 'False Discovery Rate', 'False negative rate', 'Balanced Accuracy', 'True Skill Statistics','Heidke Skill Score']) DT_metrics.loc['Mean'] = DT_metrics.mean() RF_metrics = pd.DataFrame(model_acc_RF, columns =['model','fold','Accuracy','Sensitivity', 'Specificity', 'Precision', 'F1_score','Error rate', 'Negative predictive value', 'False positive rate', 'False Discovery Rate', 'False negative rate', 'Balanced Accuracy', 'True Skill Statistics','Heidke Skill Score']) RF_metrics.loc['Mean'] = RF_metrics.mean() # - # Results for logistic regression performed on Obesity data using 10-fold cross validation LR_metrics # + # Results for Decision tree performed on Obesity data using 10-fold cross validation DT_metrics # + # Results for Random forest performed on Obesity data using 10-fold cross validation RF_metrics # - # # Deep Learning # ### LSTM from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout # + model_acc_lstm = [] i = 1 for train, test in kf.split(X): X_train, X_test = X[train], X[test] y_train, y_test = Y[train], Y[test] # create model model = Sequential() model.add(LSTM(200, activation='relu',input_shape=(1,16))) model.add(Dense(100, activation='relu')) model.add(Dense(50, activation='relu')) model.add(Dense(25, activation='sigmoid')) model.add(Dense(1)) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model X_train_new = X_train.reshape((X_train.shape[0],1, X_train.shape[1])) X_test_new = X_test.reshape((X_test.shape[0],1, X_test.shape[1])) model.fit(X_train_new,y_train, epochs = 100, batch_size = 32, verbose=0) # predict on the model predval = model.predict(X_test_new).flatten() predval_new = np.where(predval > 0.5, 1, 0) #Evalute the model metric_lstm = c_matrix(y_test, predval_new, 'LSTM', i) model_acc_lstm.append(metric_lstm) i += 1 LSTM_metrics = pd.DataFrame(model_acc_lstm, columns =['model','fold','Accuracy','Sensitivity', 'Specificity', 'Precision', 'F1_score','Error rate', 'Negative predictive value', 'False positive rate', 'False Discovery Rate', 'False negative rate', 'Balanced Accuracy', 'True Skill Statistics','Heidke Skill Score']) LSTM_metrics.loc['Mean'] = LSTM_metrics.mean() # + # Results for LSTM performed on Obesity data using 10-fold cross validation LSTM_metrics # - lr = pd.DataFrame(LR_metrics.iloc[10:,2:]) dt = pd.DataFrame(DT_metrics.iloc[10:,2:]) rf = pd.DataFrame(RF_metrics.iloc[10:,2:]) lstm = pd.DataFrame(LSTM_metrics.iloc[10:,2:]) k = [lr,dt,rf,lstm] ALL_models = pd.concat(k) obesity_predictions = ALL_models.set_axis(['Linear Regression', 'Decision Tree', 'Random Forest','LSTM'], axis=0) # ## Conclusion obesity_predictions # ## Which algorithm performs better ? # # On comparing the accuracy, it is evident that Random forest outperforms all other models and therfore the best model for predicting obesity given the this dataset. # # The Random forest Algorithm performs better than all the other models, because random forest can handle classification tasks with all kinds of input features and also with minimal preprocessing. #
Chaudhari_veena_finaltermproj.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 index of a saddle point # # We consider a *n* degree-of-freedom Hamiltonian of the following form: # # \begin{equation} # H(q, p) = \sum_{i=1}^{n} \frac{p_i^2}{2} + V(q), \quad (q,p) \in \mathbb{R}^n \times \mathbb{R}^n, # \label{ham_int} # \end{equation} # # # where $q \in \mathbb{R}^n$ denote the configuration space variables and $p \in \mathbb{R}^n$ denote the corresponding conjugate momentum variables. This Hamiltonian function gives rise to the corresponding Hamilton's differential equations (or just ''Hamilton's equations'') having the following form: # # \begin{eqnarray} # \dot{q}_i & = & p_i, \nonumber \\ # \dot{p}_i & = & -\frac{\partial V}{\partial q_i} (q), \quad i=1. \ldots , n. # \label{hameq_int} # \end{eqnarray} # # # These are a set of *2n* first order differential equations defined on the phase space # $\mathbb{R}^n \times \mathbb{R}^n$. # # # A critical point of the potential energy function is a point $\bar{q} \in \mathbb{R}^n$ satisfying the following equations: # # # \begin{equation} # \frac{\partial V}{\partial q_i} (\bar{q}) =0, \quad i=1, \ldots n. # \end{equation} # # Once a critical point of the potential energy function is located, we want to ''classify'' it. This is done by examining the second derivative of the potential energy function evaluated at the critical point. The second derivative matrix is referred to as the *Hessian matrix*, and it is given by: # # \begin{equation} # \frac{\partial^2 V}{\partial q_i \partial q_j} (\bar{q}) =0, \quad i,j=1, \ldots n, # \label{hessian} # \end{equation} # # # which is a $n \times n$ symmetric matrix. Hence \eqref{hessian} has *n* real eigenvalues, which we denote by: # # \begin{equation} # \sigma_k, \quad k=1, \ldots, n. # \label{eiv_Hess} # \end{equation} # # However, returning to dynamics as given by Hamilton's equations \eqref{hameq_int}, the point $(\bar{q}, 0)$ is an equilibrium point of Hamilton's equations, i.e. when this point is substituted into the right-hand-side of \eqref{hameq_int} we obtain $(\dot{q}_1, \ldots, \dot{q}_n, \dot{p}_1, \ldots, \dot{p}_n) = (0, \ldots, 0, 0, \ldots, 0)$, i.e. the point $(\bar{q}, 0)$ does not change in time. # # Next, we want to determine the nature of the stability of this equilibrium point. Linearized stability is determined by computing the Jacobian of the right hand side of \eqref{hameq_int}, which we will denote by $M$, evaluating it at the equilibrium point $(\bar{q}, 0)$, and determining its eigenvalues. The following calculation is from \cite{ezra2004impenetrable}. # The Jacobian of the Hamiltonian vector field \eqref{hameq_int} evaluated at $(\bar{q}, 0)$ is given by: # # # \begin{equation} # M = # \left( # \begin{array}{cc} # 0_{n\times n} & \rm{id}_{n \times n} \\ # -\frac{\partial^2 V}{\partial q_i \partial q_j} (\bar{q}) & 0_{n\times n} # \end{array} # \right), # \end{equation} # # # which is a $2n \times 2n$ matrix. The eigenvalues of $M$, denoted by $\lambda$, are given by the solutions of the following characteristic equation: # # \begin{equation} # {\rm det} \, \left( M - \lambda \, {\rm id}_{2n \times 2n} \right) =0, # \label{eivM} # \end{equation} # # # where ${\rm id}_{2n \times 2n}$ denoted the $2n \times 2n$ identity matrix. Writing \eqref{eivM} in detail (i.e. using the explicit expression for the Jacobian of \eqref{hameq_int}) gives: # # # # \begin{equation} # {\rm det} \, # \left( # \begin{array}{cc} # -\lambda \, \rm{id}_{n \times n} & \rm{id}_{n \times n} \\ # -\frac{\partial^2 V}{\partial q_i \partial q_j} (\bar{q}) & -\lambda \rm{id}_{n \times n} # \end{array} # \right) = {\rm det} \, \left(\lambda^2 \, \rm{id}_{n \times n} + \frac{\partial^2 V}{\partial q_i \partial q_j} (\bar{q}) \right) =0. # \end{equation} # # We can conclude from this calculation that the eigenvalues of the $n \times n$ symmetric matrix $\frac{\partial^2 V}{\partial q_i \partial q_j} (\bar{q})$ are $-\lambda^2$, where $\lambda$ are the eigenvalues of the $n \times n$ matrix $M$. Hence, the eigenvalues of $M$ occur in pairs, denoted by # $\lambda_k, \, \lambda_{k+n}, \, k=1, \ldots n$, which have the form: # # # # \begin{equation} # \lambda_k, \, \lambda_{k+n} = \pm \sqrt{-\sigma_k}, \quad k=1, \ldots, n, # \end{equation} # # # # where $\sigma_k$ are the eigenvalues of the Hessian of the potential energy evaluated at the critical point $\bar{q}$ as denoted in \eqref{eiv_Hess}. Hence, # we see that the existence of equilibrium points of Hamilton's equations of ''saddle-like stability'' implies that there must be *at least* one negative eigenvalue of \eqref{hessian}. In fact, we have the following classification of the linearized stability of saddle-type equilibrium points of Hamilton's equations in terms of the critical points of the potential energy surface. # # # + **Index 1 saddle.** One eigenvalue of \eqref{hessian} is positive, the rest are negative. We will assume that none of the eigenvalues of \eqref{hessian} are zero. Zero eigenvalues give rise to special cases that must be dealt with separately. In the mathematics literature, these are often referred to as *saddle-center-$\cdots$-center equilibria*, with the number of center-$\cdots$-center terms equal to the number of pairs of pure imaginary eigenvalues. # # + **Index 2 saddle.** Two eigenvalues of \eqref{hessian} are positive, the rest are negative # # # and in general, # # # + **Index k saddle.** *k* eigenvalues of \eqref{hessian} are positive,thevrestvare negativev($k \le n$). # ## References # # \bibliography{reaction_dynamics}
content/prologue/index_of_a_saddle_point.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 # --- # ## _*H2 ground state energy computation using Iterative QPE*_ # # This notebook demonstrates computing and graphing the ground state energy of the Hydrogen (H2) molecule over a range of inter-atomic distances using `IQPE` (Iterative Quantum Phase Estimation) algorithm. It is compared to the ground-truth energies as computed by the `NumPyMinimumEigensolver`. # # This notebook has been written to use the PYSCF chemistry driver. See the PYSCF chemistry driver readme if you need to install the external PySCF library that this driver requires. # # First we define the `compute_energy` method, which contains the H2 molecule definition as well as the computation of its ground energy given the desired `distance` and `algorithm` (`i` is just a helper index for parallel computation to speed things up). # + import pylab import time import numpy as np import multiprocessing as mp from qiskit import BasicAer from qiskit.aqua import QuantumInstance, AquaError from qiskit.aqua.operators import Z2Symmetries, op_converter from qiskit.aqua.algorithms import IQPE, NumPyMinimumEigensolver from qiskit.chemistry import FermionicOperator from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.chemistry.drivers import PySCFDriver, UnitsType def compute_energy(i, distance, algorithm): try: driver = PySCFDriver( atom='H .0 .0 .0; H .0 .0 {}'.format(distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g' ) except: raise AquaError('PYSCF driver does not appear to be installed') molecule = driver.run() qubit_mapping = 'parity' fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubit_op = Z2Symmetries.two_qubit_reduction( op_converter.to_weighted_pauli_operator(fer_op.mapping(map_type=qubit_mapping, threshold=1e-10)), 2) if algorithm == 'NumPyMinimumEigensolver': eigensolver = NumPyMinimumEigensolver(qubit_op) result = eigensolver.run() reference_energy = result.eigenvalue.real elif algorithm == 'IQPE': num_particles = molecule.num_alpha + molecule.num_beta two_qubit_reduction = True num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0) num_time_slices = 1 num_iterations = 12 state_in = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) iqpe = IQPE(qubit_op, state_in, num_time_slices, num_iterations, expansion_mode='trotter', expansion_order=1, shallow_circuit_concat=True) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) result = iqpe.run(quantum_instance) else: raise AquaError('Unrecognized algorithm: {}'.format(algorithm)) return i, distance, result.eigenvalue.real + molecule.nuclear_repulsion_energy, molecule.hf_energy # - # Next we set up the experiment to compute H2 ground energies for a range of inter-atomic distances, in parallel. # + import concurrent.futures import multiprocessing as mp algorithms = ['IQPE', 'NumPyMinimumEigensolver'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) start_time = time.time() max_workers = max(4, mp.cpu_count()) with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor: futures = [] for j in range(len(algorithms)): algorithm = algorithms[j] for i in range(steps+1): d = start + i*by/steps future = executor.submit( compute_energy, i, d, algorithm ) futures.append(future) for future in concurrent.futures.as_completed(futures): i, d, energy, hf_energy = future.result() energies[j][i] = energy hf_energies[i] = hf_energy distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print("--- %s seconds ---" % (time.time() - start_time)) # - # Finally we plot the results: pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.show() pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='IQPE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from NumPyMinimumEigensolver') pylab.legend(loc='upper right') pylab.show()
chemistry/h2_iqpe.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 # --- # # TensorFlow Tutorialの数学的背景 − MNIST For ML Beginners(その2) # http://enakai00.hatenablog.com/entry/2016/02/14/175505 # %matplotlib inline import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from numpy.random import rand, multivariate_normal # Create the model x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W) + b) # x がトレーニングセットのデータを注入する placeholder です。784個の要素を持つベクトルがN個あるとして、(Nx784)行列になります。実際には N は不定なので、None が指定されています。 # # W は係数 wijwij の行列で、(784x10)行列です。b は定数項 bjbj で、(1x10)行列です。10は出力層の数(0~9の数字) # # 最後に y が、組み込みの softmax() 関数で784個の入力を0~9に分類してくれる(下記を目的関数として、w,bのパラメータ最適化を実施する) # # 続いて、(2)のクロスエントロピーの定義です。 # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) # y_ は、トレーニングセットのラベル tt を縦に積み上げた (Nx10)行列で、cross_entropy がそのまま(2)の符号違いに対応していることが分かります。tf.log()は行列を代入すると各成分にlog()が演算されて、行列と行列の掛け算(*)は、各成分の掛け算になります。reduce_sum()は、行列のすべての要素を足しあげる関数です # train_stepは、cross_entropyを最小化するように変数を調整するアルゴリズムの指定です。 # アルゴリズムの実行は下記の部分です。 # Train tf.initialize_all_variables().run() for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) train_step.run({x: batch_xs, y_: batch_ys})
000_lib/haikei_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 # language: python # name: python3 # --- # + from qiskit.ml.datasets import breast_cancer import matplotlib.pyplot as plt import numpy as np from qiskit import BasicAer from qiskit.circuit.library import ZZFeatureMap from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import QSVM from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name seed = 10599 aqua_globals.random_seed = seed feature_dim = 2 sample_total, training_input, test_input, class_labels = breast_cancer( training_size=40, test_size=10, n=feature_dim, plot_data=True ) # + feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear') qsvm = QSVM(feature_map, training_input, test_input) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) result = qsvm.run(quantum_instance) print(f'Testing success ratio: {result["testing_accuracy"]}') # - kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
Quantum Machine learning.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # + [markdown] origin_pos=0 # # 注意力评分函数 # :label:`sec_attention-scoring-functions` # # 在 :numref:`sec_nadaraya-watson`中, # 我们使用高斯核来对查询和键之间的关系建模。 # 我们可以将 :eqref:`eq_nadaraya-watson-gaussian`中的 # 高斯核指数部分视为*注意力评分函数*(attention scoring function), # 简称*评分函数*(scoring function), # 然后把这个函数的输出结果输入到softmax函数中进行运算。 # 通过上述步骤,我们将得到与键对应的值的概率分布(即注意力权重)。 # 最后,注意力汇聚的输出就是基于这些注意力权重的值的加权和。 # # 从宏观来看,我们可以使用上述算法来实现 # :numref:`fig_qkv`中的注意力机制框架。 # :numref:`fig_attention_output`说明了 # 如何将注意力汇聚的输出计算成为值的加权和, # 其中$a$表示注意力评分函数。 # 由于注意力权重是概率分布, # 因此加权和其本质上是加权平均值。 # # ![计算注意力汇聚的输出为值的加权和](../img/attention-output.svg) # :label:`fig_attention_output` # # 用数学语言描述,假设有一个查询 # $\mathbf{q} \in \mathbb{R}^q$和 # $m$个“键-值”对 # $(\mathbf{k}_1, \mathbf{v}_1), \ldots, (\mathbf{k}_m, \mathbf{v}_m)$, # 其中$\mathbf{k}_i \in \mathbb{R}^k$,$\mathbf{v}_i \in \mathbb{R}^v$。 # 注意力汇聚函数$f$就被表示成值的加权和: # # $$f(\mathbf{q}, (\mathbf{k}_1, \mathbf{v}_1), \ldots, (\mathbf{k}_m, \mathbf{v}_m)) = \sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i) \mathbf{v}_i \in \mathbb{R}^v,$$ # :eqlabel:`eq_attn-pooling` # # 其中查询$\mathbf{q}$和键$\mathbf{k}_i$的注意力权重(标量) # 是通过注意力评分函数$a$ 将两个向量映射成标量, # 再经过softmax运算得到的: # # $$\alpha(\mathbf{q}, \mathbf{k}_i) = \mathrm{softmax}(a(\mathbf{q}, \mathbf{k}_i)) = \frac{\exp(a(\mathbf{q}, \mathbf{k}_i))}{\sum_{j=1}^m \exp(a(\mathbf{q}, \mathbf{k}_j))} \in \mathbb{R}.$$ # :eqlabel:`eq_attn-scoring-alpha` # # 正如我们所看到的,选择不同的注意力评分函数$a$会导致不同的注意力汇聚操作。 # 在本节中,我们将介绍两个流行的评分函数,稍后将用他们来实现更复杂的注意力机制。 # # + origin_pos=3 tab=["tensorflow"] import tensorflow as tf from d2l import tensorflow as d2l # + [markdown] origin_pos=4 # ## [**掩蔽softmax操作**] # # 正如上面提到的,softmax操作用于输出一个概率分布作为注意力权重。 # 在某些情况下,并非所有的值都应该被纳入到注意力汇聚中。 # 例如,为了在 :numref:`sec_machine_translation`中高效处理小批量数据集, # 某些文本序列被填充了没有意义的特殊词元。 # 为了仅将有意义的词元作为值来获取注意力汇聚, # 我们可以指定一个有效序列长度(即词元的个数), # 以便在计算softmax时过滤掉超出指定范围的位置。 # 通过这种方式,我们可以在下面的`masked_softmax`函数中 # 实现这样的*掩蔽softmax操作*(masked softmax operation), # 其中任何超出有效长度的位置都被掩蔽并置为0。 # # + origin_pos=7 tab=["tensorflow"] #@save def masked_softmax(X, valid_lens): """通过在最后一个轴上掩蔽元素来执行softmax操作""" # X:3D张量,valid_lens:1D或2D张量 if valid_lens is None: return tf.nn.softmax(X, axis=-1) else: shape = X.shape if len(valid_lens.shape) == 1: valid_lens = tf.repeat(valid_lens, repeats=shape[1]) else: valid_lens = tf.reshape(valid_lens, shape=-1) # 最后一轴上被掩蔽的元素使用一个非常大的负值替换,从而其softmax输出为0 X = d2l.sequence_mask(tf.reshape(X, shape=(-1, shape[-1])), valid_lens, value=-1e6) return tf.nn.softmax(tf.reshape(X, shape=shape), axis=-1) # + [markdown] origin_pos=8 # 为了[**演示此函数是如何工作**]的, # 考虑由两个$2 \times 4$矩阵表示的样本, # 这两个样本的有效长度分别为$2$和$3$。 # 经过掩蔽softmax操作,超出有效长度的值都被掩蔽为0。 # # + origin_pos=11 tab=["tensorflow"] masked_softmax(tf.random.uniform(shape=(2, 2, 4)), tf.constant([2, 3])) # + [markdown] origin_pos=12 # 同样,我们也可以使用二维张量,为矩阵样本中的每一行指定有效长度。 # # + origin_pos=15 tab=["tensorflow"] masked_softmax(tf.random.uniform(shape=(2, 2, 4)), tf.constant([[1, 3], [2, 4]])) # + [markdown] origin_pos=16 # ## [**加性注意力**] # :label:`subsec_additive-attention` # # 一般来说,当查询和键是不同长度的矢量时, # 我们可以使用加性注意力作为评分函数。 # 给定查询$\mathbf{q} \in \mathbb{R}^q$和 # 键$\mathbf{k} \in \mathbb{R}^k$, # *加性注意力*(additive attention)的评分函数为 # # $$a(\mathbf q, \mathbf k) = \mathbf w_v^\top \text{tanh}(\mathbf W_q\mathbf q + \mathbf W_k \mathbf k) \in \mathbb{R},$$ # :eqlabel:`eq_additive-attn` # # 其中可学习的参数是$\mathbf W_q\in\mathbb R^{h\times q}$、 # $\mathbf W_k\in\mathbb R^{h\times k}$和 # $\mathbf w_v\in\mathbb R^{h}$。 # 如 :eqref:`eq_additive-attn`所示, # 将查询和键连结起来后输入到一个多层感知机(MLP)中, # 感知机包含一个隐藏层,其隐藏单元数是一个超参数$h$。 # 通过使用$\tanh$作为激活函数,并且禁用偏置项。 # # 下面我们来实现加性注意力。 # # + origin_pos=19 tab=["tensorflow"] #@save class AdditiveAttention(tf.keras.layers.Layer): """Additiveattention.""" def __init__(self, key_size, query_size, num_hiddens, dropout, **kwargs): super().__init__(**kwargs) self.W_k = tf.keras.layers.Dense(num_hiddens, use_bias=False) self.W_q = tf.keras.layers.Dense(num_hiddens, use_bias=False) self.w_v = tf.keras.layers.Dense(1, use_bias=False) self.dropout = tf.keras.layers.Dropout(dropout) def call(self, queries, keys, values, valid_lens, **kwargs): queries, keys = self.W_q(queries), self.W_k(keys) # 在维度扩展后, # queries的形状:(batch_size,查询的个数,1,num_hidden) # key的形状:(batch_size,1,“键-值”对的个数,num_hiddens) # 使用广播方式进行求和 features = tf.expand_dims(queries, axis=2) + tf.expand_dims( keys, axis=1) features = tf.nn.tanh(features) # self.w_v仅有一个输出,因此从形状中移除最后那个维度。 # scores的形状:(batch_size,查询的个数,“键-值”对的个数) scores = tf.squeeze(self.w_v(features), axis=-1) self.attention_weights = masked_softmax(scores, valid_lens) # values的形状:(batch_size,“键-值”对的个数,值的维度) return tf.matmul(self.dropout( self.attention_weights, **kwargs), values) # + [markdown] origin_pos=20 # 我们用一个小例子来[**演示上面的`AdditiveAttention`类**], # 其中查询、键和值的形状为(批量大小,步数或词元序列长度,特征大小), # 实际输出为$(2,1,20)$、$(2,10,2)$和$(2,10,4)$。 # 注意力汇聚输出的形状为(批量大小,查询的步数,值的维度)。 # # + origin_pos=23 tab=["tensorflow"] queries, keys = tf.random.normal(shape=(2, 1, 20)), tf.ones((2, 10, 2)) # values的小批量,两个值矩阵是相同的 values = tf.repeat(tf.reshape( tf.range(40, dtype=tf.float32), shape=(1, 10, 4)), repeats=2, axis=0) valid_lens = tf.constant([2, 6]) attention = AdditiveAttention(key_size=2, query_size=20, num_hiddens=8, dropout=0.1) attention(queries, keys, values, valid_lens, training=False) # + [markdown] origin_pos=24 # 尽管加性注意力包含了可学习的参数,但由于本例子中每个键都是相同的, # 所以[**注意力权重**]是均匀的,由指定的有效长度决定。 # # + origin_pos=25 tab=["tensorflow"] d2l.show_heatmaps(tf.reshape(attention.attention_weights, (1, 1, 2, 10)), xlabel='Keys', ylabel='Queries') # + [markdown] origin_pos=26 # ## [**缩放点积注意力**] # # 使用点积可以得到计算效率更高的评分函数, # 但是点积操作要求查询和键具有相同的长度$d$。 # 假设查询和键的所有元素都是独立的随机变量, # 并且都满足零均值和单位方差, # 那么两个向量的点积的均值为$0$,方差为$d$。 # 为确保无论向量长度如何, # 点积的方差在不考虑向量长度的情况下仍然是$1$, # 我们将点积除以$\sqrt{d}$, # 则*缩放点积注意力*(scaled dot-product attention)评分函数为: # # $$a(\mathbf q, \mathbf k) = \mathbf{q}^\top \mathbf{k} /\sqrt{d}.$$ # # 在实践中,我们通常从小批量的角度来考虑提高效率, # 例如基于$n$个查询和$m$个键-值对计算注意力, # 其中查询和键的长度为$d$,值的长度为$v$。 # 查询$\mathbf Q\in\mathbb R^{n\times d}$、 # 键$\mathbf K\in\mathbb R^{m\times d}$和 # 值$\mathbf V\in\mathbb R^{m\times v}$的缩放点积注意力是: # # $$ \mathrm{softmax}\left(\frac{\mathbf Q \mathbf K^\top }{\sqrt{d}}\right) \mathbf V \in \mathbb{R}^{n\times v}.$$ # :eqlabel:`eq_softmax_QK_V` # # 在下面的缩放点积注意力的实现中,我们使用了暂退法进行模型正则化。 # # + origin_pos=29 tab=["tensorflow"] #@save class DotProductAttention(tf.keras.layers.Layer): """Scaleddotproductattention.""" def __init__(self, dropout, **kwargs): super().__init__(**kwargs) self.dropout = tf.keras.layers.Dropout(dropout) # queries的形状:(batch_size,查询的个数,d) # keys的形状:(batch_size,“键-值”对的个数,d) # values的形状:(batch_size,“键-值”对的个数,值的维度) # valid_lens的形状:(batch_size,)或者(batch_size,查询的个数) def call(self, queries, keys, values, valid_lens, **kwargs): d = queries.shape[-1] scores = tf.matmul(queries, keys, transpose_b=True)/tf.math.sqrt( tf.cast(d, dtype=tf.float32)) self.attention_weights = masked_softmax(scores, valid_lens) return tf.matmul(self.dropout(self.attention_weights, **kwargs), values) # + [markdown] origin_pos=30 # 为了[**演示上述的`DotProductAttention`类**], # 我们使用与先前加性注意力例子中相同的键、值和有效长度。 # 对于点积操作,我们令查询的特征维度与键的特征维度大小相同。 # # + origin_pos=33 tab=["tensorflow"] queries = tf.random.normal(shape=(2, 1, 2)) attention = DotProductAttention(dropout=0.5) attention(queries, keys, values, valid_lens, training=False) # + [markdown] origin_pos=34 # 与加性注意力演示相同,由于键包含的是相同的元素, # 而这些元素无法通过任何查询进行区分,因此获得了[**均匀的注意力权重**]。 # # + origin_pos=35 tab=["tensorflow"] d2l.show_heatmaps(tf.reshape(attention.attention_weights, (1, 1, 2, 10)), xlabel='Keys', ylabel='Queries') # + [markdown] origin_pos=36 # ## 小结 # # * 将注意力汇聚的输出计算可以作为值的加权平均,选择不同的注意力评分函数会带来不同的注意力汇聚操作。 # * 当查询和键是不同长度的矢量时,可以使用可加性注意力评分函数。当它们的长度相同时,使用缩放的“点-积”注意力评分函数的计算效率更高。 # # ## 练习 # # 1. 修改小例子中的键,并且可视化注意力权重。可加性注意力和缩放的“点-积”注意力是否仍然产生相同的结果?为什么? # 1. 只使用矩阵乘法,你能否为具有不同矢量长度的查询和键设计新的评分函数? # 1. 当查询和键具有相同的矢量长度时,矢量求和作为评分函数是否比“点-积”更好?为什么? #
tensorflow/chapter_attention-mechanisms/attention-scoring-functions.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 # --- # + # # %load HW2ofMLF.py """ Created on Mon Feb 22 15:12:49 2021 @author: Administrator """ import math import numpy as np import pandas as pd from scipy.io import arff from sklearn.linear_model import LogisticRegression from sklearn import svm, datasets from sklearn.svm import SVC from sklearn.model_selection import train_test_split import sklearn.preprocessing as skpre from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeClassifier #DATA PROCESSING data, meta = arff.loadarff('C:/Users/Administrator/Desktop/4year.arff') df=pd.DataFrame(data) df['bankruptcy'] = (df['class']==b'1') df.drop(columns=['class'], inplace=True) df.columns = ['X{0:02d}'.format(k) for k in range(1,65)] + ['bankruptcy'] df.fillna(df.mean(), inplace=True) X_imp = df.values X, y = X_imp[:, :-1], X_imp[:, -1] X_train, X_test, y_train, y_test =\ train_test_split(X, y, test_size=0.2, random_state=0, stratify=y) scaler = skpre.StandardScaler() X_train_std = scaler.fit_transform(X_train) X_test_std = scaler.transform(X_test) y_train=y_train*1 y_test=y_test*1 y_train=y_train.astype(int) y_test=y_test.astype(int) lr = LogisticRegression(penalty='l1',C=0.01, solver='liblinear') lr.fit(X_train_std, y_train.astype(int)) lr.coef_[lr.coef_!=0].shape X_train_std=X_train_std[:,lr.coef_[0]!=0] X_test_std=X_test_std[:,lr.coef_[0]!=0] #lR MODEL lr = LogisticRegression(penalty='l1') lr.fit(X_train_std, y_train.astype(int)) print('LR Training accuracy:', lr.score(X_train_std, y_train.astype(int))) print('LR Test accuracy:', lr.score(X_test_std, y_test.astype(int))) #models = (svm.SVC(kernel='linear', C=C), # svm.LinearSVC(C=C, max_iter=10000), # svm.SVC(kernel='rbf', gamma=0.7, C=C), # svm.SVC(kernel='poly', degree=3, gamma='auto', C=C)) ##for clf in models: clf=svm.SVC(C=1,kernel='rbf',gamma=10) clf.fit(X_train_std,y_train) print('SVM Training accuracy:', clf.score(X_train_std, y_train)) print('SVM Test accuracy:', clf.score(X_test_std, y_test)) tree= DecisionTreeClassifier(criterion='gini', max_depth=4, random_state=1) tree.fit(X_train, y_train) #############Codes below can't run, but I can't find the reason #############Codes below can't run, but I can't find the reason #############Codes below can't run, but I can't find the reason #############print('DecTree Training accuracy:', tree.score(X_train_std,y_train)) #############print('DecTree Test accuracy:', tree.score(X_test_std,y_test)) def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02): # setup marker generator and color map markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=colors[idx], marker=markers[idx], label=cl, edgecolor='black') # highlight test samples if test_idx: # plot all samples X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:, 1], c='', edgecolor='black', alpha=1.0, linewidth=1, marker='o', s=100, label='test set') X_combined_std = np.vstack((X_train_std, X_test_std)) y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X=X_combined_std, y=y_combined, classifier=lr, test_idx=range(0, 50)) plt.xlabel('ratio1 [standardized]') plt.ylabel('ratio2[standardized]') plt.legend(loc='upper left') plt.tight_layout() plt.show() #############Codes below can't run, but I can't find the reason #############Codes below can't run, but I can't find the reason #############Codes below can't run, but I can't find the reason #plot_decision_regions(X_combined_std, y_combined, # classifier=svm.SVC, test_idx=range(105, 150)) #plt.xlabel('petal length [standardized]') #plt.ylabel('petal width [standardized]') #plt.legend(loc='upper left') #plt.tight_layout() ##plt.savefig('images/03_15.png', dpi=300) #plt.show() # #plt.tight_layout() ##plt.savefig('images/03_01.png', dpi=300) #plt.show() # #X_combined = np.vstack((X_train_std, X_test_std)) #y_combined = np.hstack((y_train, y_test)) #plot_decision_regions(X_combined, y_combined, # classifier=tree_model, # test_idx=range(105, 150)) # #plt.xlabel('ratio1') #plt.ylabel('ratio2') #plt.legend(loc='upper left') #plt.tight_layout() ##plt.savefig('images/03_20.png', dpi=300) #plt.show() ## # -
HW2_MLF.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python2 # --- % pylab inline import pandas as pd import sqlite3 import seaborn as sns db = sqlite3.connect("/Users/onyame/Dropbox/QuantifiedSelf/btle_backup_20062015_1241.sqlite") df = pd.read_sql("SELECT * from devices", db,index_col='id') df.head() df['devicetype'] = df['devicetype'].str.replace('\(.*\)', '', case=False) device_types = df.groupby('devicetype').size() device_names = df.groupby('devicename').size() device_types device_types.plot(kind='bar') device_types.keys() devices = device_types.drop([u'Apple device ',u'Unknown device']) devices devices.plot(kind='bar')
BLE devices at QS15.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 # --- import pybullet as pb import numpy as np import pybullet_data physicsClient = pb.connect(pb.GUI) pb.setAdditionalSearchPath(pybullet_data.getDataPath()) pybullet_data.getDataPath() planeId = pb.loadURDF("plane.urdf") visualShapeId = pb.createVisualShape( shapeType=pb.GEOM_MESH, fileName='~/Desktop/pybullet/procedural_objects-master/objs/0000/tree.obj', rgbaColor=None, meshScale=[0.1, 0.1, 0.1]) collisionShapeId = pb.createCollisionShape( shapeType=pb.GEOM_MESH, fileName='/home/oxygen/Desktop/pybullet/procedural_objects-master/objs/0000/0000.vhacd.obj', meshScale=[0.1, 0.1, 0.1]) multiBodyId = pb.createMultiBody( baseMass=1.0, baseCollisionShapeIndex=collisionShapeId, baseVisualShapeIndex=visualShapeId, basePosition=[0, 0, 1], baseOrientation=pb.getQuaternionFromEuler([0, 0, 0]))
simulation/pybullet/Untitled.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 # --- # # Feature Extraction and Selection # This basic example shows how to use [tsfresh](https://tsfresh.readthedocs.io/) to extract useful features from multiple timeseries and use them to improve classification performance. # # We use the robot execution failure data set as an example. # + # %matplotlib inline import matplotlib.pylab as plt from tsfresh import extract_features, extract_relevant_features, select_features from tsfresh.utilities.dataframe_functions import impute from tsfresh.feature_extraction import ComprehensiveFCParameters from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report # - # ## Load and visualize data # # The data set documents 88 robot executions (each has a unique `id` between 1 and 88), which is a subset of the [Robot Execution Failures Data Set](https://archive.ics.uci.edu/ml/datasets/Robot+Execution+Failures). # For the purpose of simplicity we are only differentiating between successfull and failed executions (`y`). # # For each execution 15 force (F) and torque (T) samples are given, which were measured at regular time intervals for the spatial dimensions x, y, and z. # Therefore each row of the data frame references a specific execution (`id`), a time index (`index`) and documents the respective measurements of 6 sensors (`F_x`, `F_y`, `F_z`, `T_x`, `T_y`, `T_z`). # + from tsfresh.examples import robot_execution_failures robot_execution_failures.download_robot_execution_failures() df, y = robot_execution_failures.load_robot_execution_failures() df.head() # - # Let's draw some example executions: df[df.id == 3][['time', 'F_x', 'F_y', 'F_z', 'T_x', 'T_y', 'T_z']].plot(x='time', title='Success example (id 3)', figsize=(12, 6)); df[df.id == 20][['time', 'F_x', 'F_y', 'F_z', 'T_x', 'T_y', 'T_z']].plot(x='time', title='Failure example (id 20)', figsize=(12, 6)); # ## Extract Features # We can use the data to extract time series features using `tsfresh`. # We want to extract features for each time series, that means for each robot execution (which is our `id`) and for each of the measured sensor values (`F_*` and `T_*`). # # You can think of it like this: tsfresh will result in a single row for each `id` and will calculate the features for each columns (we call them "kind") separately. # # The `time` column is our sorting column. # For an overview on the data formats of `tsfresh`, please have a look at [the documentation](https://tsfresh.readthedocs.io/en/latest/text/data_formats.html). # + # We are very explicit here and specify the `default_fc_parameters`. If you remove this argument, # the ComprehensiveFCParameters (= all feature calculators) will also be used as default. # Have a look into the documentation (https://tsfresh.readthedocs.io/en/latest/text/feature_extraction_settings.html) # or one of the other notebooks to learn more about this. extraction_settings = ComprehensiveFCParameters() X = extract_features(df, column_id='id', column_sort='time', default_fc_parameters=extraction_settings, # we impute = remove all NaN features automatically impute_function=impute) # - # `X` now contains for each robot execution (= `id`) a single row, with all the features `tsfresh` calculated based on the measured times series values for this `id`. X.head() # <div class="alert alert-info"> # # Currently, 4674 non-NaN features are calculated. # This number varies with the version of `tsfresh` and with your data. # # </div> # ## Select Features # Using the hypothesis tests implemented in `tsfresh` (see [here](https://tsfresh.readthedocs.io/en/latest/text/feature_filtering.html) for more information) it is now possible to select only the relevant features out of this large dataset. # # `tsfresh` will do a hypothesis test for each of the features to check, if it is relevant for your given target. X_filtered = select_features(X, y) X_filtered.head() # <div class="alert alert-info"> # # Currently, 669 non-NaN features survive the feature selection given this target. # Again, this number will vary depending on your data, your target and the `tsfresh` version. # # </div> # ## Train and evaluate classifier # Let's train a boosted decision tree on the filtered as well as the full set of extracted features. X_full_train, X_full_test, y_train, y_test = train_test_split(X, y, test_size=.4) X_filtered_train, X_filtered_test = X_full_train[X_filtered.columns], X_full_test[X_filtered.columns] classifier_full = DecisionTreeClassifier() classifier_full.fit(X_full_train, y_train) print(classification_report(y_test, classifier_full.predict(X_full_test))) classifier_filtered = DecisionTreeClassifier() classifier_filtered.fit(X_filtered_train, y_train) print(classification_report(y_test, classifier_filtered.predict(X_filtered_test))) # Compared to using all features (`classifier_full`), using only the relevant features (`classifier_filtered`) achieves better classification performance with less data. # <div class="alert alert-info"> # # Please remember that the hypothesis test in `tsfresh` is a statistical test. # You might get better performance with other feature selection methods (e.g. training a classifier with # all but one feature to find its importance) - but in general the feature selection implemented # in `tsfresh` will give you a very reasonable set of selected features. # # </div> # ## Extraction and Filtering is the same as filtered Extraction # Above, we performed the feature extraction and selection independently. # If you are only interested in the list of selected features, you can run this in one step: X_filtered_2 = extract_relevant_features(df, y, column_id='id', column_sort='time', default_fc_parameters=extraction_settings) (X_filtered.columns == X_filtered_2.columns).all()
notebooks/examples/01 Feature Extraction and Selection.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 # --- # # Preprocessing steps # # ## 0) Read in data # ## 1) Basic conversions and drops # ## 2) Joining search queries to make single-query interaction vectors, and user interaction vectors # ## 3) Create Context vector # ## 4) Finally, an example on how to access import pandas as pd import numpy as np import matplotlib.pyplot as plt import lenskit from sklearn.preprocessing import OneHotEncoder import sys print(sys.executable) # ## 0) Read in data # # + data_dir = '/home/awd275/Search_and_Discovery/sad_final_project/data/raw/small_100_results' columns_to_read = ['search_result_id','search_request_id', 'hotel_id', 'user_id','label', 'check_in', 'check_out', 'reward_program_hash', 'advance_purchase_days', 'number_of_nights', 'number_of_rooms', 'number_of_adults', 'srq_latitude', 'srq_longitude', 'check_in_weekday', 'check_out_weekday', 'srq_weekhour', 'weekday_travel', 'weekend_travel'] # - df = pd.read_parquet(data_dir,columns=columns_to_read) df.head() # ## 1) Basic conversions and drops # def df_conversions(df): ''' IMPORTANT!! 1) Adds a hotel_index column, this is assigns each hotel_id a number from 0 to len(hotel_id)-1. This index is used for our interaction vector, which is a len(hotel_id)-length vector with the interaction label as the entries. 2) Drops users with no user_id (aka, anonymous/first time users) 3) subtracts 1e^10 from user_id (ask eric why) 4) converts date time strings into pandas datetime objects ''' hotel_id_to_hotel_index = dict((hotel_id, i) for (i, hotel_id) in enumerate(df['hotel_id'].unique())) df['hotel_index']= df['hotel_id'].map(hotel_id_to_hotel_index) df.drop(df.loc[df['user_id'].isna()].index, inplace=True) df['user_id'] = df['user_id'] - 1e10 df['check_in'] = pd.to_datetime(df['check_in'],yearfirst=True) df['check_out'] = pd.to_datetime(df['check_out'],yearfirst=True) return df df = df_conversions(df) df.head() # # Joining search queries by search_result_id, and getting single/entire interaction_vecs # + def create_user_id_to_query_struct_dict(df): ''' returns a dictionary of user_id -> "query_struct." check create_query_struct_for_user for what a "query_struct" is ''' unique_user_ids = df['user_id'].unique() user_id_to_query_struct_dict = {user_id : create_query_struct_for_user(df,user_id) for user_id in unique_user_ids} return user_id_to_query_struct_dict def create_query_struct_for_user(df,user_id): ''' Returns a "query struct", which is a 2-tuple: (Assuming a given and fixed user_id): 1st entry: dict of search_request_ids to a interaction_vec for that search request. Note: The interaction_vec is a dict of hotel_index -> label for that hotel_index. Importantly, this is a sparse vector format. Thus, the 1st entry is a dict{search_request_id -> dict{hotel_idx->label}} 2nd return: user_vector containing all of the label/interactions w/user_id = user_id ''' # Select only the entries for the user we care about df_user_id = df[df['user_id']==user_id] # get all of their searches (search_id) unique_search_ids_per_user = df_user_id['search_request_id'].unique() # Loop over each search, storing the interaction for each search query interaction_vecs_per_query = [] for sr_id in unique_search_ids_per_user: # Select only entries for each search request df_sr_user_id = df_user_id[df_user_id['search_request_id']==sr_id] # Create a dict of {hotel_index:label} interaction_sparse_vec = pd.Series(df_sr_user_id['label'].values,index=df_sr_user_id['hotel_index']).to_dict() # Add it to vector interaction_vecs_per_query.append(interaction_sparse_vec) #make a dict of search_ids to interactions_vec search_id_to_interaction_vec = dict(zip(unique_search_ids_per_user,interaction_vecs_per_query)) # Merge all the interactions to get the user's entire interaction vec user_interaction_vec = merge_dicts_with_max(interaction_vecs_per_query) return search_id_to_interaction_vec,user_interaction_vec def get_single_query_interaction_vec(user_id_to_query_struct_dict,user_id,sr_id): return user_id_to_query_struct_dict[user_id][0][sr_id] def get_user_entire_interaction_vec(user_id_to_query_struct_dict,user_id): return user_id_to_query_struct_dict[user_id][1] def merge_dicts_with_max(dict_list): ''' merge a list of dictionaries if their keys overlap, return the max. e.g. {a:1,b:1} {b:2,c:2} merged into {a:1,b:2,c:2} We need this in order to merge a single users interaction vectors. Consider if a user does two queries, and ends up buying the same hotel twice. ''' return_dict = {} for dict_ in dict_list: for key in dict_: if key in return_dict: return_dict[key] = max(return_dict[key],dict_[key]) else: return_dict[key] = dict_[key] return return_dict # - user_id_to_query_struct_dict = create_user_id_to_query_struct_dict(df) # ## Creating Context Vector and encodes the categorical variables # # + def create_context_df_and_cat_encoder(df,cat_vars_to_use): ''' Creates the context_dataframe and cat_encoder returns a 2-tuple, 1st: return context_dataframe, which is a dataframe with !search_request_id as the index! 2nd: returns a sklearn OneHotEncoder, which has been trained on context_df['cat_vars_to_use'] ''' # Our df contains 100~ results for each search request id. Each of the 100 results have the same query info # e.g, they all have the same values for reward_program_has, check_in_weekday,number_of_nights,etc # We only need one row out of those 100 to properly get the context. # Here, we grab the first row sr_id_to_first_index_df = pd.DataFrame([[key,val.values[0]] for key,val in df.groupby('search_request_id').groups.items()], columns=['search_request_id','first_index']) context_df = df.loc[sr_id_to_first_index_df['first_index'].values] context_df.set_index('search_request_id',inplace=True) #Encode the categorical variables cat_onehot_enc = OneHotEncoder() cat_onehot_enc.fit(context_df[cat_vars_to_use]) return context_df,cat_onehot_enc def create_context_vec(context_df, cat_onehot_enc, cat_vars_to_use, quant_vars_to_use, sr_id): ''' returns a np.vector which contains the context information. The categorical features have already been encoded via cat_onehot_enc ''' #Get User id for this query user_id = context_df.loc[sr_id]['user_id'] # Get and encode the categorical features for this query context_cat_pre_enc = context_df.loc[sr_id][cat_vars_to_use] #Reshape if we're only dealing with one row if len(context_cat_pre_enc.shape) == 1: context_cat_pre_enc = context_cat_pre_enc.values.reshape(1,-1) context_cat_enc = cat_onehot_enc.transform(context_cat_pre_enc).todense() # Get the quantitative features for this query context_quant = context_df.loc[sr_id][quant_vars_to_use].to_numpy() if len(context_quant.shape) == 1: context_quant = context_cat_pre_enc.reshape(1,-1) #stack the encoded categorical features and quantitative features context_vec = np.hstack((context_cat_enc,context_quant)) # return the context return context_vec # + #Example test_sr_id = 10064244538 cat_vars_to_use = ['reward_program_hash', 'check_in_weekday', 'check_out_weekday', 'weekday_travel', 'weekend_travel'] quant_vars_to_use = ['check_in', 'check_out', 'advance_purchase_days', 'number_of_nights', 'number_of_rooms', 'number_of_adults', 'srq_latitude', 'srq_longitude', ] context_df, cat_onehot_enc = create_context_df_and_cat_encoder(df, cat_vars_to_use) context_vec = create_context_vec(context_df, cat_onehot_enc, cat_vars_to_use, quant_vars_to_use, test_sr_id) # - # This cell here to stop jupyter notebook from running to the finish raise NotImplementedError # # Accessing Example import pandas as pd import numpy as np import matplotlib.pyplot as plt import lenskit from sklearn.preprocessing import OneHotEncoder import sys print(sys.executable) def get_user_id_from_sr_id(context_df,sr_id): ''' Make sure you use context df, as that is indexed by search_id (this will speed things up) ''' return context_df.loc[sr_id]['user_id'] # + # Step 0 Read in Data data_dir = '/home/awd275/Search_and_Discovery/sad_final_project/data/raw/small_100_results' columns_to_read = ['search_result_id','search_request_id', 'hotel_id', 'user_id','label', 'check_in', 'check_out', 'reward_program_hash', 'advance_purchase_days', 'number_of_nights', 'number_of_rooms', 'number_of_adults', 'srq_latitude', 'srq_longitude', 'check_in_weekday', 'check_out_weekday', 'srq_weekhour', 'weekday_travel', 'weekend_travel'] df = pd.read_parquet(data_dir,columns=columns_to_read) # Step 1, basic drops and conversions df = df_conversions(df) # Step 2, create dict of user_id -> query_struct user_id_to_query_struct_dict = create_user_id_to_query_struct_dict(df) # Step 3, Create context_df and encoder vector context_df, cat_onehot_enc = create_context_df_and_cat_encoder(df, cat_vars_to_use) context_vec = create_context_vec(context_df, cat_onehot_enc, cat_vars_to_use, quant_vars_to_use, test_sr_id) # + test_sr_id = 10064244538 cat_vars_to_use = ['reward_program_hash', 'check_in_weekday', 'check_out_weekday', 'weekday_travel', 'weekend_travel'] quant_vars_to_use = ['check_in', 'check_out', 'advance_purchase_days', 'number_of_nights', 'number_of_rooms', 'number_of_adults', 'srq_latitude', 'srq_longitude', ] # Create context vector context_vec = create_context_vec(context_df, cat_onehot_enc, cat_vars_to_use, quant_vars_to_use, test_sr_id) user_id = get_user_id_from_sr_id(context_df,test_sr_id) # Get single_interaction_vec for this sr_id and user's entire interaction vec single_query_interaction_vec = get_single_query_interaction_vec(user_id_to_query_struct_dict, user_id, test_sr_id) user_entire_interaction_vec = get_user_entire_interaction_vec(user_id_to_query_struct_dict, user_id) # - context_vec user_id single_query_interaction_vec user_entire_interaction_vec # # Notes / BS below # All variables List # # 'search_result_id', # don't need # 'search_request_id', can use to join each search, doesnt go into model # 'hotel_id', categorical # 'user_id', categorical # 'label', ordinal (0,1,2,3) # 'check_in', quantitative (after date time conversion) # 'check_out', quantitative (after date time conversion) # 'reward_program_hash', categorical # 'advance_purchase_days', quantitative # 'number_of_nights', quantitative # 'number_of_rooms', quantitative # 'number_of_adults', quantitative # 'srq_latitude', quantitative # 'srq_longitude', quantitative # 'check_in_weekday', categorical # 'check_out_weekday', categorical # 'srq_weekhour', categorical (Probably don't need) # 'weekday_travel', categorical # 'weekend_travel' categorical # # # User_id # hotel_id # # # Categorical variables: # reward_program_hash # check_in_weekday # check_out_weekday # weekday_travel # weekend_travel # # quantitative variables # advance_purchase_days # number_of_nights # number_of_adults # # Pytorch flow description: # # Three inputs (two of them get concatenated): Single interaction for specific user, query, and all interactions for specific user. # # Concatenate single interaction query for specific user and query, and send to one encoder. # Send all interactions for a specific user to another encoder # # # + # !/home/awd275/miniconda3/envs/dsga3001/bin/python3 /home/awd275/Search_and_Discovery/sad_final_project/src/data/data_preprocessing_multvae.py /scratch/work/js11133/sad_data/raw/full/train /scratch/work/js11133/sad_data/processed/full/train # -
notebooks/Preprocessing.ipynb