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 (ipykernel) # language: python # name: python3 # --- # ## LightGBM # # GBDT(Gradient Boosting Decision Tree) 是利用弱分類器迭代訓練來得到最佳的模型,而 LightGBM(Light Gradient Boosting Machine)是實現 GBDT 的演算法。 # 由於 XGBoost 在訓練的時候空間暫存大,而 LightGBM 優化了 XGBoost 訓練的缺陷,在同樣的條件下加速 GBDT 演算法的運算。 # # LightGBM 修補了 GBDT 在巨量資料下會遇到記憶體限制、速度上的限制,更適合於實際面的應用。 # # # Leaf-wise的優點是在分裂次數相同的情況下,可以降低更多的誤差以達到更好的準確度;但是葉子可能因此一直長下去導致過度擬合,這裡可以增加 max_depth 的數量限制防止過擬合。 # # ![image.png](attachment:e42405d1-d048-47e7-a690-add32730d2fc.png) # # ### LightGBM 特色 # [參考來源](https://www.gushiciku.cn/pl/pvRC/zh-tw) # # - 速度更快 # - 採用直方圖演算法將遍歷樣本轉變為遍歷直方圖,極大的降低了時間複雜度。 # - 訓練過程中採用單邊梯度演算法過濾掉梯度小的樣本,減少了大量的計算。 # - 採用了基於 Leaf-wise 演算法的增長策略構建樹,減少了很多不必要的計算量。 # - 採用優化後的特徵並行、資料並行方法加速計算,當資料量非常大的時候還可以採用投票並行的策略。 # - 對快取也進行了優化,增加了快取命中率。 # - 記憶體消耗更小 # - 採用直方圖演算法將儲存特徵值轉變為儲存 bin 值,降低了記憶體消耗。 # - 訓練過程中採用互斥特徵捆綁演算法減少了特徵數量,降低了記憶體消耗。 # ### 安裝方式 # ``` # pip install lightgbm # ``` # ### 實際示範 # + # LightGBM # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Book_Purchased.csv') X = dataset.iloc[:, [2, 3]].values y = dataset.iloc[:, 5].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) import lightgbm as lgb from lightgbm import LGBMClassifier # 建立LightGBM模型 classifier = lgb.LGBMClassifier(objective = 'binary', learning_rate = 0.05, n_estimators = 100, random_state=0) # 使用訓練資料訓練模型 classifier.fit(X_train, y_train) # 使用訓練資料預測分類 y_pred = classifier.predict(X_test) from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) print(cm) # - from sklearn.metrics import classification_report print(classification_report(y_test, y_pred)) # ### 看圖說故事 # + LGBM_grid_measure = measure_performance(X = X_test, y = y_test, clf = classifier, show_classification_report=True, show_confusion_matrix=True) # feature importances print('Feature importances:', list(classifier.feature_importances_)) # visualization print('Plot feature importances...') ax = lgb.plot_importance(classifier, max_num_features=len(train)) plt.show() # - ax = lgb.plot_tree(classifier, figsize=(20, 8), show_info=['split_gain']) plt.show() # + [markdown] tags=[] # ### 比較目前所學的演算法 # + from sklearn.datasets import load_breast_cancer from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.metrics import plot_roc_curve from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier from lightgbm import LGBMClassifier import matplotlib.pyplot as plt import pandas as pd import numpy as np dataset = pd.read_csv('Book_Purchased.csv') dataset['Purchased'] = dataset['Purchased'].astype('str') dx = dataset.iloc[:, [2, 3, 4]].values dy = dataset.iloc[:, 5].values dx = PCA(n_components=2).fit_transform(dx) dx = StandardScaler().fit_transform(dx) dx_train, dx_test, dy_train, dy_test = train_test_split(dx, dy, test_size=0.2, random_state=0) # 建立不同模型 models = [ KNeighborsClassifier(), LogisticRegression(), LinearSVC(), SVC(), DecisionTreeClassifier(), RandomForestClassifier(), XGBClassifier(), LGBMClassifier(), ] # 訓練不同模型 for i, _ in enumerate(models): models[i].fit(dx_train, dy_train) plt.rcParams['font.size'] = 12 plt.figure(figsize=(8, 8)) # 建立子圖表 ax = plt.subplot(111) ax.set_title('ROC') # 畫對角線 ax.plot([0, 1], [0, 1], color='grey', linewidth=2, linestyle='--') # 對每個模型畫 ROC 曲線 for model in models: plot_roc_curve(model, dx_test, dy_test, linewidth=5, alpha=0.5, ax=ax) plt.grid(True) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.tight_layout() plt.show()
08_Model_Development/08_M7_LightGBM.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 # --- # + _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the read-only "../input/" directory # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import os for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) # You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" # You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session # + import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import spacy import re import nltk nltk.download('vader_lexicon') nltk.download('stopwords') from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk.corpus import stopwords import gensim from gensim.utils import simple_preprocess from collections import Counter from wordcloud import WordCloud import plotly.express as px import datetime from datetime import datetime import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) # + csv_file_list = ["/kaggle/input/newredditdata/COVID19Comments.csv", "/kaggle/input/newredditdata/modernavaccineComments.csv", "/kaggle/input/newredditdata/antivaxComments.csv", "/kaggle/input/newredditdata/CovidVaccineComments.csv", "/kaggle/input/newredditdata/CoronavirusComments.csv", "/kaggle/input/newredditdata/PfizerVaccineComments.csv", "/kaggle/input/newredditdata/VACCINESComments.csv", "/kaggle/input/newredditdata/AntiVaxxersComments.csv", "/kaggle/input/newredditdata/CovidVaccinatedComments.csv"] csv_reddit_files = ["/kaggle/input/newredditdata/PfizerVaccine.csv", "/kaggle/input/newredditdata/COVID19.csv", "/kaggle/input/newredditdata/CovidVaccine.csv", "/kaggle/input/newredditdata/CovidVaccinated.csv", "/kaggle/input/newredditdata/antivax.csv", "/kaggle/input/newredditdata/Coronavirus.csv", "/kaggle/input/newredditdata/VACCINES.csv", "/kaggle/input/newredditdata/AntiVaxxers.csv", "/kaggle/input/newredditdata/modernavaccine.csv"] list_of_dataframes = [] for filename in csv_file_list: list_of_dataframes.append(pd.read_csv(filename)) df = pd.concat(list_of_dataframes) list_of_title_dataframes = [] for filename in csv_reddit_files: list_of_title_dataframes.append(pd.read_csv(filename)) df_titles = pd.concat(list_of_dataframes) df_title_csv = pd.concat(list_of_title_dataframes) def tokenize(comment): for word in comment: yield(gensim.utils.simple_preprocess(str(word), deacc=True)) # deacc=True Removes punctuations df['tidy_tokens'] = list(tokenize(df['comments'])) # + df_titles['date'] split_data_title = [] only_dates_title = [] dates_title = [] for data in df_titles['date']: split_data_title.append(data.split(" ")[:1]) for data in split_data_title: for value in data: only_dates_title.append(value) for key in only_dates_title: values = datetime.strptime(key, '%Y-%m-%d').date() dates_title.append(values) df_titles = df_titles.drop(columns=['date']) df_titles.head() df_titles['date'] = dates_title df_titles.head() # + df['date'] split_data_titles = [] only_dates_titles = [] dates_titles = [] for data in df['date']: split_data_titles.append(data.split(" ")[:1]) for data in split_data_titles: for value in data: only_dates_titles.append(value) for key in only_dates_titles: values = datetime.strptime(key, '%Y-%m-%d').date() dates_titles.append(values) df = df.drop(columns=['date']) df.head() df['date'] = dates_titles df.head() # + df_title_csv['date'] split_data = [] only_dates = [] dates = [] for data in df_title_csv['date']: split_data.append(data.split(" ")[:1]) for data in split_data: for value in data: only_dates.append(value) for key in only_dates: values = datetime.strptime(key, '%Y-%m-%d').date() dates.append(values) df_title_csv = df_title_csv.drop(columns=['date']) df_title_csv.head() df_title_csv['date'] = dates df_title_csv.head() # - len(df_title_csv) ini_date = "2020-12-01" start_date = datetime.strptime(ini_date, '%Y-%m-%d').date() after_start_date = df_title_csv["date"] > start_date filtered_dates = df_title_csv.loc[after_start_date] len(filtered_dates) filtered_dates timeline = filtered_dates.groupby(['date']).count().reset_index() timeline['count'] = timeline['body'] timeline = timeline[['date', 'count']] fig = px.bar(timeline, x='date', y='count', labels={'date': 'Date', 'count': 'Reddit Count'}) fig.show() # + stop_words = stopwords.words('english') def remove_stopwords(tidy_tokens): return [[word for word in simple_preprocess(str(comment)) if word not in stop_words] for comment in tidy_tokens] df['tokens_no_stop'] = remove_stopwords(df['tidy_tokens']) #print(df.head()) df = df.drop(['tidy_tokens'], axis=1) def remove_links(tweet): tweet_no_link = re.sub(r"http\S+", "", tweet) return tweet_no_link df['tweet_text_p'] = np.vectorize(remove_links)(df['comments']) df # + vader_analyzer = SentimentIntensityAnalyzer() negative = [] neutral = [] positive = [] compound = [] def sentiment_scores(df, negative, neutral, positive, compound): for i in df['tweet_text_p']: sentiment_dict = vader_analyzer.polarity_scores(i) negative.append(sentiment_dict['neg']) neutral.append(sentiment_dict['neu']) positive.append(sentiment_dict['pos']) compound.append(sentiment_dict['compound']) # Function calling sentiment_scores(df, negative, neutral, positive, compound) # Prepare columns to add the scores later df["negative"] = negative df["neutral"] = neutral df["positive"] = positive df["compound"] = compound # Fill the overall sentiment with encoding: # (-1)Negative, (0)Neutral, (1)Positive sentiment = [] for i in df['compound']: if i >= 0.05: sentiment.append(1) elif i <= - 0.05: sentiment.append(-1) else: sentiment.append(0) df['sentiment'] = sentiment neg_tweets = df.sentiment.value_counts()[-1] neu_tweets = df.sentiment.value_counts()[0] pos_tweets = df.sentiment.value_counts()[1] df # - graph_data = df.copy() len(graph_data) ini_date = "2020-12-01" start_date = datetime.strptime(ini_date, '%Y-%m-%d').date() after_start_date = graph_data["date"] > start_date filtered_dates = graph_data.loc[after_start_date] len(filtered_dates) filtered_dates # + filtered_dates['date'] = pd.to_datetime(filtered_dates['date'], errors='coerce').dt.date # Get counts of number of tweets by sentiment for each date timeline = filtered_dates.groupby(['date', 'sentiment']).count().reset_index().dropna() fig = px.line(timeline, x='date', y='comments', color='sentiment', color_discrete_sequence=["#EF553B", "#636EFA", "#00CC96"], category_orders={'sentiment': ['neutral', 'negative', 'positive']},title='Timeline showing sentiment of Reddit Data about COVID-19 vaccines') fig.show() # + # Draw Plot fig, ax = plt.subplots(figsize=(10, 6), subplot_kw=dict(aspect="equal"), dpi= 80) data = [df.sentiment.value_counts()[-1], df.sentiment.value_counts()[0], df.sentiment.value_counts()[1]] categories = ['Negative', 'Neutral', 'Positive'] explode = [0.05,0.05,0.05] def func(pct, allvals): absolute = int(pct/100.*np.sum(allvals)) return "{:.1f}% ({:d} )".format(pct, absolute) wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data), textprops=dict(color="w"), colors=['#e55039', '#3c6382', '#78e08f'], startangle=140, explode=explode) # Decoration ax.legend(wedges, categories, title="Sentiment", loc="center left", bbox_to_anchor=(1, 0.2, 0.5, 1)) plt.setp(autotexts, size=10, weight=700) ax.set_title("Number of Comments by Sentiment", fontsize=12, fontweight="bold") plt.show() labels = ['Negative', 'Neutral', 'Positive'] freq = [df.sentiment.value_counts()[-1], df.sentiment.value_counts()[0], df.sentiment.value_counts()[1]] index = np.arange(len(freq)) plt.figure(figsize=(8,6)) plt.bar(index, freq, alpha=0.8, color= 'black') plt.xlabel('Sentiment', fontsize=13) plt.ylabel('Number of Comments', fontsize=13) plt.xticks(index, labels, fontsize=11, fontweight="bold") plt.title('Number of Comments per Sentiment', fontsize=12, fontweight="bold") plt.ylim(0, len(df['comments'])) plt.show() # We remove the neutral compound scores to compare the negative and positive tweets data = df[(df["sentiment"]!=0)] # Draw Plot plt.figure(figsize=(8,6), dpi= 80) sns.kdeplot(data["compound"], shade=True, color="#3c6382", label="Overall Compound Score", alpha=.7) # Decoration plt.title('Density Plot of Overall Compound Score', fontsize=11, fontweight='bold') plt.axvline(x=0, color='#e55039') plt.legend() plt.show() # + def lemmatization(tweets, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']): """https://spacy.io/api/annotation""" tweets_out = [] for sent in tweets: doc = nlp(" ".join(sent)) tweets_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags]) return tweets_out # Initialize spacy 'en' model, keeping only tagger component (for efficiency) # python3 -m spacy download en nlp = spacy.load('en', disable=['parser', 'ner']) # Do lemmatization keeping only noun, adj, vb, adv df['lemmatized'] = lemmatization(df['tokens_no_stop'], allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']) df.drop(['tokens_no_stop'], axis=1, inplace=True) df_pos = df[df['sentiment']==1] df_neg = df[df['sentiment']==(-1)] print(df_pos.head()) ### #Wordcloud # Join the tweet back together def rejoin_words(row): words = row['lemmatized'] joined_words = (" ".join(words)) return joined_words all_words_pos = ' '.join([text for text in df_pos.apply(rejoin_words, axis=1)]) all_words_neg = ' '.join([text for text in df_neg.apply(rejoin_words, axis=1)]) wordcloud = WordCloud(width=900, height=600, random_state=21, max_font_size=110, background_color='white', max_words=200,colormap='summer').generate(all_words_pos) plt.figure(figsize=(12, 8)) plt.title('WordCloud of Positive Comments', fontsize=14, fontweight="bold") plt.imshow(wordcloud, interpolation="bilinear") plt.axis('off') plt.show() wordcloud = WordCloud(width=900, height=600, random_state=21, max_font_size=110, background_color='ghostwhite', max_words=200,colormap='autumn').generate(all_words_neg) plt.figure(figsize=(12, 8)) plt.title('WordCloud of Negative Comments', fontsize=14, fontweight="bold") plt.imshow(wordcloud, interpolation="bilinear") plt.axis('off') plt.show() # 10 Most positive Tweets df_pos.sort_values('compound', inplace=True, ascending=False) df_pos.reset_index(drop=True, inplace=True) print(df_pos.head(10)) # 10 Most Negative Tweets df_neg.sort_values('compound', inplace=True) print(df_neg.reset_index(drop=True).head(10)) df.drop(['tweet_text_p', 'lemmatized'], axis=1, inplace=True) print(df.head()) df.to_pickle('REDDITSentiments.pkl') # -
redditnew.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="b6hNunCF5-Xt" colab={"base_uri": "https://localhost:8080/"} outputId="a532081f-4b1a-410e-e9b5-927e9938aacd" # %load_ext autoreload # %autoreload 2 # %matplotlib inline # + id="vgTY2qeJ93x2" import numpy as np # + colab={"base_uri": "https://localhost:8080/"} id="CMSTsOm36Ake" outputId="88f59dc4-2866-4f10-a231-8187b5201428" from google.colab import drive drive.mount('/content/gdrive') # + [markdown] id="Vzh-eI8g5-Xy" # ## The forward and backward passes # + id="z8zzwU5P6QPd" import sys sys.path.append('/content/gdrive/MyDrive/ColabNotebooks/fastaiPart2/course-v3/nbs/dl2') # + colab={"base_uri": "https://localhost:8080/"} id="EOHZ_3Ls7MSg" outputId="eeed1eb5-719c-4af2-aef3-c0f0e0f47e33" sys.path # + [markdown] id="Mm9wPIu45-Xz" # [Jump_to lesson 8 video](https://course.fast.ai/videos/?lesson=8&t=4960) # + id="z7T-i77P5-Xz" #export from exp.nb_01 import * def get_data(): import os import torchvision.datasets as datasets datasets.MNIST.resources = [ ('https://ossci-datasets.s3.amazonaws.com/mnist/train-images-idx3-ubyte.gz', 'f68b3c2dcbeaaa9fbdd348bbdeb94873'), ('https://ossci-datasets.s3.amazonaws.com/mnist/train-labels-idx1-ubyte.gz', 'd53e105ee54ea40749a09fcbcd1e9432'), ('https://ossci-datasets.s3.amazonaws.com/mnist/t10k-images-idx3-ubyte.gz', '9fb629c4189551a2d022fa330f9573f3'), ('https://ossci-datasets.s3.amazonaws.com/mnist/t10k-labels-idx1-ubyte.gz', 'ec29112dd5afa0611ce80d1b7f02629c') ] root = '../data' if not os.path.exists(root): os.mkdir(root) train_set = datasets.MNIST(root=root, train=True, download=True) test_set = datasets.MNIST(root=root, train=False, download=True) X_train, X_valid = train_set.data.split([50000, 10000]) Y_train, Y_valid = train_set.targets.split([50000, 10000]) trace() return (X_train.view(50000, -1) / 256.0), Y_train.float(), (X_valid.view(10000, -1))/ 256.0, Y_valid.float() #x_train,y_train,x_valid,y_valid = get_data() #def get_data(): # path = datasets.download_data(MNIST_URL, ext='.gz') # with gzip.open(path, 'rb') as f: # ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1') # return map(tensor, (x_train,y_train,x_valid,y_valid)) def normalize(x, m, s): return (x-m)/s # + [markdown] id="SYm5W0QcGiQZ" # In the following, I will add mathematical description for the python statements that define the model and the gradients of the loss function with respect to the parameters (weights) of the neural net studied in this notebook. # # Please review what you studied in linear algebra or college math. This mathematical description of the neural net is an application of your basic knowledge of linear algebra. # Without the basic knowledge of linear algebra, that is, the # language of vectors, matrices, transformations, it is not possible to follow this course successfully. You need to spend time to review or study it. I provided good references in the cybercampus site. # # Note that sometimes, I will use variables different from the original notebook, for clarification and for the match with the mathematical description of the network. # # It is really important to be able to understand the mathematical description of the network for "machine learning from foundations". Much of this mathematical description will be the subject matter of the mid-term exam. # + colab={"base_uri": "https://localhost:8080/", "height": 703} id="NfmPbWZZ5-X0" outputId="59cf544a-3625-4d76-fcb5-58c2381a9e7d" X_train,Y_train,X_valid,Y_valid = get_data() # + colab={"base_uri": "https://localhost:8080/"} id="ik0tdaD_8-Ij" outputId="9008a671-9581-40fd-ebde-5fbf65f90d1e" len(X_train) # + id="8uUZyVF_wGvn" outputId="4ca75c3a-0fc1-4bb5-bf9c-a1f9c488185e" colab={"base_uri": "https://localhost:8080/"} Y_valid.shape # + [markdown] id="3vNHIGAOH0VS" # X_train is a set of input vectors to the neural net, represented as a matrix: # # X_train = \\ # $X = \begin{bmatrix} # x^{(1)} \\ \vdots \\ x^{(m)} # \end{bmatrix} # = # \begin{bmatrix} # x_{1}^{(1)} & \cdots & x_{n^{[0]}}^{(1)} \\ # \vdots & \cdots & \vdots \\ # x_{1}^{(m)} & \cdots & x_{n^{[0]}}^{(m)} # \end{bmatrix} # $ # # Here, the index in the parenthesis superfix 1 in $x^{(1)}$ means that input vector $x^{(1)}$ is from from data sample 1. The suffix 1 in $x_{1}^{(1)}$ means that $x_{1}^{(1)}$ is the first element of vector $x^{(1)}$. $m$ is the number of samples in the dataset: $m=50,000$. $n^{[0]}$ is the size of the input vector on the 0th layer: $n^{[0]}=784$. In the notebook, $n^{[0]}$ is written as $n0$. # # In summary, note that the input to the neural net for training is represented as a matrix x_train. In this representation, the rows of the matrix x_train refer to samples. Some software and papers represent X so that the columns of x_train refer to samples as follows: # # X_train \\ # $X = \begin{bmatrix} # x^{(1)} \cdots x^{(m)} # \end{bmatrix} # = # \begin{bmatrix} # x_{1}^{(1)} & \cdots & x_{1}^{(m)} \\ # \vdots & \cdots & \vdots \\ # x_{n^{[0]}}^{(1)} & \cdots & x_{n^{[0]}}^{(m)} # \end{bmatrix} # $ # + colab={"base_uri": "https://localhost:8080/"} id="1XGPCf8T9UjJ" outputId="c2e1505b-d6e3-4a1a-da8a-0e04654e865c" X_train[0].shape # + [markdown] id="VbILlqfJG7Er" # The number of nodes in the input layer = the size of the 0th layer = the size of the input vector, x, = 784 = 28 * 28 = x_train[0].shape. In the mathematical description of the network, I will use $n^{[0]}$ to refer to the size of the 0th layer: $n^{[0]}$ = 784. # + colab={"base_uri": "https://localhost:8080/"} id="xaZzISo_5-X1" outputId="b8ad1b64-d2df-4ebf-e66b-c9e83e7044de" train_mean,train_std = X_train.mean(),X_train.std() train_mean,train_std # + [markdown] id="I4Gu7BF3Chu8" # In this notebook, we construct a fully connected (FC) neural net with two layers, one hidden layer and the output layer. The input layer, considered the 0th layer, is not counted in the number of layers. # # The number of nodes in the hidden layer = the size of the hidden layer = 50. The number of nodes in the input layer = the size of the 0th layer = the size of the input vector, x, = 784 = 28 * 28. The number of nodes in the output layer = the size of the output layer = 1. In the mathematical description of the network, I will use $n^{[0]}$, $n^{[1]}$, $n^{[2]}$ to refer to the size of the 0th layer, the 1st layer, and the second layer, respectively. Hence we have: # # $n^{[0]}$ = 784, = $n^{[1]}$ = 50, $n^{[2]}$ =1. # # In the notebook, $n^{[0]}$, $n^{[1]}$, $n^{[2]}$ will be written as n0, n1, n2, respectively. # + id="S3nmN8UL5-X3" X_train = normalize(X_train, train_mean, train_std) # NB: Use training, not validation mean for validation set X_valid = normalize(X_valid, train_mean, train_std) # + colab={"base_uri": "https://localhost:8080/"} id="nCCqEllW5-X3" outputId="d7f90369-e03d-498c-8589-211bf81deda9" train_mean,train_std = X_train.mean(),X_train.std() train_mean,train_std # + id="6xBjabxA5-X4" #export def test_near_zero(a,tol=1e-3): assert a.abs()<tol, f"Near zero: {a}" # + id="vS8_j4lZ5-X4" test_near_zero(X_train.mean()) test_near_zero(1-X_train.std()) # + [markdown] id="N-awerTWNc63" # m is the number of samples in the dataset. # + colab={"base_uri": "https://localhost:8080/"} id="d_Dz6Z6YOQF9" outputId="c5180e95-9d7b-471a-a30c-81e446d4c8df" X_train.shape # + colab={"base_uri": "https://localhost:8080/"} id="pzgYF69T5-X5" outputId="0e7c027d-5ca7-4a94-fb6b-69789beece96" m, n0 = X_train.shape c = Y_train.max()+1 m,n0,c Y_train.max() # + [markdown] id="vagz-GZe5-X5" # ## Foundations version # + [markdown] id="pfeJZz_45-X5" # ### Basic architecture # + [markdown] id="NnJVOx2vBrpR" # # + [markdown] id="4kqnGdFs5-X6" # [Jump_to lesson 8 video](https://course.fast.ai/videos/?lesson=8&t=5128) # + [markdown] id="_wo4BvAdB57G" # # + id="WzFgW_Wi5-X6" # num hidden n1 = 50 # + [markdown] id="4_NV4eLQ5-X6" # [Tinker practice](https://course.fast.ai/videos/?lesson=8&t=5255) # + [markdown] id="W968ePvjRSoQ" # # # + [markdown] id="sYJAHMZ5aciZ" # # The definition of the first layer: # # The weighted sum (the first part of the node/neuron): # # Note that matrices are written in capital letters. # # $Z^{[1]} # = X W^{[1]} + b^{[1]}$ # # $ z^{[1](s)} # = x^{(s)} W^{[1]} + b^{[1]}, s=1,m = 50000$ # # # $\begin{bmatrix} # z^{[1](1)} \\ # \vdots \\ # z^{[1](m)} # \end{bmatrix} # $ = # $\begin{bmatrix} # z_{1}^{[1](1)} & \cdots & z_{n^{[1]}}^{[1](1)} \\ # \vdots & \cdots & \vdots \\ # z_{1}^{[1](m)} & \cdots & z_{n^{[1]}}^{[1](m)} # \end{bmatrix} # $ \\ # # # = # $\begin{bmatrix} # x_{1}^{(1)} & \cdots & x_{n^{[0]}}^{(1)} \\ # \vdots & \cdots & \vdots \\ # x_{1}^{(m)} & \cdots & x_{n^{[0]}}^{(m)} # \end{bmatrix} # $ # $ # \begin{bmatrix} # w_{11}^{[2]} & \cdots & w_{1n^{[1]}}^{[2]} \\ # \vdots & \cdots & \vdots \\ # w_{n^{[0]}1}^{[2]} & \cdots & w_{n^{[0]}n^{[1]}}^{[2]} \end{bmatrix} # $ \\ # # + # $ # \begin{bmatrix} # b_{1}^{[2]} & \cdots & b_{n^{[1]}}^{[2]} # \end{bmatrix} # $ # # = # $\begin{bmatrix} # x^{(1)} \cdot w_{\bullet 1}^{[2]} & \cdots & x^{(1)} \cdot w_{\bullet n^{[1]}}^{[2]} \\ # \vdots & \cdots & \vdots \\ # x^{(m)} \cdot w_{\bullet 1}^{[2]} & \cdots & # x^{(m)} \cdot w_{\bullet n^{[1]}}^{[2]} # \end{bmatrix} # $ # \\ # # + # $ # \begin{bmatrix} # b_{1}^{[2]} & \cdots & b_{n^{[1]}}^{[2]} # \end{bmatrix} # $ # # The activation (the second part of the node/neuron): # # $ # A^{[1]} # = g( Z^{[1]}) = g(X W^{[1]} + b^{[1]}) $ # # $ # \begin{bmatrix} # a^{[1](1)} \\ # \vdots \\ # a^{[1](m)} # \end{bmatrix} # =\begin{bmatrix} # a_{1}^{[1](1)} & \cdots & a_{n^{[1]}}^{[1](1)} \\ # \vdots & \cdots & \vdots \\ # a_{1}^{[1](m)} & \cdots & a_{n^{[1]}}^{[1](m)} # \end{bmatrix} # =\begin{bmatrix} # g(z_{1}^{[1](1)}) & \cdots & g(z_{n^{[1]}}^{[1](1)}) \\ # \vdots & \cdots & \vdots \\ # g(z_{1}^{[1](m)}) & \cdots & g(z_{n^{[1]}}^{[1](m)}) \end{bmatrix} # =\begin{bmatrix} # g(z^{[1](1)}) \\ # \vdots \\ # g(z^{[1](m)}) \end{bmatrix} # $ # # In our network, $g = relu$ # # # Here, the index in the square superfix 2 in $z^{[1](1)}$ means that the variable $z^{[1](1)}$ lives on the 1st layer of the network. # The index in the parenthesis superfix 1 in $z^{[1](1)}$ means that the variable $z^{[1](1)}$ is computed from data sample 1. The suffix 1 in # $z_{1}^{[1](1)}$ means that $z_{1}^{[1](1)}$ is the first element of vector $z^{[1](1)}$. $n^{[i]}$ is the number of the nodes (units or neurons) on the $i$-th layer. The 0th layer of the network refers to the input layer. # # # + [markdown] id="77kObYlhC3U1" # The definition of the 2nd layer. # # # # $ Z^{[2]} # = A^{[1]} W^{[2]} + b^{[2]}$ # # $ z^{[2](s)} # = a^{[1](s)} W^{[2]} + b^{[2]}, s=1,m = 50000$ # # # $\begin{bmatrix} # z_{1}^{[2](1)} & \cdots & z_{n^{[2]}}^{[2](1)} \\ # \vdots & \cdots & \vdots \\ # z_{1}^{[2](m)} & \cdots & z_{n^{[2]}}^{[2](m)} # \end{bmatrix} # $ \\ # # = # $\begin{bmatrix} # a_{1}^{(1)} & \cdots & a_{n^{[1]}}^{(1)} \\ # \vdots & \cdots & \vdots \\ # a_{1}^{(m)} & \cdots & a_{n^{[1]}}^{(m)} # \end{bmatrix} # $ # $ # \begin{bmatrix} # w_{11}^{[2]} & \cdots & w_{1n^{[2]}}^{[2]} \\ # \vdots & \cdots & \vdots \\ # w_{n^{[1]}1}^{[2]} & \cdots & w_{n^{[1]}n^{[2]}}^{[2]} \end{bmatrix} # $ \\ # # + # $ # \begin{bmatrix} # b_{1}^{[2]} & \cdots & b_{n^{[2]}}^{[2]} # \end{bmatrix} # $ # # # # # Here, the index in the square superfix 2 in $z^{[2](1)}$ means that the variable $z^{[2](1)}$ lives on the 2nd layer of the network. # The index in the parenthesis superfix 1 in $z^{[2](1)}$ means that the variable $z^{[2](1)}$ is computed from data sample 1. The suffix 1 in $z_{1}^{[2](1)}$ means that $z_{1}^{[2](1)}$ is the first element of vector $z^{[2](1)}$. # # # # In this notebook, the size of the second layer (the output layer), $n^{[2]}$ is 1. # There is only one node on the second layer, hence only one element in the output vector $z^{[2](i)}$ on the 2nd layer in our example neural net. # So we have: # # # $\begin{bmatrix} # z_{1}^{[2](1)} \\ # \vdots \\ # z_{1}^{[2](m)} # \end{bmatrix} # $ \\ # = # $\begin{bmatrix} # a_{1}^{[1](1)} & \cdots & a_{n^{[1]}}^{[1](1)} \\ # \vdots & \cdots & \vdots \\ # a_{1}^{(m)} & \cdots & a_{n^{[1]}}^{[1](m)} # \end{bmatrix} # $ # $ # \begin{bmatrix} # w_{11}^{[2]} \\ # \vdots \\ # w_{n^{[1]}1}^{[2]} # \end{bmatrix} # $ \\ # + # $ # \begin{bmatrix} # b_{1}^{[2]} # \end{bmatrix} # $ \\ # # In general, there are more than one elements in the output vector. # + [markdown] id="WObdO6AgT19v" # In the above, the description of the 1st layer # # $ z^{[1](s)} # = x^{(s)} W^{[1]} + b^{[1]}$ # # assumes that input vector $x^{{s)}$ is written a row vector. # In this case, the vectors in all the layers are considered as row vectors. # # Other people often write it as a column vector as follows: # # # x_train \\ # $= \begin{bmatrix} # x^{(1)} \cdots x^{(m)} # \end{bmatrix} # = # \begin{bmatrix} # x_{1}^{(1)} & \cdots & x_{1}^{(m)} \\ # \vdots & \cdots & \vdots \\ # x_{n^{[0]}}^{(1)} & \cdots & x_{n^{[0]}}^{(m)} # \end{bmatrix} # $ # # In this case, the description of the 1st layer is written as: # # $ z^{[1](s)} # = W^{[1]} x^{(s)} + b^{[1]}$ # # Also, the vectors on the other layers are considered as column vectors. The conversion from one description to another can obtained by transposing the equation: # # $ {z^{[1](s)}}^{T} # = ( x^{(s)} W^{[1]} ) ^{T} + {b^{[1]}}^{T} # = {W^{[1]}}^{T} {x^{(s)}}^{T} + { b^{[1]}}^{T} # $ # + [markdown] id="F6_hSGCpa2ep" # # + [markdown] id="86MGtdAGg_M3" # To train the neural net means to determine the values of the weights $W^{[1]}, W^{[2]}$ and biases $b^{[1]}, b^{[2]}$, so that the loss function L ($W^{[1]}, W^{[2]}$, $b^{[1]}, b^{[2]}$) is minimized. To do so, we need to initialize them to random numbers chosen appropriately, as follows: # # Note that in the noteboo, $W^{[1]}, W^{[2]}, b^{[1]}, b^{[2]}, A ^{[1]} $ are written as W1, W2, b1, b2, A1. # + id="8Xzlvhy25-X7" # simplified kaiming He init W1 = torch.randn(n0,n1)/math.sqrt(n0) # n0 is the size of the input vector x, n1 is the number of nodes in the 1st layer b1 = torch.zeros(n1) W2 = torch.randn(n1,1)/math.sqrt(n1) # 1 is the number of nodes in the second layer (the output layer) b2 = torch.zeros(1) # + id="e-jtQUbI5-X8" test_near_zero(w1.mean()) test_near_zero(w1.std()-1/math.sqrt(m)) # + colab={"base_uri": "https://localhost:8080/"} id="rBjo8r7O5-X9" outputId="a1f3ed40-33b7-45ac-89b2-d12d1edb7b4a" # This should be ~ (0,1) (mean,std)... X_valid.mean(),X_valid.std() # + [markdown] id="c8dIv9H2k3Iy" # Function lin() is used to compute # # $ Z^{[2]} # = A^{[1]} W^{[2]} + b^{[2]}$ and $ Z^{[1]} # = X W^{[1]} + b^{[1]}$ # + id="6T6Hp_oM5-X-" def lin(X, W, b): return X@W + b # + id="u-faJxX55-X_" Z1 = lin(X_valid, W1, b1) # + colab={"base_uri": "https://localhost:8080/"} id="p4LwFw7dY3eF" outputId="71764368-76d7-4d4b-a9aa-33a4484ac030" X_valid.shape # + colab={"base_uri": "https://localhost:8080/"} id="Uj2llJ7b5-X_" outputId="052996e6-2bc9-4616-caaa-dadd95915fc8" #...so should this, because we used kaiming init, which is designed to do this Z1.mean(),Z1.std() # + id="8yANZFMz5-YB" def relu(Z): return Z.clamp_min(0.) # + id="Fk5_q7ld5-YC" Z1 = lin(X_valid, W1, b1) A1 = relu( Z1 ) # + colab={"base_uri": "https://localhost:8080/"} id="Iv7GQ0c45-YC" outputId="b7f05a51-e54c-4c1c-df10-e149d7840fb9" #...actually it really should be this! A1.mean(),A1.std() # + [markdown] id="-tGq6Sta5-YD" # From pytorch docs: `a: the negative slope of the rectifier used after this layer (0 for ReLU by default)` # # $$\text{std} = \sqrt{\frac{2}{(1 + a^2) \times \text{fan_in}}}$$ # # This was introduced in the paper that described the Imagenet-winning approach from *He et al*: [Delving Deep into Rectifiers](https://arxiv.org/abs/1502.01852), which was also the first paper that claimed "super-human performance" on Imagenet (and, most importantly, it introduced resnets!) # + [markdown] id="5pqJ9i9m5-YD" # [Jump_to lesson 8 video](https://course.fast.ai/videos/?lesson=8&t=5128) # + id="09FOdeFH5-YD" # kaiming init / he init for relu W1 = torch.randn(n0,n1)*math.sqrt(2/n0) # + colab={"base_uri": "https://localhost:8080/"} id="-ePZ4wD15-YE" outputId="bba87de9-e0f5-4601-ace0-6aaf8d9dddd0" W1.mean(),W1.std() # + colab={"base_uri": "https://localhost:8080/"} id="bJdmqNag5-YE" outputId="94e2f40e-b4b1-46e1-8eb1-f4c26ac12886" Z1 = lin(X_valid, W1, b1) A1 = relu( Z1) A1.mean(),A1.std() # + id="r8O1NjrC5-YF" #export from torch.nn import init # + id="OjXu4Gq05-YF" W1 = torch.zeros(n0,n1) init.kaiming_normal_(W1, mode='fan_out') A1 = relu(lin(X_valid, W1, b1)) # + id="C8Thp0YVo3as" colab={"base_uri": "https://localhost:8080/"} outputId="eb9d1ea4-44c7-49a4-e753-13009af5df08" W1.shape # + id="mhCoytJqpK5i" colab={"base_uri": "https://localhost:8080/"} outputId="9891ee43-f3a9-4ad3-aeb5-4d76c5dfd0a3" W1.t().shape # + id="5jETx2oR5-YF" # init.kaiming_normal_?? # + colab={"base_uri": "https://localhost:8080/"} id="nJDqDh6l5-YF" outputId="20440b84-5300-4eb5-8e6c-0c1e1dc9b943" W1.mean(),W1.std() # + colab={"base_uri": "https://localhost:8080/"} id="WqoOHNXn5-YG" outputId="93a8e468-e943-4d9b-af4f-cfb41710156c" A1.mean(),A1.std() # + colab={"base_uri": "https://localhost:8080/"} id="Wv7oXXVO5-YG" outputId="8571560d-b44e-4aa6-80af-9aab121ecf3d" W1.shape # + id="J0Tg2Uq15-YG" import torch.nn # + id="XzfYmlPYpfx_" colab={"base_uri": "https://localhost:8080/"} outputId="88849bec-0c6f-4559-8021-3c25f805ed00" X_valid[0].shape # + colab={"base_uri": "https://localhost:8080/"} id="oRgE733i5-YH" outputId="ba179788-395a-4cdc-a210-48730411400c" torch.nn.Linear(n0,n1).weight.shape # + id="m9_aH0It5-YH" # torch.nn.Linear.forward?? # + id="vjHq6PoH5-YH" # torch.nn.functional.linear?? # + id="0VsxXtMp5-YI" # torch.nn.Conv2d?? # + id="EDFhDvI-5-YI" # torch.nn.modules.conv._ConvNd.reset_parameters?? # + id="RDZaD2dA5-YI" # what if...? def relu(Z): return Z.clamp_min(0.) - 0.5 # + colab={"base_uri": "https://localhost:8080/"} id="3jNw_L-B5-YI" outputId="1d862192-83ae-48ff-f98e-0161e8707fca" # kaiming init / he init for relu W1 = torch.randn(n0,n1)*math.sqrt(2./n0 ) A1 = relu(lin(X_valid, W1, b1)) A1.mean(),A1.std() # + [markdown] id="7IJ5e9X-xT2a" # function model(X) computes the output of the neural net Z2 such that # # $ Z^{[2]} # = A^{[1]} W^{[2]} + b^{[2]}$ # # $ Z^{[1]} # = X W^{[1]} + b^{[1]}$ # + id="NhvenibH5-YJ" def model(X): Z1 = lin(X, W1, b1) #print ("Z1=", Z1) A1= relu(Z1) #print ("A1 = ", A1) Z2= lin(A1, W2, b2) #print ("Z2 = ", Z2) return Z2 # + id="DU5VFUTBG8uU" Z2=model(X_valid[:2]) # + id="C1c1X6Wu5-YJ" # %timeit -n 10 _=model(X_valid[0]) # + id="O9SoPoSl5-YJ" assert model(X_valid).shape==torch.Size([X_valid.shape[0],1]) # + [markdown] id="LlyflLbC5-YK" # ### Loss function: MSE # + [markdown] id="QMKbmGY_5-YK" # [Jump_to lesson 8 video](https://course.fast.ai/videos/?lesson=8&t=6372) # + [markdown] id="0BQsZ2xW5-YK" # We need `squeeze()` to get rid of that trailing (,1), in order to use `mse`. (Of course, `mse` is not a suitable loss function for multi-class classification; we'll use a better loss function soon. We'll use `mse` for now to keep things simple.) # + [markdown] id="2SoqHuMr9Xgq" # # # + [markdown] id="bOEHIG5gLe7D" # # + [markdown] id="FcQxM1bBK4SZ" # # + [markdown] id="bRf_q9JzNngt" # The loss function $L$: # # # $L = \frac{1}{m}\sum_{s=1}^{m}(z^{[2](s)} - y^{(s)}) # \cdot(z^{[2](s)} - y^{(s)}) # $ \\ # # $ z^{[2](s)} # = a^{[1](s)} W^{[2]} + b^{[2]}$ # # $ a^{[1](s)} = g( z^{[1](s)} )$ # # $ z^{[1](s)} # = x^{(s)} W^{[1]} + b^{[1]}$ # # # Here, $Y\_train$ # $ # = \begin{bmatrix} # y^{(1)} \\ # \vdots \\ # y^{(m)} # \end{bmatrix} # $ # # # Now to train the neural net, we need to compute the following gradient matrices of $L$: # # $\frac{\partial L}{\partial W^{[2]}} = \left[ \frac{\partial L}{\partial w_{ij}^{[2]}} \right]$ \\ # $\frac{\partial L}{\partial b^{[2]}} = \left[ \frac{\partial L}{\partial b_{i}^{[2]}} \right]$ \\ # $\frac{\partial L}{\partial W^{[1]}} = \left[ \frac{\partial L}{\partial w_{ij}^{[1]}} \right]$ # \\ # $\frac{\partial L}{\partial b^{[1]}} = \left[ \frac{\partial L}{\partial b_{i}^{[1]}} \right]$ # # # # # # + [markdown] id="OnRnvwOFMd5O" # # # # # $\frac{\partial L}{\partial W^{[2]}} # = \left[ \frac{\partial L}{ \partial w_{ij}^{[2]} } \right]$ # # $ \frac{\partial L}{ \partial w_{ij}^{[2]} } # = \frac{1}{m}\sum_{s=1}^{2m} # \frac{\partial L} {\partial z^{[2](s)}} # \frac{\partial z^{[2](s)} }{\partial w_{ij}^{[2]} } # $ # # $ # \frac{\partial L}{\partial z^{[2](s)} } =2*(z^{[2](s)} - y^{(s)}) # $ # # $\frac{\partial L} {\partial z^{[2](s)}}\frac{\partial z^{[2](s)} }{\partial w_{ij}^{[2]} } # = \sum_{k=1}^{n^{[2]}} \frac{\partial L}{\partial z_{k}^{[2](s)} } \frac{\partial z_{k}^{[2](s)} }{\partial w_{ij}^{[2]} } \\ # = # \sum_{k=1}^{n^{[2]}} \frac{\partial L}{\partial z_{k}^{[2](s)} } \frac{ \partial \sum_{l=1}^{n^{[1]}} a_{l} ^{[1](s)} w_{lk}^{[2]} }{\partial w_{ij}^{[2]} } # = \sum_{k=1}^{n^{[2]}} \frac{\partial L}{\partial z_{k}^{[2](s)} } \frac{ \sum_{l=1}^{n^{[1]}} a_{l} ^{[1](s)} \partial w_{lk}^{[2]} }{\partial w_{ij}^{[2]} } # = \frac{\partial L}{\partial z_{j}^{[2](s)} } \frac{ a_{i} ^{[1](s)} \partial w_{ij}^{[2]} }{\partial w_{ij}^{[2]} } # = \frac{\partial L}{\partial z_{j}^{[2](s)} } a_{i}^{[1](s)} # $ # # $\frac{\partial L}{\partial W^{[2]}} # = \left[ \frac{\partial L}{ \partial w_{ij}^{[2]} } \right] # = \left[ \frac{1}{m}\sum_{s=1}^{m} a_{i}^{[1](s)} \frac{\partial L}{\partial z_{j}^{[2](s)} } \right] \\ # = \frac{1}{m}\sum_{s=1}^{m} \left[ a_{i}^{[1](s)} \frac{\partial L}{\partial z_{j}^{[2](s)} } \right] # = \frac{1}{m}\sum_{s=1}^{m} a^{[1](s)^{T}} \frac{\partial L}{\partial z^{[2](s)} }$ # # + [markdown] id="A4zu7A1nWnji" # $\frac{\partial L}{\partial b^{[2]}} # = \frac{\partial L}{\partial Z^{[2]}} \frac{\partial Z^{[2]}}{\partial b^{[2]}} \\ # =\frac{1}{m}\sum_{s=1}^{m} # \frac{\partial L^{(s)}} {\partial z^{[2](s)}} # \frac{\partial z^{[2](s)}}{\partial b^{[2]}} # =\frac{1}{m}\sum_{s=1}^{m} # \frac{\partial L^{(s)}} {\partial z^{[2](s)}} # $ # # # # + [markdown] id="6z60uMeDv5GR" # # + [markdown] id="34KVl_8bbr8k" # # $L = \frac{1}{m}\sum_{s=1}^{m}(z^{[2](s)} - y^{(s)}) # \cdot(z^{[2](s)} - y^{(s)}) # $ # # $\frac{\partial L}{\partial W^{[1]}} # = \left[ \frac{\partial L}{ \partial w_{ij}^{[1]} } \right]$ # # $ \frac{\partial L}{ \partial w_{ij}^{[1]} } # = \frac{1}{m}\sum_{s=1}^{m} # \frac{\partial L} {\partial z^{[1](s)}} # \frac{\partial z^{[1](s)} }{\partial w_{ij}^{[1]} } \\ # $ # # # # $\frac{\partial L} {\partial z^{[1](s)}} # = \frac{\partial L}{\partial a^{[1](s)}} # \frac{\partial a^{[1](s)}} {\partial z^{[1](s)}} # = \frac{\partial L} {\partial z^{[2](s)}} # \frac{\partial z^{[2](s)}} {\partial a^{[1](s)}} # \frac{\partial a^{[1](s)}} {\partial z^{[1](s)}} # $ # # # $ # \frac{\partial L}{\partial z^{[2](s)} } =2*(z^{[2](s)} - y^{(s)}) # $ # # $ z^{[2](s)} # = a^{[1](s)} W^{[2]} + b^{[2]}$ # # $ a^{[1](s)} = g( z^{[1](s)} )$ # # $ z^{[1](s)} # = x^{(s)} W^{[1]} + b^{[1]}$ # # $ # \frac{\partial z^{[2](s)}} {\partial a^{[1](s)}} # = {W^{[2]}}^{T} # $ # # $ \frac{\partial a^{[1](s)}}{\partial z^{[1](s)}} # =\frac{\partial relu(z^{[1](s)} ) } {\partial z^{[1](s)}} # = diag( sgn ( relu'(z^{[1](s)} ) ) ) # $ # # Here, # # $ sgn( x) = 1$ if $x > 0$, $0$ otherwise. # # $\frac{\partial L} {\partial z^{[1](s)}} # =\frac{\partial L}{\partial a^{[1](s)}} # \frac{\partial a^{[1](s)}} {\partial z^{[1](s)}} # = # (\frac{\partial L} {\partial z^{[2](s)}} # \frac{\partial z^{[2](s)}} {\partial a^{[1](s)}} ) # \frac{\partial a^{[1](s)}} {\partial z^{[1](s)}} \\ # = ( 2*(z^{[2](s)} - y^{(s)}) {W^{[2]}}^{T} ) \odot # sgn( relu'( z^{[1](s)} ) ) # $ # # $\frac{\partial L} {\partial z^{[1](s)}}\frac{\partial z^{[1](s)} }{\partial w_{ij}^{[1]} } # = \sum_{k=1}^{n^{[1]}} \frac{\partial L}{\partial z_{k}^{[1](s)} } \frac{\partial z_{k}^{[1](s)} }{\partial w_{ij}^{[1]} } \\ # = # \sum_{k=1}^{n^{[1]}} \frac{\partial L^{(s)}}{\partial z_{k}^{[1](s)} } \frac{ \partial \sum_{l=1}^{n^{[1]}} x_{l} ^{(s)} w_{lk}^{[1]} }{\partial w_{ij}^{[1]} } # = \sum_{k=1}^{n^{[1]}} \frac{\partial L}{\partial z_{k}^{[1](s)} } \frac{ \sum_{l=1}^{n^{[1]}} x_{l} ^{(s)} \partial w_{lk}^{[1]} }{\partial w_{ij}^{[1]} } \\ # = \frac{\partial L}{\partial z_{j}^{[1](s)} } \frac{ x_{i} ^{(s)} \partial w_{ij}^{[1]} }{\partial w_{ij}^{[1]} } # = \frac{\partial L}{\partial z_{j}^{[1](s)} } x_{i}^{(s)} # $ # # $\frac{\partial L}{\partial W^{[1]}} # = \left[ \frac{\partial L}{ \partial w_{ij}^{[1]} } \right] # = \left[ \frac{1}{m}\sum_{s=1}^{m} x_{i}^{(s)} \frac{\partial L}{\partial z_{j}^{[1](s)} } \right] \\ # = \frac{1}{m}\sum_{s=1}^{m} \left[ x_{i}^{(s)} \frac{\partial L}{\partial z_{j}^{[1](s)} } \right] # = \frac{1}{m}\sum_{s=1}^{m} x^{(s)^{T}} \frac{\partial L}{\partial z^{[1](s)} } # $ # # + [markdown] id="6g3pESYSbrU0" # $\frac{\partial L}{\partial b^{[1]}} # = \frac{1}{m}\frac{\partial L}{\partial b^{[1]}} # =\frac{1}{m}\sum_{s=1}^{m} # \frac{\partial L} {\partial z^{[1](s)}} # \frac{\partial z^{[1](s)}}{\partial b^{[1]}} \\ # =\frac{1}{m}\sum_{s=1}^{m} # \frac{\partial L} {\partial z^{[2](s)}} # \frac{\partial z^{[2](s)}} {\partial a^{[1](s)}} # \frac{\partial a^{[1](s)}} {\partial z^{[1](s)}} I \\ # =\frac{1}{m}\sum_{s=1}^{m} # \frac{\partial L} {\partial z^{[2](s)}} # {W^{[2]}}^{T} # diag( \frac{\partial relu} {\partial z^{[1](s)}} )\\ # =\frac{1}{m}\sum_{s=1}^{m} # \frac{\partial L} {\partial z^{[2](s)}} # {W^{[2]}}^{T} \odot \frac{\partial relu} {\partial z^{[1](s)}} # $ # # + [markdown] id="MvvFiiM6H3DI" # # # + [markdown] id="jjkKEwU1Hsci" # # # + [markdown] id="fQGc9Mb0Hyij" # # + [markdown] id="lX8wDzNtt7vB" # mse() function computes and returns the value of the loss function L: # # $L (Z2, Y) = \frac{1}{m}\sum_{s=1}^{m}(z^{[2](s)} - y^{(s)}) # \cdot(z^{[2](s)} - y^{(s)}) \\ # $ # # + id="eOU_T3Lc5-YL" #export def mse(Z2, Y_train): return (Z2.squeeze(-1) - Y_train).pow(2).mean() # + id="HkGRdw8y5-YL" Y_train,Y_valid = Y_train.float(),Y_valid.float() # + id="hakvToYZ5-YL" Z2 = model(X_train) # + id="kjWh0D-pdEfR" # + id="RV1dQvJm5-YM" loss = mse(Z2, y_train) # + [markdown] id="9G-jJnb45-YM" # ### Gradients and backward pass # + [markdown] id="XpgdxO7D5-YM" # [Jump_to lesson 8 video](https://course.fast.ai/videos/?lesson=8&t=6493) # + [markdown] id="okIIqki9zN0B" # $L = \frac{1}{m}\sum_{s=1}^{m}(z^{[2](s)} - y^{(s)}) # \cdot(z^{[2](s)} - y^{(s)})$ # # Compute the gradient of $L$ with respect to $Z^{[2]}$: # # $ \frac{ \partial L }{ \partial Z^{[2]} } # = \begin{bmatrix} # \frac{ \partial L }{ \partial z^{[2](1)} } \\ # \vdots \\ # \frac{ \partial L }{ \partial z^{[2](m)} } # \end{bmatrix} # $ # # $ # \frac{\partial L}{\partial z^{[2](s)} } =2*(z^{[2](s)} - y^{(s)}) / m # $ # + id="eQVon0G75-YN" def mse_grad(Z2, Y_train): # compute the grad of loss L with respect to Z2 and store it in Z2.g #print (inp.g.shape) # tensor x_train is given a new field that contains its gradient relative y_hat m = Z2.shape[0] # the number of rows in Z2 Z2.g = 2. * (Z2.squeeze() - Y_train).unsqueeze(-1) / m # + [markdown] id="w049dquY8d3_" # $ \frac{\partial a^{[1](s)}}{\partial z^{[1](s)}} # =\frac{\partial relu(z^{[1](s)} ) } {\partial z^{[1](s)}} # = diag( sgn ( relu'(z^{[1](s)} ) ) ) # $ # # Here, # # $ sgn( x) = 1$ if $x > 0$, $0$ otherwise. # # Represent the diagonal matrix # $diag( sgn ( relu'(z^{[1](s)} ) ) )$ as a vector $sgn ( relu'(z^{[1](s)} ) )$. # # # # + id="L6uuYz5k5-YP" def relu_grad(Z1, A1): # grad of the activation, relu, with respect to Z1, and store it in Z1.g Z1.g = (Z1>0).float() * A1.g # + [markdown] id="KJnS7K7RAbny" # Function lin_grad2(A1, Z2, W2, b2) computes three gradients as follows: # # (1) $ # \frac{\partial L}{\partial a^{[1](s)}} # =(\frac{\partial L} {\partial z^{[2](s)}} # \frac{\partial z^{[2](s)}} {\partial a^{[1](s)}} ) # = ( 2*(z^{[2](s)} - y^{(s)}) {W^{[2]}}^{T} )$ # # It will be used to compute the following gradient later: # # $\frac{\partial L} {\partial z^{[1](s)}} # =\frac{\partial L}{\partial a^{[1](s)}} # \frac{\partial a^{[1](s)}} {\partial z^{[1](s)}} # = # (\frac{\partial L} {\partial z^{[2](s)}} # \frac{\partial z^{[2](s)}} {\partial a^{[1](s)}} ) # \frac{\partial a^{[1](s)}} {\partial z^{[1](s)}} \\ # = ( 2*(z^{[2](s)} - y^{(s)}) {W^{[2]}}^{T} ) \odot # sgn( relu'( z^{[1](s)} ) ) # $ # # (2) # $\frac{\partial L}{\partial W^{[2]}} # = \left[ \frac{\partial L^{(s)}}{ \partial w_{ij}^{[2]} } \right] # = \left[ \frac{1}{m}\sum_{s=1}^{m} a_{i}^{[1](s)} \frac{\partial L^{(s)}}{\partial z_{j}^{[2](s)} } \right] \\ # = \frac{1}{m}\sum_{s=1}^{m} \left[ a_{i}^{[1](s)} \frac{\partial L^{(s)}}{\partial z_{j}^{[2](s)} } \right] # = \sum_{s=1}^{m} a^{[1](s)^{T}} \frac{1}{m}\frac{\partial L^{(s)}}{\partial z^{[2](s)} }$ # # (3) # $\frac{\partial L}{\partial b^{[2]}} # = \frac{\partial L}{\partial Z^{[2]}} \frac{\partial Z^{[2]}}{\partial b^{[2]}} \\ # =\frac{1}{m}\sum_{s=1}^{m} # \frac{\partial L^{(s)}} {\partial z^{[2](s)}} # \frac{\partial z^{[2](s)}}{\partial b^{[2]}} # =\frac{1}{m}\sum_{s=1}^{m} # \frac{\partial L^{(s)}} {\partial z^{[2](s)}} # $ # + id="omBAYDnh5-YP" def lin_grad2(A1, Z2, W2, b2): # grad of L with respect to A1 A1.g = Z2.g @ W2.t() # grad of L with respect to W2 W2.g = (A1.unsqueeze(-1) * Z2.g.unsqueeze(1)).sum(0) # grad of L with respect to b2 b2.g = Z2.g.sum(0) # + id="nhil8iIu_3GK" def lin_grad1(X, Z1, W1, b1): # grad of L with respect to X X.g = Z1.g @ W1.t() # grad of L with respect to W1 W1.g = (X.unsqueeze(-1) * Z1.g.unsqueeze(1)).sum(0) # grad of L with respect to b1 b1.g = Z1.g.sum(0) # + id="QubdDuqC5-YP" def forward_and_backward(X_train, Y_train): # forward pass: Z1 = X_train @ W1 + b1 # Z1 is a matrix A1 = relu(Z1) # A1 is a matrix Z2 = A1 @ W2 + b2 # Z2 is a matrix # we don't actually need the loss in backward! loss = mse(Z2, Y_train) # backward pass: # compute the gradient of the loss L with respect to Z2 and store it in Z2.g mse_grad(Z2, Y_train) # compute the gradient of Z2 with respect to A1, and store it in A1.g lin_grad2(A1, Z2, W2, b2) # xf. Z2 = A1 @ W2 + b2 relu_grad(Z1, A1) # cf. A1 = relu(A1) lin_grad1(X_train, Z1, W1, b1) #cf. Z1 = X_train @ W1 + b1 # + colab={"base_uri": "https://localhost:8080/", "height": 164} id="oEh55i9J5-YQ" outputId="7fc000f7-9736-445b-88d8-968d18c79b7d" forward_and_backward(X_train, Y_train) # + id="I9vfp9Gd5-YQ" # Save for testing against later w1g = w1.g.clone() w2g = w2.g.clone() b1g = b1.g.clone() b2g = b2.g.clone() ig = x_train.g.clone() # + [markdown] id="7axjYSJd5-YQ" # We cheat a little bit and use PyTorch autograd to check our results. # + id="rflckM445-YR" xt2 = x_train.clone().requires_grad_(True) w12 = w1.clone().requires_grad_(True) w22 = w2.clone().requires_grad_(True) b12 = b1.clone().requires_grad_(True) b22 = b2.clone().requires_grad_(True) # + id="xkMyi0E75-YS" def forward(inp, targ): # forward pass: l1 = inp @ w12 + b12 l2 = relu(l1) out = l2 @ w22 + b22 # we don't actually need the loss in backward! return mse(out, targ) # + id="-sW2yU7c5-YS" loss = forward(xt2, y_train) # + id="jdIyWWhL5-YT" loss.backward() # + id="32fqWKXq5-YT" test_near(w22.grad, w2g) test_near(b22.grad, b2g) test_near(w12.grad, w1g) test_near(b12.grad, b1g) test_near(xt2.grad, ig ) # + [markdown] id="60sY6g9A5-YT" # ## Refactor model # + [markdown] id="QqwIwiob5-YU" # ### Layers as classes # + [markdown] id="ujwhx_1x5-YU" # [Jump_to lesson 8 video](https://course.fast.ai/videos/?lesson=8&t=7112) # + id="5MozUwDh5-YU" class Relu(): def __call__(self, inp): self.inp = inp self.out = inp.clamp_min(0.)-0.5 return self.out def backward(self): self.inp.g = (self.inp>0).float() * self.out.g # + id="qzMZHFNE5-YV" class Lin(): def __init__(self, w, b): self.w,self.b = w,b def __call__(self, inp): self.inp = inp self.out = inp@self.w + self.b return self.out def backward(self): self.inp.g = self.out.g @ self.w.t() # Creating a giant outer product, just to sum it, is inefficient! self.w.g = (self.inp.unsqueeze(-1) * self.out.g.unsqueeze(1)).sum(0) self.b.g = self.out.g.sum(0) # + id="Dxirmfwb5-YW" class Mse(): def __call__(self, inp, targ): self.inp = inp self.targ = targ self.out = (inp.squeeze() - targ).pow(2).mean() return self.out def backward(self): self.inp.g = 2. * (self.inp.squeeze() - self.targ).unsqueeze(-1) / self.targ.shape[0] # + id="w1guaMoQ5-YW" class Model(): def __init__(self, w1, b1, w2, b2): self.layers = [Lin(w1,b1), Relu(), Lin(w2,b2)] self.loss = Mse() def __call__(self, x, targ): for l in self.layers: x = l(x) return self.loss(x, targ) def backward(self): self.loss.backward() for l in reversed(self.layers): l.backward() # + id="MorGG1Qu5-YX" w1.g,b1.g,w2.g,b2.g = [None]*4 model = Model(w1, b1, w2, b2) # + id="5Ol-P22k5-YX" outputId="8667281f-5364-42f3-e6d7-cc3dc4cba27b" # %time loss = model(x_train, y_train) # + id="NSbKFUYs5-YY" outputId="0609b104-6440-4cda-9fec-bd1228012d19" # %time model.backward() # + id="V7BfDx_v5-YY" test_near(w2g, w2.g) test_near(b2g, b2.g) test_near(w1g, w1.g) test_near(b1g, b1.g) test_near(ig, x_train.g) # + [markdown] id="cmCmOpUo5-YY" # ### Module.forward() # + id="IcdPHsTz5-YY" class Module(): def __call__(self, *args): self.args = args self.out = self.forward(*args) return self.out def forward(self): raise Exception('not implemented') def backward(self): self.bwd(self.out, *self.args) # + id="C1yFJbHU5-YZ" class Relu(Module): def forward(self, inp): return inp.clamp_min(0.)-0.5 def bwd(self, out, inp): inp.g = (inp>0).float() * out.g # + id="3XcYzhPO5-Ya" class Lin(Module): def __init__(self, w, b): self.w,self.b = w,b def forward(self, inp): return inp@self.w + self.b def bwd(self, out, inp): inp.g = out.g @ self.w.t() self.w.g = torch.einsum("bi,bj->ij", inp, out.g) self.b.g = out.g.sum(0) # + id="16qFhJ2q5-Ya" class Mse(Module): def forward (self, inp, targ): return (inp.squeeze() - targ).pow(2).mean() def bwd(self, out, inp, targ): inp.g = 2*(inp.squeeze()-targ).unsqueeze(-1) / targ.shape[0] # + id="KLFSVnB35-Yb" class Model(): def __init__(self): self.layers = [Lin(w1,b1), Relu(), Lin(w2,b2)] self.loss = Mse() def __call__(self, x, targ): for l in self.layers: x = l(x) return self.loss(x, targ) def backward(self): self.loss.backward() for l in reversed(self.layers): l.backward() # + id="_Ut8ItyX5-Yb" w1.g,b1.g,w2.g,b2.g = [None]*4 model = Model() # + id="fm9UYns25-Yc" outputId="cc6e3863-3528-4eac-abb4-256170a46510" # %time loss = model(x_train, y_train) # + id="cJg2fbgu5-Yd" outputId="0d4d4559-9444-4842-dc52-a1417479f2db" # %time model.backward() # + id="MMVSU5vX5-Yf" test_near(w2g, w2.g) test_near(b2g, b2.g) test_near(w1g, w1.g) test_near(b1g, b1.g) test_near(ig, x_train.g) # + [markdown] id="T7CoEs8B5-Yf" # ### Without einsum # + [markdown] id="9Jkbry0n5-Yg" # [Jump_to lesson 8 video](https://course.fast.ai/videos/?lesson=8&t=7484) # + id="BRMk9VkP5-Yg" class Lin(Module): def __init__(self, w, b): self.w,self.b = w,b def forward(self, inp): return inp@self.w + self.b def bwd(self, out, inp): inp.g = out.g @ self.w.t() self.w.g = inp.t() @ out.g self.b.g = out.g.sum(0) # + id="WYeUhw3_5-Yg" w1.g,b1.g,w2.g,b2.g = [None]*4 model = Model() # + id="xSLm1_Zp5-Yh" outputId="3b74f240-655a-44b9-d049-022bdb0a1646" # %time loss = model(x_train, y_train) # + id="b1awZuZK5-Yi" outputId="8398f297-2821-4184-cb70-f4c9db64ef10" # %time model.backward() # + id="Wil2jhwW5-Yj" test_near(w2g, w2.g) test_near(b2g, b2.g) test_near(w1g, w1.g) test_near(b1g, b1.g) test_near(ig, x_train.g) # + [markdown] id="NjABxzup5-Yj" # ### nn.Linear and nn.Module # + id="7aBlWkwq5-Yj" #export from torch import nn # + id="ulk-yUVr5-Yj" class Model(nn.Module): def __init__(self, n_in, nh, n_out): super().__init__() self.layers = [nn.Linear(n_in,nh), nn.ReLU(), nn.Linear(nh,n_out)] self.loss = mse def __call__(self, x, targ): for l in self.layers: x = l(x) return self.loss(x.squeeze(), targ) # + id="sc8BGGYn5-Yk" model = Model(m, nh, 1) # + id="Yk8W6T6I5-Yk" outputId="668ca663-ddb9-483a-f76d-91bb03b28a72" # %time loss = model(x_train, y_train) # + id="EABCQagY5-Yk" outputId="f0137715-96df-421e-e29d-f701af6fd440" # %time loss.backward() # + [markdown] id="GDFieAnU5-Yl" # ## Export # + id="QN1RejcK5-Yl" outputId="db0e0d34-cc63-4ad1-9acb-7e52779b91c9" # !./notebook2script.py 02_fully_connected.ipynb # + id="0Bdw2pYJ5-Yl"
nbs/dl2/02_moon_fully_connected.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib inline # # Auto-scheduling Matrix Multiplication for CPU # ============================================= # **Author**: `<NAME> <https://github.com/merrymercy>`_, `<NAME> <https://github.com/jcf94/>`_ # # This is a tutorial on how to use the auto-scheduler for CPUs. # # Different from the template-based `autotvm <tutorials-autotvm-sec>` which relies on # manual templates to define the search space, the auto-scheduler does not require any templates. # Users only need to write the computation declaration without any schedule commands or templates. # The auto-scheduler can automatically generate a large search space and # find a good schedule in the space. # # We use matrix multiplication as an example in this tutorial. # # Note that this tutorial will not run on Windows or recent versions of macOS. To # get it to run, you will need to wrap the body of this tutorial in a :code:`if # __name__ == "__main__":` block. # # + import os import numpy as np import tvm from tvm import te, auto_scheduler # - # Define the computation # ^^^^^^^^^^^^^^^^^^^^^^ # To begin with, let us define the computation of a matmul with bias add. # The function should return the list of input/output tensors. # From these tensors, the auto-scheduler can get the whole computational graph. # # @auto_scheduler.register_workload def matmul_add(N, L, M, dtype): A = te.placeholder((N, L), name="A", dtype=dtype) B = te.placeholder((L, M), name="B", dtype=dtype) C = te.placeholder((N, M), name="C", dtype=dtype) k = te.reduce_axis((0, L), name="k") matmul = te.compute( (N, M), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k), name="matmul", attrs={"layout_free_placeholders": [B]}, # enable automatic layout transform for tensor B ) out = te.compute((N, M), lambda i, j: matmul[i, j] + C[i, j], name="out") return [A, B, C, out] # Create the search task # ^^^^^^^^^^^^^^^^^^^^^^ # We then create a search task with N=L=M=1024 and dtype="float32" # If your machine supports avx instructions, you can # # - replace "llvm" below with "llvm -mcpu=core-avx2" to enable AVX2 # - replace "llvm" below with "llvm -mcpu=skylake-avx512" to enable AVX-512 # # # + target = tvm.target.Target("llvm") N = L = M = 1024 task = tvm.auto_scheduler.SearchTask(func=matmul_add, args=(N, L, M, "float32"), target=target) # Inspect the computational graph print("Computational DAG:") print(task.compute_dag) # - # Next, we set parameters for the auto-scheduler. # # * :code:`num_measure_trials` is the number of measurement trials we can use during the search. # We only make 10 trials in this tutorial for a fast demonstration. In practice, 1000 is a # good value for the search to converge. You can do more trials according to your time budget. # * In addition, we use :code:`RecordToFile` to dump measurement records into a file `matmul.json`. # The measurement records can be used to query the history best, resume the search, # and do more analyses later. # * see :any:`auto_scheduler.TuningOptions` for more parameters # # log_file = "matmul.json" tune_option = auto_scheduler.TuningOptions( num_measure_trials=10, measure_callbacks=[auto_scheduler.RecordToFile(log_file)], verbose=2, ) # Run the search # ^^^^^^^^^^^^^^ # Now we get all inputs ready. Pretty simple, isn't it? # We can kick off the search and let the auto-scheduler do its magic. # After some measurement trials, we can load the best schedule from the log # file and apply it. # # # Run auto-tuning (search) task.tune(tune_option) # Apply the best schedule sch, args = task.apply_best(log_file) # We can lower the schedule to see the IR after auto-scheduling. # The auto-scheduler correctly performs optimizations including multi-level tiling, # layout transformation, parallelization, vectorization, unrolling, and operator fusion. # # print("Lowered TIR:") print(tvm.lower(sch, args, simple_mode=True)) # Check correctness and evaluate performance # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # We build the binary and check its correctness and performance. # # # + func = tvm.build(sch, args, target) a_np = np.random.uniform(size=(N, L)).astype(np.float32) b_np = np.random.uniform(size=(L, M)).astype(np.float32) c_np = np.random.uniform(size=(N, M)).astype(np.float32) out_np = a_np.dot(b_np) + c_np ctx = tvm.cpu() a_tvm = tvm.nd.array(a_np, ctx=ctx) b_tvm = tvm.nd.array(b_np, ctx=ctx) c_tvm = tvm.nd.array(c_np, ctx=ctx) out_tvm = tvm.nd.empty(out_np.shape, ctx=ctx) func(a_tvm, b_tvm, c_tvm, out_tvm) # Check results np.testing.assert_allclose(out_np, out_tvm.asnumpy(), rtol=1e-3) # Evaluate execution time. evaluator = func.time_evaluator(func.entry_name, ctx, min_repeat_ms=500) print( "Execution time of this operator: %.3f ms" % (np.median(evaluator(a_tvm, b_tvm, c_tvm, out_tvm).results) * 1000) ) # - # Using the record file # ^^^^^^^^^^^^^^^^^^^^^ # During the search, all measurement records are dumped into the record # file "matmul.json". The measurement records can be used to re-apply search results, # resume the search, and perform other analyses. # # # Here is an example where we load the best schedule from a file, # and print the equivalent python schedule API. This can be used for # debugging and learning the behavior of the auto-scheduler. # # print("Equivalent python schedule:") print(task.print_best(log_file)) # A more complicated example is to resume the search. # In this case, we need to create the search policy and cost model by ourselves # and resume the status of search policy and cost model with the log file. # In the example below we resume the status and do more 5 trials. # # # + def resume_search(task, log_file_name): cost_model = auto_scheduler.XGBModel() cost_model.update_from_file(log_file_name) search_policy = auto_scheduler.SketchPolicy( task, cost_model, init_search_callbacks=[auto_scheduler.PreloadMeasuredStates(log_file_name)], ) tune_option = auto_scheduler.TuningOptions( num_measure_trials=5, measure_callbacks=[auto_scheduler.RecordToFile(log_file_name)] ) task.tune(tune_option, search_policy=search_policy) # resume_search(task, log_file) # - # <div class="alert alert-info"><h4>Note</h4><p>We cannot run the line above because of the conflict between # python's multiprocessing and tvm's thread pool. # After running a tvm generated binary the python's multiprocessing library # will hang forever. You have to make sure that you don't run any tvm # generated binaries before calling auot-scheduler's search. # To run the function above, you should comment out all code in # "Check correctness and evaluate performance" section. # # You should be careful about this problem in your applications. # There are other workarounds for this problem. # For example, you can start a new thread/process (with the builtin python library # threading or multiprocessing) and run the tvm binaries in the new thread/process. # This provides an isolation and avoids the conflict in the main thread/process. # You can also use :any:`auto_scheduler.LocalRPCMeasureContext` for auto-scheduler, # as shown in the GPU tutorial (`auto-scheduler-conv-gpu`).</p></div> # #
_downloads/f1a09967bab66114252357e4a9babb45/tune_matmul_x86.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 # --- # + _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" DEBUG = True MODE = 'TRAIN' #MODE = 'Inference' MODEL_DIR = '../input/optiver-lgb-and-te-baseline' # + import numpy as np import pandas as pd import gc import pathlib from tqdm.auto import tqdm # Widget progress bar import json from multiprocessing import Pool, cpu_count import time import requests as re from datetime import datetime from dateutil.relativedelta import relativedelta, FR # Input data files are available in the read-only "../input/" directory # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import pyarrow.parquet as pq import glob import os from sklearn import model_selection import joblib import lightgbm as lgb import plotly.graph_objects as go import plotly.express as px import matplotlib.pyplot as plt import matplotlib.style as style from matplotlib_venn import venn2, venn3 import seaborn as sns from matplotlib import pyplot from matplotlib.ticker import ScalarFormatter sns.set_context('talk') style.use('seaborn-colorblind') import warnings warnings.simplefilter('ignore') pd.get_option('display.max_columns') # - class CFG: INPUT_DIR = '../input/optiver-realized-volatility-prediction' OUTPUT_DIR = './' # + # Logging = essential # import logging # logging.basicConfig( # level = logging.DEBUG, # format='{asctime} {levelname:<8} {message}', # styel='{' # ) def init_logger(log_file='train.log'): from logging import getLogger, INFO, FileHandler, Formatter, StreamHandler logger = getLogger(__name__) logger.setLevel(INFO) handler1 = StreamHandler() handler1.setFormatter(Formatter('%(message)s')) handler2 = FileHandler(filename=log_file) handler2.setFormatter(Formatter('%(message)s')) logger.addHandler(handler1) logger.addHandler(handler2) return logger logger = init_logger(log_file=f'{CFG.OUTPUT_DIR}/baseline.log') logger.info(f'Start Logging...') # - train = pd.read_csv(os.path.join(CFG.INPUT_DIR, 'train.csv')) # target, what you are trying to predict, first appears in train test = pd.read_csv(os.path.join(CFG.INPUT_DIR, 'test.csv')) ss = pd.read_csv(os.path.join(CFG.INPUT_DIR, 'sample_submission.csv')) train train['target'].describe() # + # train['stock_id'].value_counts() # train['time_id'].value_counts() # - test.head() ss.head() sns.displot(data=train['target']) # + fig, ax = plt.subplots(16, 7, figsize=(20, 60)) ax = ax.flatten() for i, stock_id in tqdm(enumerate(train['stock_id'].unique())): ax[i].hist(train.query('stock_id == @stock_id')['target'], bins=100) ax[i].set_title(stock_id) plt.tight_layout() # + train_book_stocks = os.listdir(os.path.join(CFG.INPUT_DIR, 'book_train.parquet')) train_trade_stocks = os.listdir(os.path.join(CFG.INPUT_DIR, 'trade_train.parquet')) if DEBUG: logger.info('Debug mode: using 5 stocks only') train_book_stocks = train_book_stocks[:5] logger.info('{:,} train book stocks: {}'.format(len(train_book_stocks), train_book_stocks)) # - test_book_stocks = os.listdir(os.path.join(CFG.INPUT_DIR, 'book_test.parquet')) test_trade_stocks = os.listdir(os.path.join(CFG.INPUT_DIR, 'trade_test.parquet')) print('{:,} test book stocks: {}'.format(len(test_book_stocks), test_book_stocks)) print('{:,} test trade stocks: {}'.format(len(test_trade_stocks), test_trade_stocks)) print(test_trade_stocks == test_book_stocks) #load stock_id=0 def load_book(stock_id, data_type='train'): """ load parquet book data for given stock_id """ #the following line imports the parquet book train data and selects the specified stock_id to be stored in book_df book_df = pd.read_parquet(os.path.join(CFG.INPUT_DIR, f'book_{data_type}.parquet/stock_id={stock_id}')) book_df['stock_id'] = stock_id book_df['stock_id'] = book_df['stock_id'].astype(np.int8) #int8 Byte (-128 to 127), parquet returns stock_id as categorical return book_df def load_trade(stock_id=0, data_type='train'): """ load parquet trade data for given stock_id """ #the following line imports the parquet trade train data and selects the specified stock_id to be stored in trade_df trade_df = pd.read_parquet(os.path.join(CFG.INPUT_DIR, f'trade_{data_type}.parquet/stock_id={stock_id}')) trade_df['stock_id'] = stock_id trade_df['stock_id'] = trade_df['stock_id'].astype(np.int8) return trade_df def fix_jsonerr(df): # fix json column error for lightgbm # isalnum returns true if all digits in string are alphanumeric, letters or numbers df.columns = ["".join (c if c.isalnum() else "_" for c in str(x)) for x in df.columns] return df # + def log_return(list_stock_prices): return np.log(list_stock_prices).diff() def realized_volatility(stock_price): series_log_return = log_return(stock_price) return np.sqrt(np.sum(series_log_return ** 2)) # - def fe_row(book): #Feature engineering (just volatility) for each row #volatility for i in[1,2]: #wap book[f'book_wap{i}'] = (book[f'bid_price{i}'] * book[f'ask_size{i}'] + book[f'ask_price{i}'] * book[f'bid_size{i}']) / (book[f'bid_size{i}'] + book[f'ask_size{i}']) #mean wap book['book_wap_mean'] = (book['book_wap1'] + book['book_wap2']) / 2 #wap diff book['book_wap_diff'] = book['book_wap1'] - book['book_wap2'] #other orderbook features book['book_price_spread'] = (book['ask_price1'] - book['bid_price1']) / (book['ask_price1'] + book['bid_price1']) book['book_bid_spread'] = book['bid_price1'] - book['bid_price2'] book['book_ask_spread'] = book['ask_price1'] - book['ask_price2'] book['book_total_volume'] = book['ask_size1'] + book['ask_size2'] + book['bid_size1'] + book['bid_size2'] book['book_volume_imbalance'] = (book['ask_size1'] + book['ask_size2']) - (book['bid_size1'] + book['bid_size2']) #level volume imbalance for i in[1,2]: book[f'book_bid_ask_vol_imbalance{i}'] = book[f'ask_size{i}'] - book[f'bid_size{i}'] return book def fe_agg(book_df): #feature engineering (aggregation by stock_id x time_id) # features book_feats = book_df.columns[book_df.columns.str.startswith('book_')].values.tolist() trade_feats = ['price', 'size', 'order_count', 'seconds_in_bucket'] # agg trade features trade_df = book_df.groupby(['time_id', 'stock_id'])[trade_feats].agg(['sum', 'mean', 'std', 'max', 'min']).reset_index() # agg volatility features fe_df = book_df.groupby(['time_id', 'stock_id'])[book_feats].agg([realized_volatility]).reset_index() fe_df.columns = [" ".join(col).strip() for col in fe_df.columns.values] # merge fe_df = fe_df.merge(trade_df, how='left', on=['time_id', 'stock_id']) return fe_df # %time #stock_ids = [int(i.split('=')[-1]) for i in train_book_stocks] stock_ids = [0] book_df = list(tqdm(map(load_book, stock_ids), total=len(stock_ids))) book_df = pd.concat(book_df) book_df #lots of data on single stock # %time trade_df = list(tqdm(map(load_trade, stock_ids), total=len(stock_ids))) trade_df = pd.concat(trade_df) trade_df # + # Just for inner observation, don't run # book_df = book_df.merge(trade_df, how='inner', on=['time_id','seconds_in_bucket','stock_id']) # book_df.head() # - book_df = book_df.merge(trade_df, how='outer', on=['time_id','seconds_in_bucket','stock_id']) book_df.head(15) book_df = fe_row(book_df) # more features book_df # Realized Volatility calculation based on book_wap1 example book_df1 = book_df[['time_id','seconds_in_bucket','bid_price1','ask_price1','bid_size1','ask_size1','bid_price2','ask_price2','book_wap1','book_wap2','stock_id','price','size','order_count']] book_df1 book_df1 = book_df1.merge(train[train['stock_id'] == 0], how='outer', on=['stock_id','time_id']) book_df1 b1 = book_df1[book_df1['time_id'] == 5] b2 = b1[['seconds_in_bucket','price']].dropna() b3 = b1[['seconds_in_bucket', 'bid_price1','ask_price1']] b4 = b1[['seconds_in_bucket', 'bid_price2','ask_price2']] # + fig, ax = plt.subplots() line1 = ax.plot(b2['seconds_in_bucket'], b2['price'], label='Traded Price', color='black') line2 = ax.plot(b3['seconds_in_bucket'],b3['bid_price1'], label='bid1', dashes=[6,2]) line3 = ax.plot(b3['seconds_in_bucket'],b3['ask_price1'], label='ask1', dashes=[6,2]) line4 = ax.plot(b4['seconds_in_bucket'],b4['bid_price2'], label='bid2', dashes=[6,2]) line5 = ax.plot(b4['seconds_in_bucket'],b4['ask_price2'], label='ask2', dashes=[6,2], color='purple') ax.set_title('Stock:0, Time_id: 5, Bids vs Traded Price vs Asks') ax.legend(prop={'size': 8}) fig = plt.figure(figsize=(20, 16)) plt.tight_layout() # - df = book_df1[(book_df1['stock_id']==0) & (book_df1['time_id']==5)] # Realized Volatility calculation, Root Sum of Squares log_df = np.log(df['book_wap1']).diff() log_df = np.power(log_df,2) log_df = np.sum(log_df) np.sqrt(log_df) book_feats = book_df1.columns[book_df1.columns.str.startswith('book_')].values.tolist() fe_df = book_df1.groupby(['time_id', 'stock_id'])[book_feats].agg([realized_volatility]).reset_index() fe_df.columns = [" ".join(col).strip() for col in fe_df.columns.values] fe_df fe_df['book_wap1 realized_volatility'].describe() train[train['stock_id']==0]['target'].describe() fe_df['book_wap1 realized_volatility'].hist(bins=100) #blue train[train['stock_id']==0]['target'].hist(bins=100) #green plt.title(label='Stock 0: Calculated Realized Volatility and Stock 0: Train Target Histogram') # + # plt.boxplot(fe_df['book_wap1 realized_volatility'],vert=False) # plt.title(label='Stock 0: Realized Volatility Box Plot') # Use x instead of y argument for horizontal plot #fig.add_trace(go.Box(x=x1)) import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Box(x=fe_df['book_wap1 realized_volatility'],boxpoints='all',jitter=0.44)) fig.show() # - # This is where the previous functions come together def fe_all(book_df): """ perform feature engineerings """ # row-wise feature engineering, ADDS THE EXTRA FEATURES TO THE DATAFRAME book_df = fe_row(book_df) # feature engineering agg by stock_id x time_id, ADDS REALIZED VOLATILITY TO SOME OF THE FEATURES fe_df = fe_agg(book_df) return fe_df def book_fe_by_stock(stock_id=0): """ load orderbook and trade data for the given stock_id and merge """ # load data book_df = load_book(stock_id, 'train') trade_df = load_trade(stock_id, 'train') book_feats = book_df.columns.values.tolist() # merge book_df = book_df.merge(trade_df, how='outer', on=['time_id', 'seconds_in_bucket', 'stock_id']) # sort by time book_df = book_df.sort_values(by=['time_id', 'seconds_in_bucket']) # fillna for book_df book_df[book_feats] = book_df[book_feats].fillna(method='ffill') # feature engineering fe_df = fe_all(book_df) return fe_df def book_fe_by_stock_test(stock_id=0): """ same function but for the test """ # load data book_df = load_book(stock_id, 'test') trade_df = load_trade(stock_id, 'test') book_feats = book_df.columns.values.tolist() # merge book_df = book_df.merge(trade_df, how='outer', on=['time_id', 'seconds_in_bucket', 'stock_id']) # sort by time book_df = book_df.sort_values(by=['time_id', 'seconds_in_bucket']) # fillna for book_df book_df[book_feats] = book_df[book_feats].fillna(method='ffill') # feature engineering fe_df = fe_all(book_df) return fe_df """ So, the primary reasons to use imap/imap_unordered over map/map_async are: Your iterable is large enough that converting it to a list would cause you to run out of/use too much memory. You want to be able to start processing the results before all of them are completed. """ def book_fe_all(stock_ids, data_type='train'): # feature engineering with multithread processing # feature engineering agg by stock_id x time_id with Pool(cpu_count()) as p: if data_type == 'train': feature_dfs = list(tqdm(p.imap(book_fe_by_stock, stock_ids), total=len(stock_ids))) # this is where it can take a list of the stock ids elif data_type == 'test': feature_dfs = list(tqdm(p.imap(book_fe_by_stock_test, stock_ids), total=len(stock_ids))) fe_df = pd.concat(feature_dfs) # feature engineering agg by stock_id volatility_feats = [f for f in fe_df.columns if ('realized' in f) & ('wap' in f)] if data_type == 'train': # agg stock_df = fe_df.groupby('stock_id')[volatility_feats].agg(['mean', 'std', 'max', 'min']).reset_index() # fix column names stock_df.columns = ['stock_id'] + [f'{f}_stock' for f in stock_df.columns.values.tolist()[1:]] stock_df = fix_jsonerr(stock_df) # feature engineering agg by time_id time_df = fe_df.groupby('time_id')[volatility_feats].agg(['mean', 'std', 'max', 'min']).reset_index() time_df.columns = ['time_id'] + [f'{f}_time' for f in time_df.columns.values.tolist()[1:]] # merge fe_df = fe_df.merge(time_df, how='left', on='time_id') # make sure to fix json error for lightgbm fe_df = fix_jsonerr(fe_df) # out if data_type == 'train': return fe_df, stock_df elif data_type == 'test': return fe_df # %%time MODE = 'TRAIN' if MODE == 'TRAIN': # all book data feature engineering stock_ids = [int(i.split('=')[-1]) for i in train_book_stocks] book_df, stock_df = book_fe_all(stock_ids, data_type='train') assert book_df['stock_id'].nunique() > 2 assert book_df['time_id'].nunique() > 2 # save stock_df for the test stock_df.to_pickle('train_stock_df.pkl') logger.info('train stock df saved!') # merge book_df,stock_df, and train book_df = book_df.merge(stock_df, how='left', on='stock_id').merge(train, how='left', on=['stock_id', 'time_id']).replace([np.inf, -np.inf], np.nan).fillna(method='ffill') # make row_id book_df['row_id'] = book_df['stock_id'].astype(str) + '-' + book_df['time_id'].astype(str) print(book_df.shape) book_df.head() book_df stock_df.columns stock_df # + # test test_book_stocks = os.listdir(os.path.join(CFG.INPUT_DIR, 'book_test.parquet')) logger.info('{:,} test book stocks: {}'.format(len(test_book_stocks), test_book_stocks)) # all book data feature engineering test_stocks_ids = [int(i.split('=')[-1]) for i in test_book_stocks] test_book_df = book_fe_all(test_stocks_ids, data_type='test') # load stock_df, if inference #MODE = 'INFERENCE' if MODE == 'INFERENCE': stock_df = pd.read_pickle('./train_stock_df.pkl') #stock_df = pd.read_pickle(f'{MODEL_DIR}/train_stock_df.pkl') # merge test_book_df = test.merge(stock_df, how='left', on='stock_id').merge(test_book_df, how='left', on=['stock_id', 'time_id']).replace([np.inf, -np.inf], np.nan).fillna(method='ffill') # make row_id test_book_df['row_id'] = test_book_df['stock_id'].astype(str) + '-' + test_book_df['time_id'].astype(str) print(test_book_df.shape) test_book_df.head() # + #prepares model input parameters for testing/inference # LIGHTGBM will ignore missing values during a split, then allocate them to whichever side reduces the loss the most target = 'target' drops = [target, 'row_id', 'time_id'] features = [f for f in test_book_df.columns.values.tolist() if (f not in drops) & (test_book_df[f].isna().sum() == 0) & (book_df[f].isna().sum() == 0)] cats = ['stock_id'] logger.info('{:,} features ({:,} categorical): {}'.format(len(features), len(cats), features)) # + #training target = 'target' drops = [target, 'row_id', 'time_id'] train_features = [f for f in book_df.columns.values.tolist() if (f not in drops) & (book_df[f].isna().sum() == 0)] cats = ['stock_id'] logger.info('{:,} features ({:,} categorical): {}'.format(len(train_features), len(cats), train_features)) # - features train_features # + # evaluation metric def RMSPEMetric(): def RMSPE(yhat, dtrain): y = dtrain.get_label() elements = ((y - yhat) / y) ** 2 return 'RMSPE', float(np.sqrt(np.sum(elements) / len(y))), False return RMSPE def rmspe(y_true, y_pred): return (np.sqrt(np.mean(np.square((y_true - y_pred) / y_true)))) # - def fit_model(params, X_train, y_train, X_test, features=features, cats=[], era='stock_id', fold_type='kfold', n_fold = 5, seed=42): """ fit model with cv (cross validation) """ models = [] oof_df = X_train[['time_id', 'stock_id', target]].copy() oof_df['pred'] = np.nan y_preds = np.zeros((len(X_test),)) if fold_type == 'stratifiedshuffle': cv = model_selection.StratifiedShuffleSplit(n_splits=n_fold, random_state=seed) kf = cv.split(X_train, X_train[era]) elif fold_type == 'kfold': cv = model_selection.KFold(n_splits=n_fold, shuffle=True, random_state=seed) kf = cv.split(X_train, y_train) fi_df = pd.DataFrame() fi_df['features'] = features fi_df['importance'] = 0 for fold_id, (train_index, valid_index) in tqdm(enumerate(kf)): #split X_tr = X_train.loc[train_index, features] X_val = X_train.loc[valid_index, features] y_tr = y_train.loc[train_index] y_val = y_train.loc[valid_index] # model, note inverse weighting train_set = lgb.Dataset(X_tr, y_tr, categorical_feature = cats, weight = 1/np.power(y_tr, 2)) val_set = lgb.Dataset(X_val, y_val, categorical_feature = cats, weight = 1/np.power(y_val, 2)) # model training model = lgb.train(params, train_set, valid_sets = [train_set, val_set], feval=RMSPEMetric(), verbose_eval=250) # feature importance fi_df[f'importance_fold{fold_id}'] = model.feature_importance(importance_type='gain') fi_df['importance'] += fi_df[f'importance_fold{fold_id}'].values # save model joblib.dump(model, f'model_fold{fold_id}.pkl') logger.debug('model saved!') # predict oof_df['pred'].iloc[valid_index] = model.predict(X_val) y_pred = model.predict(X_test[features]) y_preds += y_pred / n_fold models.append(model) return oof_df, y_preds, models, fi_df # + # %%time #Overfitting on the training data params = { "device": "gpu", "gpu_platform_id": 0, "gpu_device_id": 0, 'n_estimators' : 500, 'objective': 'rmse', 'boosting_type': 'dart', 'max_depth': -1, 'learning_rate': 0.3, 'num_leaves': 128, 'min_data_in_leaf': 1000, 'max_bin': 70, 'subsample': 0.82, 'subsample_freq': 7, 'feature_fraction': 0.6, 'lambda_l1': 0.5, 'lambda_l2': 1, #'min_gain_to_split': 0.009275035155177913, 'seed': 42, 'early_stopping_rounds': 50, 'verbose': -1 } if MODE == 'TRAIN': oof_df, y_preds, models, fi_df = fit_model(params, book_df, book_df[target], test_book_df, features=train_features, cats = cats, era = 'stock_id', fold_type = 'stratifiedshuffle', n_fold = 5, seed = 42) # - fi_df.sort_values(by=['importance'],ascending=False) # + from sklearn.metrics import r2_score def rmspe(y_true, y_pred): return (np.sqrt(np.mean(np.square((y_true - y_pred) / y_true)))) if MODE == 'TRAIN': oof_df.dropna(inplace=True) y_true = oof_df[target].values y_pred = oof_df['pred'].values oof_df[target].hist(bins=100) oof_df['pred'].hist(bins=100) R2 = round(r2_score(y_true, y_pred), 3) RMSPE = round(rmspe(y_true, y_pred), 3) logger.info(f'Performance of the prediction: R2 score: {R2}, RMSPE: {RMSPE}') # - if MODE == 'TRAIN': for stock_id in oof_df['stock_id'].unique(): y_true = oof_df.query('stock_id == @stock_id')[target].values y_pred = oof_df.query('stock_id == @stock_id')['pred'].values R2 = round(r2_score(y_true, y_pred), 3) RMSPE = round(rmspe(y_true, y_pred), 3) logger.info(f'Performance by stock_id={stock_id}: R2 score: {R2}, RMSPE: {RMSPE}') MODE= 'TRAIN' # + # %%time #Overfitting on the training data params = { "device": "gpu", "gpu_platform_id": 0, "gpu_device_id": 0, 'n_estimators' : 500, 'objective': 'rmse', 'boosting_type': 'dart', 'max_depth': 8, 'learning_rate': 0.3, 'num_leaves': 128, 'max_bin': 68, 'seed': 42, 'early_stopping_rounds': 50, 'verbose': -1 } if MODE == 'TRAIN': oof_df, y_preds, models, fi_df = fit_model(params, book_df, book_df[target], test_book_df, features=train_features, cats = cats, era = None, fold_type = 'kfold', n_fold = 5, seed = 42) # + from sklearn.metrics import r2_score def rmspe(y_true, y_pred): return (np.sqrt(np.mean(np.square((y_true - y_pred) / y_true)))) if MODE == 'TRAIN': oof_df.dropna(inplace=True) y_true = oof_df[target].values y_pred = oof_df['pred'].values oof_df[target].hist(bins=100) #blue oof_df['pred'].hist(bins=100) #green R2 = round(r2_score(y_true, y_pred), 3) RMSPE = round(rmspe(y_true, y_pred), 3) logger.info(f'Performance of the naive prediction: R2 score: {R2}, RMSPE: {RMSPE}') # - if MODE == 'TRAIN': for stock_id in oof_df['stock_id'].unique(): y_true = oof_df.query('stock_id == @stock_id')[target].values y_pred = oof_df.query('stock_id == @stock_id')['pred'].values R2 = round(r2_score(y_true, y_pred), 3) RMSPE = round(rmspe(y_true, y_pred), 3) logger.info(f'Performance by stock_id={stock_id}: R2 score: {R2}, RMSPE: {RMSPE}') # + # %%time #Overfitting on the training data params = { "device": "gpu", "gpu_platform_id": 0, "gpu_device_id": 0, 'n_estimators' : 500, 'objective': 'rmse', 'min_data_in_leaf': 1000, 'boosting_type': 'dart', 'max_depth': -1, 'learning_rate': 0.3, 'num_leaves': 128, 'max_bin': 68, 'seed': 42, 'early_stopping_rounds': 50, 'verbose': -1 } if MODE == 'TRAIN': oof_df, y_preds, models, fi_df = fit_model(params, book_df, book_df[target], test_book_df, features=train_features, cats = cats, era = None, fold_type = 'kfold', n_fold = 5, seed = 42) # - if MODE == 'TRAIN': oof_df.dropna(inplace=True) y_true = oof_df[target].values y_pred = oof_df['pred'].values oof_df[target].hist(bins=100) #blue oof_df['pred'].hist(bins=100) #green R2 = round(r2_score(y_true, y_pred), 3) RMSPE = round(rmspe(y_true, y_pred), 3) logger.info(f'Performance of the naive prediction: R2 score: {R2}, RMSPE: {RMSPE}') if MODE == 'TRAIN': for stock_id in oof_df['stock_id'].unique(): y_true = oof_df.query('stock_id == @stock_id')[target].values y_pred = oof_df.query('stock_id == @stock_id')['pred'].values R2 = round(r2_score(y_true, y_pred), 3) RMSPE = round(rmspe(y_true, y_pred), 3) logger.info(f'Performance by stock_id={stock_id}: R2 score: {R2}, RMSPE: {RMSPE}') # + import optuna def objective(trial, features=features, X=book_df, y=book_df[target], cats=cats): param_grid = { #"n_estimators": trial.suggest_categorical("n_estimators", [813]), "n_estimators": 500, "device": "gpu", "gpu_platform_id": 0, "gpu_device_id": 0, "learning_rate": 0.3, "boosting": trial.suggest_categorical("boosting",['dart','gbdt','goss']), #"learning_rate": trial.suggest_float("learning_rate", 0.1, 0.2, 0.3), "num_leaves": trial.suggest_int("num_leaves", 128, 1024), "max_depth": trial.suggest_int("max_depth", 7, 10), "min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 500, 750, 1000), "max_bin": trial.suggest_int("max_bin", 64, 70), 'early_stopping_rounds': 10, #"lambda_l1": trial.suggest_int("lambda_l1", 0, 100, step=5), #"lambda_l2": trial.suggest_int("lambda_l2", 0, 100, step=5), #"min_gain_to_split": trial.suggest_float("min_gain_to_split", 0, 15), } cv = model_selection.KFold(n_splits=2, shuffle=True, random_state=46) #kf = cv.split(X_train, y_train) cv_scores = np.empty(2) # from optuna blog # splits the data into 5 groups, uses one as validation, trains models and gets results then repeats for fold_id, (train_index, valid_index) in tqdm(enumerate(cv.split(X,y))): #split X_tr = X.loc[train_index, features] X_val = X.loc[valid_index, features] y_tr = y.loc[train_index] y_val = y.loc[valid_index] # model, note inverse weighting please train_set = lgb.Dataset(X_tr, y_tr, categorical_feature = cats, weight = 1/np.power(y_tr, 2)) val_set = lgb.Dataset(X_val, y_val, categorical_feature = cats, weight = 1/np.power(y_val, 2)) # Note that train() will return a model from the best iteration. model = lgb.train(param_grid, train_set, valid_sets = [train_set, val_set], feval=RMSPEMetric(), verbose_eval=250) #model.fit(X_train=book_df,y_train = book_df[target],test_book_df,cats = cats) # predict y_pred = model.predict(X_val[features]) y_true = y_val return (np.sqrt(np.mean(np.square((y_true - y_pred)/y_true)))) # - #optimization_function = partial(objective, X=x, y=y) study = optuna.create_study(direction='minimize') study.optimize(objective) #n_trials=20 print('Number of finished trials:', len(study.trials)) print('Best trial:', study.best_trial.params) # + # Number of finished trials: 20 # Best trial: {'boosting': 'dart', 'num_leaves': 288, 'max_depth': 9, 'min_data_in_leaf': 500, 'max_bin': 68} #Trial 304 finished with value: 0.2411297275201126 and parameters: {'boosting': 'dart', 'num_leaves': 661, 'max_depth': 8, 'min_data_in_leaf': 500, 'max_bin': 68}. Best is trial 304 with value: 0.2411297275201126. # + # %%time params = { "device": "gpu", "gpu_platform_id": 0, "gpu_device_id": 0, 'n_estimators' : 500, 'objective': 'rmse', 'boosting_type': 'gbdt', 'max_depth': -1, 'learning_rate': 0.3, 'num_leaves': 128, 'max_bin': 70, 'seed': 42, 'early_stopping_rounds': 50, 'verbose': -1 } if MODE == 'INFERENCE': oof_df, y_preds, models, fi_df = fit_model(params, book_df, book_df[target], test_book_df, features=features, cats = cats, era = None, fold_type = 'kfold', n_fold = 5, seed = 42)
Optiver Realized Volatility Prediction/Optiver Realized Volatility Prediction.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 # --- # # Looping over systematic models # # Ideally, we would be using something from this in the docs to loop through our 50 different systematic models, which only differ in which parameters are thawed or frozen: # https://sherpa.readthedocs.io/en/4.11.0/model_classes/api/sherpa.models.model.SimulFitModel.html#sherpa.models.model.SimulFitModel # # Until such time that we understand how that works, we will be helping ourselves with a good old `for` loop. In this notebook, I am figuring out how. # + # Imports import os import numpy as np import matplotlib.pyplot as plt import astropy.units as u from astropy.constants import G os.chdir('../HST_python') from config import CONFIG_INI from limb_darkening import limb_dark_fit import margmodule as marg from sherpa.data import Data1D from sherpa.plot import DataPlot from sherpa.plot import ModelPlot from sherpa.fit import Fit from sherpa.stats import LeastSq from sherpa.optmethods import LevMar from sherpa.stats import Chi2 from sherpa.plot import FitPlot # - # ### Data paths localDir = CONFIG_INI.get('data_paths', 'local_path') outDir = os.path.join(localDir, CONFIG_INI.get('data_paths', 'output_path')) curr_model = CONFIG_INI.get('data_paths', 'current_model') dataDir = os.path.join(localDir, os.path.join(localDir, CONFIG_INI.get('data_paths', 'data_path')), curr_model) # ### Read data # + # Read in the txt file for the lightcurve data x, y, err, sh = np.loadtxt(os.path.join(dataDir, 'W17_white_lightcurve_test_data.txt'), skiprows=7, unpack=True) wavelength = np.loadtxt(os.path.join(dataDir, 'W17_wavelength_test_data.txt'), skiprows=3) tzero = x[0] flux0 = y[0] print("x.shape: {}".format(x.shape)) print("y.shape: {}".format(y.shape)) print("err.shape: {}".format(err.shape)) print("sh.shape: {}".format(sh.shape)) print("wvln.shape: {}".format(wavelength.shape)) # - # ### PLanet parameters and limb darkening # + Per = CONFIG_INI.getfloat('planet_parameters', 'Per') * u.d Per = Per.to(u.s) constant1 = ((G * np.square(Per)) / (4 * np.square(np.pi))) ** (1 / 3) aor = CONFIG_INI.getfloat('planet_parameters', 'aor') # this is unitless -> "distance of the planet from the star (meters)/stellar radius (meters)" MsMpR = (aor / constant1) ** 3. print("MsMpR: {}\n".format(MsMpR)) # Limb darkening M_H = CONFIG_INI.getfloat('limb_darkening', 'metallicity') # metallicity Teff = CONFIG_INI.getfloat('limb_darkening', 'Teff') # effective temperature logg = CONFIG_INI.getfloat('limb_darkening', 'logg') # log(g), gravitation # Define limb darkening directory, which is inside this package limbDir = os.path.join('..', 'Limb-darkening') ld_model = CONFIG_INI.get('limb_darkening', 'ld_model') grat = CONFIG_INI.get('technical_parameters', 'grating') _uLD, c1, c2, c3, c4, _cp1, _cp2, _cp3, _cp4, _aLD, _bLD = limb_dark_fit(grat, wavelength, M_H, Teff, logg, limbDir, ld_model) print("\nThe four cs: {}, {}, {}, {}".format(c1, c2, c3, c4)) # - # ### Sherpa data object # + # Instantiate a data object data = Data1D('Data', x, y, staterror=err) print(data) # Plot the data with Sherpa dplot = DataPlot() dplot.prepare(data) dplot.plot() # - # ### Sherpa model - here's where we start working # # All parameters will be thawed, except for the ones that have `alwaysfrozen=True` in their initializaiton. # Define the model tmodel = marg.Transit(tzero, MsMpR, c1, c2, c3, c4, flux0, name="testmodel", sh=sh) print(tmodel) # We can read the requested grid from our module. grid_selection = CONFIG_INI.get('technical_parameters', 'grid_selection') grid = marg.wfc3_systematic_model_grid_selection(grid_selection) print('1st systematic model: {}'.format(grid[0])) # We can loop through that easily. for i, s in enumerate(grid): print(i+1, s) # So, `s` will be a single systematic model: print(s) # So far, so good. # # Now, we can also loop though all the model parameters pretty easily. for i in tmodel.pars: print('->', i.name) print(i) print('\n') # Now we need to think of a way to combine `s` with the parameters in the model. Remember that `s` has as many entries as `tmodel` has parameters. # The first loop is the big loop that goes through all the systematic models. # The second loop is what sets up the frozen and thawed parameters. for i, s in enumerate(grid): for k, p in enumerate(s): print('i:', i) print('k:', p) # + # Now in our context with the model: # - for i, s in enumerate(grid): #print(s) for k, select in enumerate(s): if select == 0: tmodel.pars[k].thaw() elif select == 1: tmodel.pars[k].freeze() # How do we test this though? Lets do it one by one with the systematics. # + po = 36 # pick any between 0 and 49 (we have 50 systematic models) sys = grid[po] print(sys) for k, select in enumerate(sys): if select == 0: tmodel.pars[k].thaw() elif select == 1: tmodel.pars[k].freeze() print(tmodel) # - # Works!
notebooks/dev/main_script/Looping over systematic models.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.1 64-bit (''PyUdemy'': conda)' # metadata: # interpreter: # hash: 53c9f3a4159f48d83d907bef19770d20ea5efe7306b7b4f4b1cab0d144297c55 # name: 'Python 3.8.1 64-bit (''PyUdemy'': conda)' # --- # Types for the keys: BOOL, INT, NONE, FLOAT, STR, TUPLE (immutable types) # Types for the values: any type my_dict1 = {True: 'test', 10: [1, 2, 3], None: 10.5, 10.1: {'k': 'v'}, 'jan': {'test'}, (10, 20): (5, 4)} print(my_dict1) my_dict2 = dict(firstname='Thomas', lastname='Fritsch') print(my_dict2) # + my_dict2['birthday'] = '15.01.1974' print(my_dict2) print(my_dict2['birthday']) print(len(my_dict2)) # - for key in my_dict2.keys(): print(key) for val in my_dict2.values(): print(val) for key, val in my_dict2.items(): print(key, val) del my_dict2['birthday'] print(my_dict2) if 'firstname' in my_dict2: print('yes') else: print('no') print(my_dict2['birthday']) # + birthday = my_dict2.get('birthday') if birthday: print(birthday) # - print(my_dict2) del my_dict2['birthday'] print(my_dict2.pop('birthday', None)) print(my_dict2)
Chapter4_Iterables/Dicts/dicts.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 # --- # author: <NAME> from Bio import SeqIO from Bio import SeqRecord as SeqRecord import pandas as pd import numpy as np import itertools from matplotlib import pyplot as plt # # Analysis of the alignments of draft assemblies using mummer DELTA = {} ASSEMBLIES = {} tig_order = {} cum_len = {} for s in ['Jean-Talon_reordered.fasta','S288c.genome.fa','barcode11.cns.fa', 'Jean-Talon.unitigs.fasta', 'Jean-Talon.contigs.fasta']: ASSEMBLIES[s] = {} tig_order[s] = [] cl = [] with open(f'/Volumes/MacintoshHD/Dropbox/Jean_Talon/assemblies/{s}') as fi: for seq in SeqIO.parse(fi, 'fasta'): ASSEMBLIES[s][seq.id] = seq tig_order[s].append(seq.id) cl.append(len(seq.seq)) cl = pd.Series([0]+list(np.cumsum(cl)[:-1]), index=tig_order[s]) cum_len[s] = cl if s!='Jean-Talon_reordered.fasta': delta = pd.read_csv(f'/Volumes/MacintoshHD/Dropbox/Jean_Talon/mummer/{s}.coords', sep='\t', skiprows=range(4), index_col=None, header=None) delta = delta.loc[(delta[4]>=1e4) & (delta[5]>=1e4)].astype({1:int,2:int,2:int,2:int}).sort_values(by=4) delta['s1'] = delta[0]+cum_len['Jean-Talon_reordered.fasta'].loc[delta[7].values].values delta['e1'] = delta[1]+cum_len['Jean-Talon_reordered.fasta'].loc[delta[7].values].values delta['s2'] = delta[2]+cum_len[s].loc[delta[8].values].values delta['e2'] = delta[3]+cum_len[s].loc[delta[8].values].values DELTA[s] = delta # + fig = plt.figure(figsize=[32,8]) gs = plt.GridSpec(ncols=4, nrows=1, wspace=0.3, left=0.03, bottom=0.08, right=0.96, top=0.9) assembly_alias = {'Jean-Talon_reordered.fasta': 'Jean-Talon wtdbg2 polished', 'S288c.genome.fa': 'S288C', 'barcode11.cns.fa': 'Jean-Talon wtdbg2 draft (>8kb reads)', 'Jean-Talon.unitigs.fasta': 'Jean-Talon Canu draft unitigs (>8kb reads)', 'Jean-Talon.contigs.fasta': 'Jean-Talon Canu draft contigs (>8kb reads)'} coord_translocation = np.mean(np.array([1.4e5, 1.47e5])+cum_len['Jean-Talon_reordered.fasta'].loc['ctg6_pilon']) for ax_idx, s in enumerate(['S288c.genome.fa', 'barcode11.cns.fa', 'Jean-Talon.contigs.fasta', 'Jean-Talon.unitigs.fasta']): ax = fig.add_subplot(gs[ax_idx]) delta = DELTA[s] for i in delta.index: s1, e1, s2, e2 = delta.loc[i, ['s1','e1','s2','e2']] c = str(1-delta.loc[i,6]/100) ax.plot([s1,e1], [s2,e2], color=c, lw=1) for i in cum_len[s]: ax.axhline(i, lw=0.5, ls=':', color='k') for i in cum_len['Jean-Talon_reordered.fasta']: ax.axvline(i, lw=0.5, ls=':', color='k') ax.margins(0) ax.axvline(coord_translocation, color='red', ls='-', lw=3, alpha=0.3) assembly_size = ax.axis() ax.set_xticks(np.arange(0, assembly_size[1], 1e6)) ax.set_xticklabels(np.arange(0, assembly_size[1]*1e-6, 1).astype(int)) ax.set_yticks(np.arange(0, assembly_size[3], 1e6)) ax.set_yticklabels(np.arange(0, assembly_size[3]*1e-6, 1).astype(int)) #if s=='S288c.genome.fa': for tig, df in delta.groupby(8): if len(ASSEMBLIES[s][tig].seq)>2e5: ax.text(assembly_size[1]*1.02, np.mean([df['s2'].min(), df['e2'].max()]), s=tig, va='center', ha='left', size=7) for tig, df in delta.groupby(7): if len(ASSEMBLIES['Jean-Talon_reordered.fasta'][tig].seq)>2e5: ax.text(np.mean([df['s1'].min(), df['e1'].max()]), assembly_size[3]*1.02, s=tig, va='bottom', ha='center', rotation=90, size=7) ax.set_xlabel(assembly_alias['Jean-Talon_reordered.fasta'], size=14) ax.set_ylabel(assembly_alias[s], size=14) plt.savefig('/Volumes/MacintoshHD/Dropbox/Jean_Talon/fig/FigS7.svg') #plt.show() plt.close()
07_draft_assemblies/assemblies.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 # --- # # OOI Equipment mapping # - by <NAME> # - 6/14/2016 # - This notebook is for retrieving information from google sheets and then mapping to a JSON file, each instrument has its own JSON file configuration # - The required libraries for this manipulation is *gspread*, *oauth2client*, and *pycrypto* # + # Google Authentication Libraries import oauth2client, gspread import json # oauth2client version check and gspread oauth_ver = oauth2client.__version__ gspread_ver = gspread.__version__ print "oauth2client version : {}".format(oauth_ver) print "gspread version : {}".format(gspread_ver) # - if oauth_ver < "2.0.2": from oauth2client.client import SignedJwtAssertionCredentials json_key = json.load(open('XXXX.json')) # Get scope for google sheets # Gather all spreadsheets shared with the client_email: <EMAIL> scope = ['https://spreadsheets.google.com/feeds'] # Retrieve credentials from JSON key of service account credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope) # Authorize gspread to connect to google sheets gc = gspread.authorize(credentials) else: from oauth2client.service_account import ServiceAccountCredentials # Get scope for google sheets # Gather all spreadsheets shared with the client_email: <EMAIL> scope = ['https://spreadsheets.google.com/feeds'] # Retrieve credentials from JSON key of service account credentials = ServiceAccountCredentials.from_json_keyfile_name('XXXX.json', scope) # Authorize gspread to connect to google sheets gc = gspread.authorize(credentials) # Get all spreadsheets available for NANOOS gsheets = gc.openall() # Get title of the spreadsheets for i in range(0,len(gsheets)): print "{0} {1}".format(i,gsheets[i].title) # Open sensor_configurations_mappings only sc = gc.open("sensor_configurations_mappings") # Get all worksheets in a sheet wks = sc.worksheets() wks s1 = sc.get_worksheet(0) s2 = sc.get_worksheet(1) print s1, s2 # ## Parsing data to a pandas dataframe # - Now that connection has been established, data is parsed to be viewed # Import pandas and numpy to make data easier to view # %matplotlib inline import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt print "pandas version: {}".format(pd.__version__) print "numpy version: {}".format(np.__version__) # Getting all the values of sheet1 array1 = s1.get_all_values() array2 = s2.get_all_values() # Convert data into pandas dataframe df = pd.DataFrame(array1) df.columns = array1[0] df.drop(df.index[0], inplace=True) df = df.convert_objects(convert_numeric=True) df.head() # Convert data into pandas dataframe df1 = pd.DataFrame(array2) df1.columns = array2[0] df1.drop(df1.index[0], inplace=True) df1 = df1.convert_objects(convert_numeric=True) df1.head() def createJSON(df): # Get Platforms json_data = df[['platform','instrument','depth_m','mfn','deployment','data_logger','subtype']].reset_index(drop=True) platforms = json_data['platform'].unique() mainkey = dict() prop = dict() # Gather Platform info together plat = [json_data.loc[json_data['platform'] == p] for p in platforms] # Create JSON for i in range(0, len(plat)): instrum = dict() mainkey = dict() for j in range(0, len(plat[i]['platform'].values)): platform_name = plat[i]['platform'].values[j] instrument_name = plat[i]['instrument'].values[j] depth_m = plat[i]['depth_m'].values[j] mfn = plat[i]['mfn'].values[j] deployment = plat[i]['deployment'].values[j] data_logger = plat[i]['data_logger'].values[j] subtype = plat[i]['subtype'].values[j] # Check for mfn if mfn != '': mfn = True else: mfn = False # Getting subtype if subtype != '': subtype = subtype.split('::')[1] else: subtype = None prop['depth_m'] = float(depth_m) prop['mfn'] = mfn prop['deployment'] = deployment prop['data_logger'] = data_logger prop['subtype'] = subtype instrum['{}'.format(instrument_name)] = prop mainkey['{}'.format(platform_name)] = instrum prop = dict() # prints the JSON structured dictionary print json.dumps(mainkey, sort_keys=True, indent=4, separators=(',', ': ')) # Output to JSON file fj = open("{}.json".format(platform_name), 'w') fj.write(json.dumps(mainkey, sort_keys=False, indent=4, separators=(',', ': '))) fj.close() createJSON(df)
OOI/OOI_equipment_mapping.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 # --- # # Machine Learning Engineer Nanodegree # ## Unsupervised Learning # ## Project: Creating Customer Segments # Welcome to the third project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `'TODO'` statement. Please be sure to read the instructions carefully! # # In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide. # # >**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode. # ## Getting Started # # In this project, you will analyze a dataset containing data on various customers' annual spending amounts (reported in *monetary units*) of diverse product categories for internal structure. One goal of this project is to best describe the variation in the different types of customers that a wholesale distributor interacts with. Doing so would equip the distributor with insight into how to best structure their delivery service to meet the needs of each customer. # # The dataset for this project can be found on the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Wholesale+customers). For the purposes of this project, the features `'Channel'` and `'Region'` will be excluded in the analysis — with focus instead on the six product categories recorded for customers. # # Run the code block below to load the wholesale customers dataset, along with a few of the necessary Python libraries required for this project. You will know the dataset loaded successfully if the size of the dataset is reported. # + # Import libraries necessary for this project import numpy as np import pandas as pd import seaborn as sns from IPython.display import display # Allows the use of display() for DataFrames # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks # %matplotlib inline # Load the wholesale customers dataset try: data = pd.read_csv("customers.csv") data.drop(['Region', 'Channel'], axis = 1, inplace = True) print("Wholesale customers dataset has {} samples with {} features each.".format(*data.shape)) except: print("Dataset could not be loaded. Is the dataset missing?") # - # ## Data Exploration # In this section, you will begin exploring the data through visualizations and code to understand how each feature is related to the others. You will observe a statistical description of the dataset, consider the relevance of each feature, and select a few sample data points from the dataset which you will track through the course of this project. # # Run the code block below to observe a statistical description of the dataset. Note that the dataset is composed of six important product categories: **'Fresh'**, **'Milk'**, **'Grocery'**, **'Frozen'**, **'Detergents_Paper'**, and **'Delicatessen'**. Consider what each category represents in terms of products you could purchase. # Display a description of the dataset display(data.describe()) # ### Implementation: Selecting Samples # To get a better understanding of the customers and how their data will transform through the analysis, it would be best to select a few sample data points and explore them in more detail. In the code block below, add **three** indices of your choice to the `indices` list which will represent the customers to track. It is suggested to try different sets of samples until you obtain customers that vary significantly from one another. # + # Select three indices of your choice you wish to sample from the dataset indices = [29, 72, 412] # Create a DataFrame of the chosen samples samples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True) print("Chosen samples of wholesale customers dataset:") display(samples) # - # ### Question 1 # Consider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers. # # * What kind of establishment (customer) could each of the three samples you've chosen represent? # # **Hint:** Examples of establishments include places like markets, cafes, delis, wholesale retailers, among many others. Avoid using names for establishments, such as saying *"McDonalds"* when describing a sample customer as a restaurant. You can use the mean values for reference to compare your samples with. The mean values are as follows: # # * Fresh: 12000.2977 # * Milk: 5796.2 # * Grocery: 7951.3 # * Detergents_paper: 2881.4 # * Delicatessen: 1524.8 # # Knowing this, how do your samples compare? Does that help in driving your insight into what kind of establishments they might be? # # **Answer:** # # - Index 42: Fresh Supplier: This sample has predominantly fresh food, almost 4 times the mean value. This suggest a mass producer of fresh food. # - Index 142: Wholesale retailer: This sample has all features significantly, except for Delicatessen, which suggest that it seems like a more 'popular' place to buy all sort of stuff. # - Index 342: Grocery Shop: This sample has mainly groceries, milk and detergents_paper, which suggests it is a grocery shop. # ### Implementation: Feature Relevance # One interesting thought to consider is if one (or more) of the six product categories is actually relevant for understanding customer purchasing. That is to say, is it possible to determine whether customers purchasing some amount of one category of products will necessarily purchase some proportional amount of another category of products? We can make this determination quite easily by training a supervised regression learner on a subset of the data with one feature removed, and then score how well that model can predict the removed feature. # # In the code block below, you will need to implement the following: # - Assign `new_data` a copy of the data by removing a feature of your choice using the `DataFrame.drop` function. # - Use `sklearn.cross_validation.train_test_split` to split the dataset into training and testing sets. # - Use the removed feature as your target label. Set a `test_size` of `0.25` and set a `random_state`. # - Import a decision tree regressor, set a `random_state`, and fit the learner to the training data. # - Report the prediction score of the testing set using the regressor's `score` function. # + from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor # Make a copy of the DataFrame, using the 'drop' function to drop the given feature new_data = data.drop(['Grocery'], axis=1) # Split the data into training and testing sets(0.25) using the given feature as the target # Set a random state. X_train, X_test, y_train, y_test = train_test_split(new_data, data['Grocery'], test_size=0.25, random_state=42) # Create a decision tree regressor and fit it to the training set regressor = DecisionTreeRegressor(random_state=42) regressor.fit(X_train, y_train) # Report the score of the prediction using the testing set score = regressor.score(X_test, y_test) print(f"Score: {score}") # - # ### Question 2 # # * Which feature did you attempt to predict? # * What was the reported prediction score? # * Is this feature necessary for identifying customers' spending habits? # # **Hint:** The coefficient of determination, `R^2`, is scored between 0 and 1, with 1 being a perfect fit. A negative `R^2` implies the model fails to fit the data. If you get a low score for a particular feature, that lends us to beleive that that feature point is hard to predict using the other features, thereby making it an important feature to consider when considering relevance. # **Answer:** # # - I attempted to predict the **'Grocery'** feature # - The reported prediction score was **0.6818840085440834** # - This feature it's not necessary to identify customers' spending habits because it has a high score, this suggests that the other features correlate well with **'Grocery'** and the feature will not provide much information gain. # ### Visualize Feature Distributions # To get a better understanding of the dataset, we can construct a scatter matrix of each of the six product features present in the data. If you found that the feature you attempted to predict above is relevant for identifying a specific customer, then the scatter matrix below may not show any correlation between that feature and the others. Conversely, if you believe that feature is not relevant for identifying a specific customer, the scatter matrix might show a correlation between that feature and another feature in the data. Run the code block below to produce a scatter matrix. # Produce a scatter matrix for each pair of features in the data pd.plotting.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde'); # ### Question 3 # * Using the scatter matrix as a reference, discuss the distribution of the dataset, specifically talk about the normality, outliers, large number of data points near 0 among others. If you need to sepearate out some of the plots individually to further accentuate your point, you may do so as well. # * Are there any pairs of features which exhibit some degree of correlation? # * Does this confirm or deny your suspicions about the relevance of the feature you attempted to predict? # * How is the data for those features distributed? # # **Hint:** Is the data normally distributed? Where do most of the data points lie? You can use [corr()](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.corr.html) to get the feature correlations and then visualize them using a [heatmap](http://seaborn.pydata.org/generated/seaborn.heatmap.html)(the data that would be fed into the heatmap would be the correlation values, for eg: `data.corr()`) to gain further insight. sns.heatmap(data.corr(), annot=True, cmap='Blues') # **Answer:** # # - As we can see in the scatter matrix, the data is highly skewed and not normaly distributed. To me the outliers seems like some large company establishments. The large number of data points near 0 seems to be related to the size of the establishments in the dataset, which seems to be mostly focused on small establishments. # - From the heatmap, we can see that the pair **Grocery and Detergents_Paper** have a high correlation (**0.92**). The pair **Grocery and Milk** also present a linear correlation with a coefficient of **0.73**, with a similar strenght from the pair **Detergents_Paper and Milk (0.66)**. # - This confirm my susicions about the relevane of the feature **Grocery**, this feature has a weak relevence in establising the profile of the data because there is not much information gain with high correlated features and this feature has a high correlation with **Milk** and **Detergents_Paper** # - The data for those features is highly skewed and not normaly distributed. # ## Data Preprocessing # In this section, you will preprocess the data to create a better representation of customers by performing a scaling on the data and detecting (and optionally removing) outliers. Preprocessing data is often times a critical step in assuring that results you obtain from your analysis are significant and meaningful. # ### Implementation: Feature Scaling # If data is not normally distributed, especially if the mean and median vary significantly (indicating a large skew), it is most [often appropriate](http://econbrowser.com/archives/2014/02/use-of-logarithms-in-economics) to apply a non-linear scaling — particularly for financial data. One way to achieve this scaling is by using a [Box-Cox test](http://scipy.github.io/devdocs/generated/scipy.stats.boxcox.html), which calculates the best power transformation of the data that reduces skewness. A simpler approach which can work in most cases would be applying the natural logarithm. # # In the code block below, you will need to implement the following: # - Assign a copy of the data to `log_data` after applying logarithmic scaling. Use the `np.log` function for this. # - Assign a copy of the sample data to `log_samples` after applying logarithmic scaling. Again, use `np.log`. # + # Scale the data using the natural logarithm log_data = np.log(data) # Scale the sample data using the natural logarithm log_samples = np.log(samples) # Produce a scatter matrix for each pair of newly-transformed features pd.plotting.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde'); # - # ### Observation # After applying a natural logarithm scaling to the data, the distribution of each feature should appear much more normal. For any pairs of features you may have identified earlier as being correlated, observe here whether that correlation is still present (and whether it is now stronger or weaker than before). # # Run the code below to see how the sample data has changed after having the natural logarithm applied to it. # Display the log-transformed sample data display(log_samples) # ### Implementation: Outlier Detection # Detecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many "rules of thumb" for what constitutes an outlier in a dataset. Here, we will use [Tukey's Method for identfying outliers](http://datapigtechnologies.com/blog/index.php/highlighting-outliers-in-your-data-with-the-tukey-method/): An *outlier step* is calculated as 1.5 times the interquartile range (IQR). A data point with a feature that is beyond an outlier step outside of the IQR for that feature is considered abnormal. # # In the code block below, you will need to implement the following: # - Assign the value of the 25th percentile for the given feature to `Q1`. Use `np.percentile` for this. # - Assign the value of the 75th percentile for the given feature to `Q3`. Again, use `np.percentile`. # - Assign the calculation of an outlier step for the given feature to `step`. # - Optionally remove data points from the dataset by adding indices to the `outliers` list. # # **NOTE:** If you choose to remove any outliers, ensure that the sample data does not contain any of these points! # Once you have performed this implementation, the dataset will be stored in the variable `good_data`. # + outliers = [] # For each feature find the data points with extreme high or low values for feature in log_data.keys(): # Calculate Q1 (25th percentile of the data) for the given feature Q1 = np.percentile(log_data[feature], 25.) # Calculate Q3 (75th percentile of the data) for the given feature Q3 = np.percentile(log_data[feature], 75.) # Use the interquartile range to calculate an outlier step (1.5 times the interquartile range) step = (Q3-Q1)*1.5 # Display the outliers print("Data points considered outliers for the feature '{}':".format(feature)) feat_outliers = log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))] display(feat_outliers) # Select the indices for data points you wish to remove outliers.extend(feat_outliers.index.tolist()) # Get only outliers that appears in more than one feature outliers_series = pd.Series(outliers) outliers = outliers_series[outliers_series.duplicated()].unique().tolist() # Remove the outliers, if any were specified good_data = log_data.drop(log_data.index[outliers]).reset_index(drop = True) # - # ### Question 4 # * Are there any data points considered outliers for more than one feature based on the definition above? # * Should these data points be removed from the dataset? # * If any data points were added to the `outliers` list to be removed, explain why. # # ** Hint: ** If you have datapoints that are outliers in multiple categories think about why that may be and if they warrant removal. Also note how k-means is affected by outliers and whether or not this plays a factor in your analysis of whether or not to remove them. # **Answer:** # # - Some data points are considered outliers for more that one feature, the points are *65, 66, 75, 128 and 154* # - These data points should be removed from the dataset because the use of them will only skew the results. They are really different from the rest of the dataset and will add no value to the prediction. # - I only remove the outliers who are considered an outlier in more that one feature to reduce the potential of skewing the results. If we remove those who are considered an outlier in just one feature we will remove almost 10% of the data points, and this can cause us to lose important information.} # ## Feature Transformation # In this section you will use principal component analysis (PCA) to draw conclusions about the underlying structure of the wholesale customer data. Since using PCA on a dataset calculates the dimensions which best maximize variance, we will find which compound combinations of features best describe customers. # ### Implementation: PCA # # Now that the data has been scaled to a more normal distribution and has had any necessary outliers removed, we can now apply PCA to the `good_data` to discover which dimensions about the data best maximize the variance of features involved. In addition to finding these dimensions, PCA will also report the *explained variance ratio* of each dimension — how much variance within the data is explained by that dimension alone. Note that a component (dimension) from PCA can be considered a new "feature" of the space, however it is a composition of the original features present in the data. # # In the code block below, you will need to implement the following: # - Import `sklearn.decomposition.PCA` and assign the results of fitting PCA in six dimensions with `good_data` to `pca`. # - Apply a PCA transformation of `log_samples` using `pca.transform`, and assign the results to `pca_samples`. # + from sklearn.decomposition import PCA # Apply PCA by fitting the good data with the same number of dimensions as features pca = PCA(n_components=6, random_state=42) pca.fit(good_data) # Transform log_samples using the PCA fit above pca_samples = pca.transform(log_samples) # Generate PCA results plot pca_results = vs.pca_results(good_data, pca) # - # ### Question 5 # # * How much variance in the data is explained* **in total** *by the first and second principal component? # * How much variance in the data is explained by the first four principal components? # * Using the visualization provided above, talk about each dimension and the cumulative variance explained by each, stressing upon which features are well represented by each dimension(both in terms of positive and negative variance explained). Discuss what the first four dimensions best represent in terms of customer spending. # # **Hint:** A positive increase in a specific dimension corresponds with an *increase* of the *positive-weighted* features and a *decrease* of the *negative-weighted* features. The rate of increase or decrease is based on the individual feature weights. pca_results.cumsum() # **Answer:** # # - **70.68%** of the variance are explained by the **first two** principal components. # - **93.11%** of the variance are explained by the **first four** principal components. # - **Discussion:** # - **First Dimension:** it has the largest explained variance, with all features having significant weights. **Detergents_Paper** has the highest weight and **Delicatessen** the smallest. In this dimension, **Detergents_paper, Grocery and Milk** have almost all the total weight and this suggest that this dimension is best categorized by customers spending on retail goods. # - **Second Dimension:** this dimension has a large explained variance but all the features now have negative weights. In this dimension, the 3 features dominating the first dimesion have a smaller weight, but the another 3 (**Fresh, Frozen and Delicatessen**) are now dominating the total weight of this dimension and suggests that this dimension is best categorized by customers spending on foods (could be a restaurant, maybe?) # - **Third Dimension:** this dimension still have their total weight dominated by **Fresh, Frozen and Delicatessen**, but the explained variace on this dimension is a little lower because the other features have their weight reduced. This dimension is best categorized by customers spending on **Frozen and Delicatessen** but not **Fresh**. # - **Fourth Dimension:** in this dimension we have a significant positive weight to **Frozen and Detergents_Paper** and a significant negative weight to **Fresh and Delicatessen** with a loss of explained variance. This dimension is best categorized by customers spending on frozen goods. # - **Fifth Dimension:** in this dimension the explained variance is even smaller, with **Milk and Grocery** being well represented with positive weights and **Detergents_Paper and Delicatessen** with negative weights. # - **Sixth Dimension:** only three features are significant in this dimension - **Milk, Grocery and Detergents_Paper** - with a really small explained variance. # ### Observation # Run the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it in six dimensions. Observe the numerical value for the first four dimensions of the sample points. Consider if this is consistent with your initial interpretation of the sample points. # Display sample log-data after having a PCA transformation applied display(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values)) # ### Implementation: Dimensionality Reduction # When using principal component analysis, one of the main goals is to reduce the dimensionality of the data — in effect, reducing the complexity of the problem. Dimensionality reduction comes at a cost: Fewer dimensions used implies less of the total variance in the data is being explained. Because of this, the *cumulative explained variance ratio* is extremely important for knowing how many dimensions are necessary for the problem. Additionally, if a signifiant amount of variance is explained by only two or three dimensions, the reduced data can be visualized afterwards. # # In the code block below, you will need to implement the following: # - Assign the results of fitting PCA in two dimensions with `good_data` to `pca`. # - Apply a PCA transformation of `good_data` using `pca.transform`, and assign the results to `reduced_data`. # - Apply a PCA transformation of `log_samples` using `pca.transform`, and assign the results to `pca_samples`. # + # Apply PCA by fitting the good data with only two dimensions pca = PCA(n_components=2) pca.fit(good_data) # Transform the good data using the PCA fit above reduced_data = pca.transform(good_data) # Transform log_samples using the PCA fit above pca_samples = pca.transform(log_samples) # Create a DataFrame for the reduced data reduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2']) # - # ### Observation # Run the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions. Observe how the values for the first two dimensions remains unchanged when compared to a PCA transformation in six dimensions. # Display sample log-data after applying PCA transformation in two dimensions display(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2'])) # ## Visualizing a Biplot # A biplot is a scatterplot where each data point is represented by its scores along the principal components. The axes are the principal components (in this case `Dimension 1` and `Dimension 2`). In addition, the biplot shows the projection of the original features along the components. A biplot can help us interpret the reduced dimensions of the data, and discover relationships between the principal components and original features. # # Run the code cell below to produce a biplot of the reduced-dimension data. # Create a biplot vs.biplot(good_data, reduced_data, pca) # ### Observation # # Once we have the original feature projections (in red), it is easier to interpret the relative position of each data point in the scatterplot. For instance, a point the lower right corner of the figure will likely correspond to a customer that spends a lot on `'Milk'`, `'Grocery'` and `'Detergents_Paper'`, but not so much on the other product categories. # # From the biplot, which of the original features are most strongly correlated with the first component? What about those that are associated with the second component? Do these observations agree with the pca_results plot you obtained earlier? # ## Clustering # # In this section, you will choose to use either a K-Means clustering algorithm or a Gaussian Mixture Model clustering algorithm to identify the various customer segments hidden in the data. You will then recover specific data points from the clusters to understand their significance by transforming them back into their original dimension and scale. # ### Question 6 # # * What are the advantages to using a K-Means clustering algorithm? # * What are the advantages to using a Gaussian Mixture Model clustering algorithm? # * Given your observations about the wholesale customer data so far, which of the two algorithms will you use and why? # # ** Hint: ** Think about the differences between hard clustering and soft clustering and which would be appropriate for our dataset. # **Answer:** # # - K-Means: # - Simplicity and Speed: it has few parameters and can outperform other algorithms on large datasets. # - Always converges: it performs best when data is well separated and non-uniform. # - Gaussian Mixture: # - Soft assigns a point to clusters: each point have a probability to belong to any centroids. # - Performs well in less defined datasets. # - Capability of incorporating the covariance between points in the model to identify more complex clusters. # - As we can see in the biplot, some dimensions in the data have a strong degree of correlation between each other and the data cannot be well separated with a lot of data points don't clearly belonging to one particular cluster. That said, the best option in this case is to use the **Gaussian Mixture Model**, as we will add more flexibility and information gain with it. # ### Implementation: Creating Clusters # Depending on the problem, the number of clusters that you expect to be in the data may already be known. When the number of clusters is not known *a priori*, there is no guarantee that a given number of clusters best segments the data, since it is unclear what structure exists in the data — if any. However, we can quantify the "goodness" of a clustering by calculating each data point's *silhouette coefficient*. The [silhouette coefficient](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.silhouette_score.html) for a data point measures how similar it is to its assigned cluster from -1 (dissimilar) to 1 (similar). Calculating the *mean* silhouette coefficient provides for a simple scoring method of a given clustering. # # In the code block below, you will need to implement the following: # - Fit a clustering algorithm to the `reduced_data` and assign it to `clusterer`. # - Predict the cluster for each data point in `reduced_data` using `clusterer.predict` and assign them to `preds`. # - Find the cluster centers using the algorithm's respective attribute and assign them to `centers`. # - Predict the cluster for each sample data point in `pca_samples` and assign them `sample_preds`. # - Import `sklearn.metrics.silhouette_score` and calculate the silhouette score of `reduced_data` against `preds`. # - Assign the silhouette score to `score` and print the result. # + from sklearn.mixture import GaussianMixture from sklearn.metrics import silhouette_score # Apply your clustering algorithm of choice to the reduced data clusterer = GaussianMixture(n_components=2, random_state=42) clusterer.fit(reduced_data) # Predict the cluster for each data point preds = clusterer.predict(reduced_data) # Find the cluster centers centers = clusterer.means_ # Predict the cluster for each transformed sample data point sample_preds = clusterer.predict(pca_samples) # Calculate the mean silhouette coefficient for the number of clusters chosen score = silhouette_score(reduced_data,preds) print(score) # - # ### Question 7 # # * Report the silhouette score for several cluster numbers you tried. # * Of these, which number of clusters has the best silhouette score? # **Answer:** # # | Number of Clusters | Score | # | :----------------: | :-----: | # | 2 | 0.4219 | # | 3 | 0.4042 | # | 4 | 0.2932 | # | 5 | 0.3004 | # | 6 | 0.3261 | # | 7 | 0.3242 | # | 8 | 0.2964 | # | 9 | 0.3071 | # | 10 | 0.3103 | # | 11 | 0.3391 | # | 12 | 0.3143 | # | 13 | 0.3082 | # # The number of clusters with the best silhouette score is **2**. # ### Cluster Visualization # Once you've chosen the optimal number of clusters for your clustering algorithm using the scoring metric above, you can now visualize the results by executing the code block below. Note that, for experimentation purposes, you are welcome to adjust the number of clusters for your clustering algorithm to see various visualizations. The final visualization provided should, however, correspond with the optimal number of clusters. # Display the results of the clustering from implementation vs.cluster_results(reduced_data, preds, centers, pca_samples) # ### Implementation: Data Recovery # Each cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the *averages* of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's center point corresponds to *the average customer of that segment*. Since the data is currently reduced in dimension and scaled by a logarithm, we can recover the representative customer spending from these data points by applying the inverse transformations. # # In the code block below, you will need to implement the following: # - Apply the inverse transform to `centers` using `pca.inverse_transform` and assign the new centers to `log_centers`. # - Apply the inverse function of `np.log` to `log_centers` using `np.exp` and assign the true centers to `true_centers`. # # + # Inverse transform the centers log_centers = pca.inverse_transform(centers) # Exponentiate the centers true_centers = np.exp(log_centers) # Display the true centers segments = ['Segment {}'.format(i) for i in range(0,len(centers))] true_centers = pd.DataFrame(np.round(true_centers), columns = data.keys()) true_centers.index = segments display(true_centers) # - # ### Question 8 # # * Consider the total purchase cost of each product category for the representative data points above, and reference the statistical description of the dataset at the beginning of this project(specifically looking at the mean values for the various feature points). What set of establishments could each of the customer segments represent? # # **Hint:** A customer who is assigned to `'Cluster X'` should best identify with the establishments represented by the feature set of `'Segment X'`. Think about what each segment represents in terms their values for the feature points chosen. Reference these values with the mean values to get some perspective into what kind of establishment they represent. # **Answer:** # # - **Segment 0:** This segment seems to be some kind of **Retail** establishment, because it sells mostly fresh and few of the others products. # - **Segment 1:** This segment seems to be a **Restaurant, Cafe or Grocery Shop**, because I think all this establishments would have some high values in Milk and Groceries. # ### Question 9 # # * For each sample point, which customer segment from* **Question 8** *best represents it? # * Are the predictions for each sample point consistent with this?* # # Run the code block below to find which cluster each sample point is predicted to be. # + # Display the predictions for i, pred in enumerate(sample_preds): print("Sample point", i, "predicted to be in Cluster", pred) display(samples) # - # **Answer:** # # - Sample point 0: the **Segment 0** best represents it. # - Sample point 1: the **Segment 0** best represents it. # - Sample point 2: the **Segment 1** best represents it. # # The prediction to the sample points are consistent with this. # ## Conclusion # In this final section, you will investigate ways that you can make use of the clustered data. First, you will consider how the different groups of customers, the ***customer segments***, may be affected differently by a specific delivery scheme. Next, you will consider how giving a label to each customer (which *segment* that customer belongs to) can provide for additional features about the customer data. Finally, you will compare the ***customer segments*** to a hidden variable present in the data, to see whether the clustering identified certain relationships. # ### Question 10 # Companies will often run [A/B tests](https://en.wikipedia.org/wiki/A/B_testing) when making small changes to their products or services to determine whether making that change will affect its customers positively or negatively. The wholesale distributor is considering changing its delivery service from currently 5 days a week to 3 days a week. However, the distributor will only make this change in delivery service for customers that react positively. # # * How can the wholesale distributor use the customer segments to determine which customers, if any, would react positively to the change in delivery service?* # # **Hint:** Can we assume the change affects all customers equally? How can we determine which group of customers it affects the most? # **Answer:** # # When we reduce the delivery service from 5 days a week to 3 days a week we are likely to have a higher impact on costumers that are concearned about the freshness of their products. When we analyze our Clusters we can see that, if our assumptions are right, the **Cluster 1** will be more affected because a (Restaurant, Cafe or Grocery Shop) will want 5-day delivery to keep food as fresh as possible. On the other hand, **Cluster 0** are Retailers, who can be more flexible because they usually by a lot and make a stock of non-perishable goods and will not be affected in the same proportion. # # That said, the wholesaler will be able to draw more realistic hypothesist about the expected behavior the the customers in each cluster and create diferent strategies to apply different A/B Tests to a sample of each test based on this assumptions. # ### Question 11 # Additional structure is derived from originally unlabeled data when using clustering techniques. Since each customer has a ***customer segment*** it best identifies with (depending on the clustering algorithm applied), we can consider *'customer segment'* as an **engineered feature** for the data. Assume the wholesale distributor recently acquired ten new customers and each provided estimates for anticipated annual spending of each product category. Knowing these estimates, the wholesale distributor wants to classify each new customer to a ***customer segment*** to determine the most appropriate delivery service. # * How can the wholesale distributor label the new customers using only their estimated product spending and the **customer segment** data? # # **Hint:** A supervised learner could be used to train on the original customers. What would be the target variable? # **Answer:** # # The wholesale distributor can train a supervised learner such as SVM (with has a good performance separating classified clusters) or XGBoost with the initial dataset, using as target value the costumer segment resulting from the GMM clustering. Once we have this, we can use the trained model to predict in wich customer segment the new customer is likely to be and then determine the most apropriated delivery service. # ### Visualizing Underlying Distributions # # At the beginning of this project, it was discussed that the `'Channel'` and `'Region'` features would be excluded from the dataset so that the customer product categories were emphasized in the analysis. By reintroducing the `'Channel'` feature to the dataset, an interesting structure emerges when considering the same PCA dimensionality reduction applied earlier to the original dataset. # # Run the code block below to see how each data point is labeled either `'HoReCa'` (Hotel/Restaurant/Cafe) or `'Retail'` the reduced space. In addition, you will find the sample points are circled in the plot, which will identify their labeling. # Display the clustering results based on 'Channel' data vs.channel_results(reduced_data, outliers, pca_samples) # ### Question 12 # # * How well does the clustering algorithm and number of clusters you've chosen compare to this underlying distribution of Hotel/Restaurant/Cafe customers to Retailer customers? # * Are there customer segments that would be classified as purely 'Retailers' or 'Hotels/Restaurants/Cafes' by this distribution? # * Would you consider these classifications as consistent with your previous definition of the customer segments? # **Answer:** # # - The GMM with 2 clusters has a similar distribution to the distribution presented above, showing that the GMM esbalished the key relationships well. With the GMM clustering we couldn't get some outliers and anomalous data points, such as the sample 2. # - Yes, in the extreme parts of the Dimension 1 we can confidently classify as purely *Retailer* or *Hotels/Restaurants/Cafes*. # - Yes, this classifications are consistent with my previous definition o the customer segments, with the exception of Hotel as a segment, because I didn't consider hotels and put Grocery shops in their place. # > **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to # **File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.
customer_segments/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.8.8 64-bit (''kaggle'': conda)' # language: python # name: python388jvsc74a57bd0324064526588904db53d8c1754501a1e17277e16e25f64624bf6abfe73e224f9 # --- # # Waveform based CNN # # From https://github.com/gwastro/ml-training-strategies/blob/master/Pytorch/network.py # + import torch import math import numpy as np import torch.nn as nn from torch.fft import fft, rfft, ifft import matplotlib.pyplot as plt from scipy import signal import librosa import librosa.display from torchaudio.functional import bandpass_biquad, lfilter from pathlib import Path COMP_NAME = "g2net-gravitational-wave-detection" INPUT_PATH = Path(f"/mnt/storage_dimm2/kaggle_data/{COMP_NAME}/") OUTPUT_PATH = Path(f"/mnt/storage_dimm2/kaggle_output/{COMP_NAME}/") import sys sys.path.append("/home/anjum/kaggle/g2net-gravitational-wave-detection/") from src.resnet1d import ResNet1D # + def load_file(id_, folder="train"): path = INPUT_PATH / folder / id_[0] / id_[1] / id_[2] / f"{id_}.npy" waves = np.load(path) # return waves / np.max(np.abs(waves), axis=1).reshape(3, 1) return waves / np.max(np.abs(waves)) # https://www.kaggle.com/kevinmcisaac/g2net-spectral-whitening def apply_whiten(signal, window=False): # signal is a numpy array signal = torch.from_numpy(signal).float() if signal.ndim == 2: win_length = signal.shape[1] else: win_length = signal.shape[0] # Not needed if a window has already been applied. Tukey is probably better if window: hann = torch.hann_window(win_length, periodic=True, dtype=float) signal *= hann spec = fft(signal) mag = torch.sqrt(torch.real(spec * torch.conj(spec))) return torch.real(ifft(spec / mag)).numpy() * np.sqrt(win_length / 2) def apply_bandpass(x, lf=35, hf=350, order=4, sr=2048): sos = signal.butter(order, [lf, hf], btype="bandpass", output="sos", fs=sr) normalization = np.sqrt((hf - lf) / (sr / 2)) return signal.sosfiltfilt(sos, x) / normalization def pad_data(x, padding=0.25, sr=2048): pad_value = int(padding * sr) return np.pad(x, ((0, 0), (pad_value, pad_value))) # - # wave_id = "098a464da9" # Super clean signal wave_id = "000a5b6e5c" class WaveformCNN(nn.Module): def __init__(self, n_channels=3): super().__init__() self.net = nn.Sequential( nn.BatchNorm1d(n_channels), nn.Conv1d(n_channels, 8, 64), nn.ELU(), nn.Conv1d(8, 8, 32), nn.MaxPool1d(4), nn.ELU(), nn.Conv1d(8, 16, 32), nn.ELU(), nn.Conv1d(16, 32, 16), nn.MaxPool1d(3), nn.ELU(), nn.Conv1d(32, 64, 16), nn.ELU(), nn.Conv1d(64, 128, 16), nn.AdaptiveAvgPool1d(1), nn.ELU(), nn.Flatten(), nn.Linear(128, 64), nn.Dropout(p=0.5), nn.ELU(), nn.Linear(64, 64), nn.Dropout(p=0.5), nn.ELU(), nn.Linear(64, 1), ) def forward(self, x): return self.net(x) wcnn = WaveformCNN(3) data = torch.from_numpy(load_file(wave_id)).unsqueeze(0).float() data.shape out = wcnn(data) out.shape # # Make a residual net # + model = ResNet1D( in_channels=3, base_filters=128, kernel_size=16, stride=2, n_block=48, groups=32, n_classes=1, downsample_gap=6, increasefilter_gap=12, verbose=False, ) model # - out = model(data) out.shape
datasaurus/notebooks/waveform_cnn.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/mrksntndr/Linear-Algebra-58019/blob/main/Matrix_Algebra.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="3X0nt22fzU7E" # ##Python program to inverse # + colab={"base_uri": "https://localhost:8080/"} id="Cwx39Wgi3HYA" outputId="11e7fde7-0596-4dbd-bfe9-bba5eaaa6b13" import numpy as np A=np.array([[1,2],[4,7]]) invA=(np.linalg.inv(A)) print(invA) # + colab={"base_uri": "https://localhost:8080/"} id="YP-msnD43ow6" outputId="238df34f-c23e-4b34-d7e1-c49650b521da" C=np.dot(A,invA) print(C) # + colab={"base_uri": "https://localhost:8080/"} id="ntJtc2CM4tXg" outputId="2a7ce456-548d-4402-86bb-953de5679325" ##Python Program to Transpose a 3x3 Matrix A=([[6,1,1],[4,-2,5],[2,8,7]]) A = np.array ([[6,1,1],[4,-2,5],[2,8,7]]) InvOfA = np.linalg.inv(A) #To inverse Matrix A print(A) B = np.transpose(A) #To transpose Matrix A print (B) # + colab={"base_uri": "https://localhost:8080/"} id="5-bWZYJV6dm1" outputId="63be9fea-d89c-46c9-f93d-a7d6fdabe487" dot = np.dot(A, InvOfA) #Get dot product of A and its inverse print(dot) # + [markdown] id="9QBfEBKTB_75" # ##CODING ACTIVITY 3 # + colab={"base_uri": "https://localhost:8080/"} id="_5hcZgUWB9km" outputId="32c6e9cb-dc3a-4c04-8d14-4010935be594" A = np.array([[6,1,1,3],[4,-2,5,1],[2,8,7,6],[3,1,9,7]]) InvOfA = np.linalg.inv(A) #To inverse Matrix A print(A) B = np.transpose(A) #To transpose Matrix A print (B)
Matrix_Algebra.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 working_dir = '..' datasets = os.listdir(working_dir) datasets orgs = [os.path.join(working_dir, d) for d in datasets[3:6]] orgs proximities = [np.load(os.path.join(org, 'niche_proximities_sample.npy')) for org in orgs] proximities[0].shape proximities = np.concatenate(proximities)
notebooks/combine_organoid_features.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 # --- # ## Interactive Computing in Jupyter and Python with OmniSci # # ![](https://avatars1.githubusercontent.com/u/7553829?s=200&v=4) ![](https://avatars1.githubusercontent.com/u/34879953?s=200&v=4) # # ### Bio # # <NAME> is a Developer Advocate at Quansight with a passion for literate programing and a contributor to Jupyter and HoloViz. # # <NAME> is a Software Engineer at Quansight with an interest for analyzing big data with visualization tools in python. She is also a contributor to HoloViz. # # ### Abstract # # This work discusses the open source technologies used to bring Omnisci to the greater scientific python ecosystem. These efforts allow Omnisci data to be analyzed in Jupyterlab, query data from omnisci databases, interoperate with `pandas` dataframes, and visualize information. We'll walk through several computational notebooks that cover the capabilities of Omnisci interacting with different data analysis and visualization tools in Python. Throughout these exercises we'll highlight the open source packages and technologies that amplify OmniSci's abilities with tools like `ibis`, `pandas`, and `holoviews`. # ## Overview of OmniSci and the scientific python community # # OmniSci is an analytics platform designed to handle very large datasets. It leverages the processing power of GPUs alongside traditional CPUs to achieve very high performance. OmniSci combines an open-source SQL engine (OmniSciDB), server-side rendering (OmniSci Render), and web-based data visualization (OmniSci Immerse) to provide a comprehensive platform for data analysis. # # + jupyter={"source_hidden": true} __import__("graphviz").Source("""graph {layout=circo {{intake -- {ibis -- pandas}} -- {holoviews}}--hvplot geoviews--{holoviews hvplot}[style=dotted]} """) # - # <a id='available_tools'></a> # ## Tools Available for Data Science # If you are an OmniSci open source edition user, you will not have access to Immerse, but you can still explore OmniSci with the Data Science Foundation tools. # # **Ibis / Pandas** # Ibis is a productivity API for working in Python and analyzing data in remote SQL-based data stores such as OmniSciDB. Inspired by the pandas toolkit for data analysis, Ibis provides a Pythonic API that compiles to SQL. Combined with OmniSciDB scale and speed, Ibis offers a familiar but more powerful method for analyzing very large datasets "in-place." # Ibis supports multiple SQL databases backends, and also supports pandas as a native backend. Combined with Altair, this integration allows you to explore multiple datasets across different data sources. # # **Holoviews / hvPlot / GeoViews** # HoloViews is an open-source Python library designed to make data analysis and visualization seamless and simple. With HoloViews, you can usually express what you want to do in very few lines of code, letting you focus on what you are trying to explore and convey, not on the process of plotting. hvPlot provides a high-level plotting API built on HoloViews that provides a general and consistent API for plotting data in common data formats such as pandas, xarray, dask, intake, NeworkX, and more. Through the Holoviews-Ibis-OmniSci workflow, its possible to interactively visualize OmniSci data without writing SQL code. GeoViews is a geographic extension of the Holoviews library which provides tools for projecting and visualizing geographic data. # # **Intake OmniSci Plugin** # [Intake](https://intake.readthedocs.io) is a lightweight package for finding, investigating, loading and disseminating data. It is a cataloging system for listing data sources, their metadata and parameters, and referencing which of driver should load each. In short, [Intake](https://intake.readthedocs.io) allows the user to specify data sources via human-readable YAML catalogs, and then transparently load them and begin analyzing data. # <a id='ibis'></a> # ## Introducing Ibis # # > Write your analytics code once, run it everywhere. # In this example, we will be using Ibis to create and manage our connection to the database. Ibis will allow us to construct complex data anlytics using a Pandas-like API. It will convert our analytics methods to a SQL query, but will push the computational burden of the query to the server. In this way, users can query extremely large databases on remote servers without heavy local computation. # # For this example we'll use a local database running inside of docker. # Connect to the database using ibis: # + from ibis.backends import omniscidb as ibis_omniscidb omnisci_client = ibis_omniscidb.connect( user='demouser', password='<PASSWORD>', host='metis.mapd.com', port=443, protocol='https', database='mapd' ) # - # ### Exploring the database using Ibis # Let's use the client to take a look at the database. # We can quickly get a list of the tables available in the database. omnisci_client.list_tables() # Now we will make a connection to the `ships_ais` table. ships = omnisci_client.table('ships_ais') display(ships) ships.head(2).execute() # You'll notice that when you inspect `ships` you see a schema object, not actual results. # Ibis won't load the data and perform any computation, but instead will leave the data in the # backend defined in the connection, and we will _ask_ the backend to perform the computations. # # This is a valuable tool when working with big data in which our client side cannot handle the # volume of data until we have reduced it. # # Let's take a quick look at information Ibis has for this table without actually pulling the data locally: # #### get the table info display(ships.info()) # #### get the table metadata display(ships.metadata()) # Ibis is converting our expression into a SQL expression. Let's take a look at the actual SQL query. print(ships.head(1000).compile()) # The table has 11.6 billion rows which we definitely can't handle locally so we can grab a subsample, then execute the query. This will bring us back the requested table as a Pandas DataFrame (we haven't asked it to perform any calculations yet). # #### execute the query ships_df = ships.head(1000).execute() print(f'Return Type: {type(ships_df)}') ships_df # Now we can immediately continue our data analytics using a Pandas DataFrame (or GeoPandas GeoDataFrame) or we can modify our Ibis query to perform some calculations before pulling back data. # <a id='advanced'></a> # ## Advanced Ibis Queries # # We can use Ibis to construct complex SQL queries and push the computation required for these queries to the server. This puts the computational burden on the server rather than the local machine, and allows for users to transform and reduce the dataset before # bringing the results back locally. # # For example, we can aggregate the number of vessels by grouping on the Vessel Type. The final `execute` statement pushes this computation to be calculated on the server and returns a Pandas DataFrame expr = ships.groupby('VesselType').aggregate(count=ships.VesselType.count()).sort_by(('count', False)).limit(20) print(expr.compile()) expr vessel_counts = expr.execute() vessel_counts # We can easily visualize this pandas dataframe in holoviews import holoviews as hv hv.extension('bokeh') hv.Bars(vessel_counts).opts(xrotation=90, width=900, height=400) # But we also can simple pass the `ibis` expression to Holoviews and it can process it. # + hv.Bars(expr).sort('count', reverse=True).compute().opts(xrotation=90, width=900, height=400) # - # Next, we can filter out the data from a single vessel. This is fairly time consuming, but the computational burden is on the server. name = '<NAME>' df = ships.filter(ships['unused_Name'] == name).execute() print(len(df)) # Our reduced dataset has 130k data points. Let's plot it and see where the *Spirit of Endeavour* has been. # # We can use GeoViews, which is a geographic extension of the Holoviews library. This will allow us to bring in some background imagery and it will also (silently) help us out with projection. # ### plotting data onto maps # `geoviews` contains tools for different web map tile services. hv.element.tiles.StamenWatercolor() + hv.element.tiles.Wikipedia() + hv.element.tiles.ESRI() import geoviews as gv import geoviews.tile_sources as gvts from holoviews.operation.datashader import datashade, shade, dynspread, rasterize import holoviews as hv gvts.StamenTerrain * dynspread(datashade(gv.Points(df, kdims=['Longitude','Latitude']), cmap=["red"])).opts(width=900, height=600) # Before moving on, we'll close our connection to the database. omnisci_client.close()
notebooks/workshop/Interactive_Computing_in_Jupyter_and_Python_part_1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # 13. Gyakorlat - Rezgésgerjesztő # 2021.05.05. # # ## Feladat: # <center><img src="gyak13_1.png" width=500/></center> # A mellékelt ábrán egy két szabadságfokú rendszer látható, melyet két merev test alkot: egy $m_1$ tömegű, $R$ sugarú tárcsa és egy $m_2$ tömegű test. A tárcsa vízszintes talajon gördül és a tömegközéppontja egy $k_1$ merevségű rugóval van a környezethez rögzítve. A másik test a gravitációs térben van és függőlegesen mozog egy súrlódásmentes megvezetés mentén, miközben a $k_2$ merevségű rugóhoz van rögzítve. A $k_2$ rugó másik vége egy idális kötélhez csatlakozik, ami egy ideális (súrlódásmentes/tömeg nélküli) csigán keresztül a tárcsa tömegközéppontjához van rögzítve. A kötél végig feszített állapotban van. # # ### Adatok: # ||| # |-------------------------------------|-------------------------------------| # | $m_0$ = 0.1 kg | $R$ = 0.3 m | # | $m_1$ = 1 kg | $e$ = 0.01 m | # | $m_2$ = 3 kg | $M_0$ = 3 Nm | # | $k_1$ = 100 N/m | $\omega$ = 30 rad/s | # | $k_2$ = 200 N/m | $\varepsilon$ = $\pi$/6 rad/s$^2$ | # # # ### Részfeladatok: # # 1. Írja fel a lineáris mátrix együtthatós mozgásegyenletet! # 2. Határozza meg a mozgástörvény állandósult állapotbeli tagját! # 3. Mekkora a $k_2$ merevségű rugóban ébredő erő legnagyobb értéke az állandósult állapotban? # 4. Határozza meg a sajátkörfrekvenciákat és a hozzátartozó sajátvektorokat! # # ## Megoldás: # ## 1. Feladat: # Kis elmozdulások esetén a lineáris mozgásegyenlet mátrixegyütthatós alakja a következő egyenlettel adható meg # # $$\mathbf{M}\mathbf{\ddot{q}}+\mathbf{C\dot{q}}+\mathbf{Kq} = \mathbf{Q^*},$$ # # ahol $\mathbf{q}$ az általános koordináták vektora, $\mathbf{M}$ a tömegmátrix, $\mathbf{C}$ a csillapítási mátrix, $\mathbf{K}$ a merevségi mátrix, a $\mathbf{Q^*}$ pedig az általános erők vektora. (Disszipatív energia nincs a rendszerben ezért a csillapítási mátrix zérus lesz.) # Első lépésként az általános koordinátákat kell meghatározni. A rendszer 2 szabadsági fokú, tehát két általános koordinátát kell definiálni, melyből az egyik az ábra alapján legyen a merev test $y$ irányú elmozdulása a másik pedig a tárcsa $\psi$ szögelfordulása: # # $$ # \mathbf{q} = \begin{bmatrix} # q_1\\ # q_2 # \end{bmatrix} = \begin{bmatrix} # y\\ # \psi # \end{bmatrix}. # $$ # # # + import sympy as sp from IPython.display import display, Math sp.init_printing() # + ## Függvények, szimbólumok definiálása m0, m1, m2, R, e, k1, k2, M0, ω, ε, g = sp.symbols("m0, m1, m2, R, e, k1, k2, M0, ω, ε, g", real=True) # Készítsünk behelyettesítési listát az adatok alapján, SI-ben adatok = [(m0, 0.1), (m1, 1), (m2, 3), (R, 0.2), (e, 0.01), (k1, 100), (k2, 200), (M0, 3), (ω, 30), (ε, sp.pi/6), (g, 9.81)] # általános koordináták t = sp.symbols("t", real=True, positive=True) y = sp.Function('y')(t) ψ = sp.Function('ψ')(t) # gerjesztés M_t = M0*sp.cos(ω*t+ε) # + ### Kinetikus energia, potenciális energia, disszipatív energia ### Először fejezzük ki a mennyiségeket az általános koordinátákkal # B pont sebessége vB = R*ψ.diff(t) # 1-es test szögsebessége ω1 = ψ.diff(t) # C pont sebessége vC = y.diff(t) # Tárcsa tehetetlenségi nyomatéka a B pontra ΘB = sp.Rational(1,2)*m1*R**2 # m0 tömeg sebessége (helyvektor deriváltja) konst = sp.symbols("konst") # konstans tag (deriválás után kiesik a kifejezésből) r0 = sp.Matrix([[e*sp.cos(ω*t)+konst],[y + e*sp.sin(ω*t)+konst]]) v0 = r0.diff(t) # tárcsa x irányú elmozdulása x = R*ψ ## Kinetikus energia T = (sp.Rational(1,2)*m1*vB**2 + sp.Rational(1,2)*ΘB*ω1**2 + sp.Rational(1,2)*m2*vC**2 + sp.Rational(1,2)*m0*v0.dot(v0)).expand().trigsimp().simplify() display(Math('T = {}'.format(sp.latex(T)))) ## Potenciális energia U = sp.Rational(1,2)*k1*(x)**2 + sp.Rational(1,2)*k2*(x-y)**2+m0*g*e*sp.sin(ω*t) display(Math('U = {}'.format(sp.latex(U)))) ## Disszipatív energia most nincs! # - ### Mátrix együtthatók legenerálása """ A tömegmátrix most nem számítható közvetlenül a kinetikus energiából, mert az excentrikus tag forgása egy álatlános erő tagot is eredményez, ami a parciális deriválásnál kiesne az egyenletből. Ilyen esetben a másodfajú Lagrange-egyenletet kell használni """ # Állítsuk elő a Lagrange-egyenletben szereplő deriváltakat # Ehhez rendezzük listába az általános koordinátákat q = [y, ψ] # Majd hozzunk létre egy 2 dimenziós nullvektort a 2 Lagrange egyenlet első két tagjának Mat = sp.zeros(2,1) for i in range(2): Mat[i] = (T.diff((q[i]).diff(t))).diff(t)-T.diff(q[i]) display(Mat) # Ebből a kétdimenziós rendszerből már könnyen kifejezhető a tömegmátrix és az általános erővektor tagja is, mivel erre az kifejezésre az alábbi írható fel (Lagrange alapján) # # $$ # \left[\begin{matrix}- e m_{0} ω^{2} \sin{\left(t ω \right)} + m_{0} \frac{d^{2}}{d t^{2}} y{\left(t \right)} + m_{2} \frac{d^{2}}{d t^{2}} y{\left(t \right)}\\\frac{3 R^{2} m_{1} \frac{d^{2}}{d t^{2}} ψ{\left(t \right)}}{2}\end{matrix}\right] = \mathbf{M\ddot{q}}-\mathbf{Q}^{m_0}(t) # $$ # # Tehát a tömegmátrix az általános erővektor második időszerinti deriváltjának az együttható mátrixa, míg az excentrikus forgómozgásból származó általános erő tag az inhomogenitást okozó tag. # + # nullmátrix létrehozása a tömegmátrixnak és az erővektornak M = sp.zeros(2) Q = sp.zeros(2,1) # általános koordináták második deriváltja ddq = sp.Matrix([y.diff(t,2), ψ.diff(t,2)]) for i in range(2): for j in range(2): M[i,j] = Mat[i].expand().coeff(ddq[j]) Q_m0 = (M*ddq).expand()-Mat.expand() display(Math('Q^{{m_0}} = {}'.format(sp.latex(Q_m0)))) display(Math('M = {}'.format(sp.latex(M)))) # + ## Merevségi mátrix már közvetlenül kapható a potenciális energiából # nullmátrix létrehozása a merevségi mátrixnak K = sp.zeros(2,2) # nullmátrix feltöltése a megfelelő parciális derivált értékekkel for i in range(2): for j in range(2): K[i,j] = U.expand().diff(q[i]).diff(q[j]) display(Math('K = {}'.format(sp.latex(K)))) # + ### Az általános erővektor másik tagja a külső erők teljesítményéből számítható # Ebben a feladatban csak az M(t) nyomaték működik külső erőként, ennek teljesítménye pedig a következő: P = -M_t*ψ.diff(t) """Ebből a külső erők vektora kapható ha vesszük az általános koordináták deriváltjainak az együtthatóit a megfelelő helyen""" Q_M = sp.zeros(2,1) for i in range(2): Q_M[i] = P.expand().coeff(q[i].diff(t)) Q_M # + ## Az általános erő a két erő tag összegéből kapható Q = Q_M+Q_m0 display(Math('Q = {}'.format(sp.latex(Q)))) """Az általános erő szétszedhető sin-os és cos-os tagokra, (ez a sajátkörfrekvencia számolásnál egy fontos lépés lesz). Ehhez először használjuk a trig_expand() parancsot, hogy kibontsuk a cos-os tagot""" Q[1] = sp.expand_trig(Q[1]) display(Math('Q = {}'.format(sp.latex(Q)))) # Majd szedjuk ki a sin(tω) és cos(tω) együtthatóit Fc = sp.zeros(2,1) Fs = sp.zeros(2,1) for i in range(2): Fc[i] = Q[i].expand().coeff(sp.cos(ω*t)) Fs[i] = Q[i].expand().coeff(sp.sin(ω*t)) display(Math('F_s = {}'.format(sp.latex(Fs)))) display(Math('F_c = {}'.format(sp.latex(Fc)))) # - # Ezzel a mozgásegyenlet # # $$\mathbf{M}\mathbf{\ddot{q}}+\mathbf{Kq} = F_s\sin(\omega t)+F_c\cos(\omega t).$$ # # ## 2. Feladat # A harmonikus gerjesztés miatt a partikuláris megoldást harmonikus próbafüggvény segaítségével keressük: # # $$ # \mathbf{q}(t) = \mathbf{L}\cos(\omega t)+\mathbf{N}\sin(\omega t). # $$ # # Ennek a deriváltjai: # # $$ # \mathbf{\dot{q}}(t) = -\omega\mathbf{L}\sin(\omega t)+\omega\mathbf{N}\cos(\omega t), # $$ # # $$ # \mathbf{\ddot{q}}(t) = -\omega^2\mathbf{L}\cos(\omega t)-\omega^2\mathbf{N}\sin(\omega t). # $$ # # Visszaírva a próbafüggvényt és a deriváltjait a mozgásegyenletbe, majd a $\sin(\omega t)$ és $\cos(\omega t)$ együtthatókat összegyűjtve adódik az egyenletrendszer $\mathbf{L}$-re és $\mathbf{N}$ -re: # # $$ # \begin{bmatrix} # -\omega^2\mathbf{M}+ \mathbf{K} & \mathbf{0}\\ # \mathbf{0} & -\omega^2\mathbf{M}+ \mathbf{K} # \end{bmatrix} \begin{bmatrix} # \mathbf{L}\\ # \mathbf{N} # \end{bmatrix} = \begin{bmatrix} # \mathbf{F}_c\\ # \mathbf{F}_s # \end{bmatrix}. # $$ # + ### Oldjuk meg az egyenletrendszert # Hozzunk létre szimbolikusan vektorokat a megoldásnak L1, L2, N1, N2 = sp.symbols("L1, L2, N1, N2") L = sp.Matrix([[L1],[L2]]) N = sp.Matrix([[N1],[N2]]) # Megoldás L_sol = sp.solve(((-ω**2*M+K)*L-Fc).subs(adatok)) N_sol = sp.solve(((-ω**2*M+K)*N-Fs).subs(adatok)) L[0] = L_sol[L1].evalf(4) L[1] = L_sol[L2].evalf(4) N[0] = N_sol[N1].evalf(4) N[1] = N_sol[N2].evalf(4) # írjuk be a partikuláris megoldásba az eredményeket q_p = (L*sp.cos(ω*t)+N*sp.sin(ω*t)).expand().subs(adatok) display(Math('\mathbf{{q}}_p = {}'.format(sp.latex(q_p)))) # - # ## 3. Feladat # + ## A rugerő maximumánál figyelembe kell venni a statikus és dinamikus részt is # Statikus deformációból adódó rész: Fk2_st = ((m0+m2)*g).subs(adatok).evalf(4) display(Math('F_\\mathrm{{k2,st}} = {}\\ \mathrm{{N}}'.format(sp.latex(Fk2_st)))) # A dinamikus rész numerikusan könnyen számítható import numpy as np t_val = np.linspace(0,0.5,1000) # lista létrehozása a [0 ; 0,5] intervallum 1000 részre való bontásával Fk2_din = np.zeros(len(t_val)) # nulla lista létrehozása (ugyanannyi elemszámmal) # dinamikus tag számítása adott időpillanatban for i in range(len(t_val)): Fk2_din[i] = (k2*(R*q_p[1]-q_p[0])).subs(adatok).subs(t,t_val[i]).evalf() Fk2_din_max = max(Fk2_din).round(2) # Dinamikus tag display(Math('F_\\mathrm{{k2,din,max}} = {}\\ \mathrm{{N}}'.format(sp.latex(Fk2_din_max)))) # Az erő maximuma Fk2_max = (Fk2_din_max + Fk2_st).evalf(4) display(Math('F_\\mathrm{{k2,max}} = {}\\ \mathrm{{N}}'.format(sp.latex(Fk2_max)))) # - # ## 4. Feladat # + ## A sajátfrekvenciák a frekvencia egyenletből kaphatók ω_n2, ω_n = sp.symbols("ω_n2, ω_n") # oldjuk meg az egyenletet `ω_n^2`-re, majd vonjunk gyököt ω_n2_val = sp.solve((-ω_n2*M+K).subs(adatok).det()) ω_n = [(sp.sqrt(i)) for i in ω_n2_val] display(Math('ω_{{n,1}} = {}\\ \mathrm{{rad/s}}'.format(sp.latex(ω_n[0].evalf(3))))) display(Math('ω_{{n,2}} = {}\\ \mathrm{{rad/s}}'.format(sp.latex(ω_n[1].evalf(4))))) # + ## lengéskép vektorok meghatározása # Hozzunk létre a lengésképvektoroknak egy üres listát, majd töltsük fel 2 lengésképvektorral, melyek első elemme 1 A = [] A2 = sp.symbols("A2") for i in range(2): A.append(sp.Matrix([[1],[A2]])) # oldjuk meg az egyenletet a lengésképekre és írjuk be a megoldásokat a lengésképvektorba (2. koordináta) A[i][1] = sp.solve((((-ω_n[i]**2*M+K)*A[i]).subs(adatok))[0])[0] display(Math('A_{{1}} = {}\\begin{{bmatrix}}\\mathrm{{m}} \\\\ \\mathrm{{rad}}\\end{{bmatrix}} '.format(sp.latex(A[0].evalf(3))))) display(Math('A_{{2}} = {}\\begin{{bmatrix}}\\mathrm{{m}} \\\\ \\mathrm{{rad}}\\end{{bmatrix}} '.format(sp.latex(A[1].evalf(4))))) # - # Készítette: # # <NAME> (Alkalmazott Mechanika Szakosztály) # <NAME> (BME MM) kidolgozása alapján. # # <NAME>: # <EMAIL> # <EMAIL> # <EMAIL> # # 2021.05.05. #
13_tizenharmadik_het/gyak_13.ipynb
# --- # title: "Function Annotation Examples" # author: "<NAME>" # date: 2017-12-20T11:53:49-07:00 # description: "Function annotation examples in Python.." # type: technical_note # draft: false # 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 Function With Annotations ''' Create a function. The argument 'text' is the string to print with the default value 'default string' and the argument The argument 'n' is an integer of times to print with the default value of 1. The function should return a string. ''' def print_text(text:'string to print'='default string', n:'integer, times to print'=1) -> str: return text * n # ## Run The Function # Run the function with arguments print_text('string', 4) # Run the function with default arguments print_text()
docs/python/basics/function_annotation_examples.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="f3PPrXAsAWMu" colab_type="text" # # Tarea 4: Optimización # # ## <NAME> # # # Select from train set[0] and train set[1] the set of observations $S = \{(x_i, y_i\}$ with $x_i ∈ R^{784}$ and $y_i ∈ \{0, 1\}$ and estimate the parameters $\beta,\ \beta_0$ that maximizes the function # # $$ # h(\beta, \beta_0)= \sum_{i=1}^{n} y_i log\pi_i + (1-y_i)log(1-\pi_i) # $$ # # $$ # pi_i:= pi_i(\beta, \beta_0) = \frac{1}{1 + \exp(-x_i^T \beta - \beta_0)} # $$ # # using the set $S$. Select one optimization method implemented in the home- # work for computing $\beta, \beta_0$. # # Select from test $set[0]$ and test $set[1]$ the set $T = {(x_i , y_i )}$ such that $x_i \in R^{784}$ and $y_i ∈ {0, 1}$ and compute the error # # $$ # error = \frac{1}{|\tau|} \sum_{x_i,y_i \in \tau} |1_{\pi_i(\beta, \beta_0) > 0.5} (x_i) - y_i| # $$ # # where $|\tau|$ represents the number of elements of the set $\tau$. # # # + [markdown] id="mY9LpBa6DE91" colab_type="text" # ## Lectura de datos # + id="zvrBc979AHgH" colab_type="code" colab={} # %matplotlib inline # + id="8a1C-NqdAHg9" colab_type="code" colab={} import time from typing import Callable, Dict, Tuple from collections import namedtuple import numpy as np import matplotlib.pyplot as plt # + id="T2GdJw3SAHhX" colab_type="code" outputId="c7952e7b-e038-44ed-856e-c47534a36778" colab={"base_uri": "https://localhost:8080/", "height": 69} import gzip, pickle with gzip.open('mnist.pkl.gz','rb') as ff : u = pickle._Unpickler( ff ) u.encoding = 'latin1' train, val, test = u.load() print( train[0].shape, train[1].shape ) print( val[0].shape, val[1].shape ) print( test[0].shape, test[1].shape ) # + id="-QWFSlxOAHhs" colab_type="code" outputId="7abae6b7-80fc-42c2-a1be-6f3b98b6e702" colab={"base_uri": "https://localhost:8080/", "height": 282} idimg = 10 im = train[0][idimg,:].reshape(-1, 28) plt.imshow(im) print('clase: ', train[1][idimg]) # + [markdown] id="SQ578sQgAHh-" colab_type="text" # ## Select data # + id="oBa5t4ZXDfTn" colab_type="code" colab={} def select_01(data, normalize=False): index_data = np.logical_or(data[1] == 0, data[1] == 1) x = data[0][index_data] y = data[1][index_data] if normalize: x /= np.linalg.norm(x, axis=1)[:,None] return x, y # + id="W6u6Fr6kDhD1" colab_type="code" outputId="f06e8e59-af2e-4076-aafb-fcbe2aceb8da" colab={"base_uri": "https://localhost:8080/", "height": 34} x_train, y_train = select_01(train, normalize=False) x_train.shape, y_train.shape # + id="uoDdHM8FELLL" colab_type="code" outputId="8154e1de-092c-4f13-ff0d-e3f9d8c8b514" colab={"base_uri": "https://localhost:8080/", "height": 34} x_val, y_val = select_01(val, normalize=False) x_val.shape, y_val.shape # + id="nKFaY5n6ENND" colab_type="code" outputId="bb2901b8-6b9e-47b3-b3b6-e27350245ef7" colab={"base_uri": "https://localhost:8080/", "height": 34} x_test, y_test = select_01(test, normalize=False) x_test.shape, y_test.shape # + [markdown] id="ssViX_qBEVW2" colab_type="text" # ## Función # + id="AaqA9Fn9EhNu" colab_type="code" colab={} def pi(w, theta): return 1.0 / (1.0 + np.exp(- w @ theta)) def f(theta, w, y, eps=1e-16): _pi = pi(w, theta) _pi2 = 1 - _pi _pi[_pi == 0] = eps _pi2[_pi2 == 0] = eps return - np.sum( y * np.log(_pi) + (1.0 - y) * np.log(_pi2) ) def f_grad(theta, w, y, eps=1.0): _pi = pi(w, theta) _pi2 = 1 - _pi return - np.sum((y * (_pi2) * w.T - (1.0 - y) * _pi * w.T), axis=1) # + id="ZZhWVAaQEjj4" colab_type="code" colab={} def to_w(x): w = np.zeros((x.shape[0], x.shape[1]+1), dtype=float) for index in range(w.shape[0]): w[index] = np.concatenate((x[index], [1.0])) return w # + id="7jTt9g72ABOm" colab_type="code" colab={} w = to_w(x_train) # + id="Z-yYZsyTA7es" colab_type="code" outputId="8d610228-04cb-4d11-cf3b-904ae55dd25e" colab={"base_uri": "https://localhost:8080/", "height": 52} print(w.shape) w[:,784] # + id="cc-i5ORgBBms" colab_type="code" colab={} beta = np.ones(w.shape[1]) # + id="7ibhT2HSBCGF" colab_type="code" outputId="7fbcee6d-33f9-413d-83f4-08bbc2968a9b" colab={"base_uri": "https://localhost:8080/", "height": 34} f(beta, w, y_train, eps=1e-6) # + id="YJlxjiOaBFAr" colab_type="code" colab={} g = f_grad(beta, w, y_train, eps=1) # + id="c3EPY79tBzBQ" colab_type="code" outputId="db05f927-5e7d-4d0a-9c17-09a4e988eef3" colab={"base_uri": "https://localhost:8080/", "height": 34} g.shape # + id="4UhF0LotEfyp" colab_type="code" outputId="a1683993-87fb-4d9f-8954-3e9c160386e1" colab={"base_uri": "https://localhost:8080/", "height": 34} np.linalg.norm(g) # + [markdown] id="XpQHUunfiAmW" colab_type="text" # ## Barzilain # + id="oEEs_Tpoh0v0" colab_type="code" colab={} def barzilai_borwein(X: np.array, f: Callable[[np.array], np.array], g: Callable[[np.array], np.array], tol_x: float=1e-12, tol_g: float=1e-12, tol_f: float=1e-12, mxitr: int=100, **kwargs): Result = namedtuple('Result', 'x_log f_log g_norm_log') # History of values computed # x_log = []; f_log = [] # stop_x_log = []; stop_f_log = []; stop_g_log = [] x_log = [] f_log = [] g_norm_log = [] x_k_prev = None; x_k = X; x_log.append(x_k) g_k_prev = None g_k = g(x_k, **kwargs.get('g_kwargs', {})) g_norm_log.append(np.linalg.norm(g_k)) f_k = f(x_k, **kwargs.get('f_kwargs', {})) f_log.append(f_k) k = 0 alpha_k = kwargs.get('alpha', 1e-2) while np.linalg.norm(g_k) > tol_g and k < mxitr: if k == 0: # h_k = H(x_k, **kwargs.get('g_kwargs', {})) # alpha_k = (g_k @ g_k) / (g_k @ h_k @ g_k) pass else: s_k1 = x_k - x_k_prev y_k1 = g_k - g_k_prev alpha_k = np.dot(s_k1, y_k1) / np.dot(y_k1, y_k1) # print(k, 'alpha', alpha_k) x_k_prev = x_k.copy() x_k = x_k_prev - alpha_k * g_k x_log.append(x_k) g_k_prev = g_k g_k = g(x_k, **kwargs.get('g_kwargs', {})) g_norm_log.append(np.linalg.norm(g_k)) f_k = f(x_k, **kwargs.get('f_kwargs', {})) f_log.append(f_k) # Stop criteria # if stop_x(x_log[-2], x_log[-1]) <= tol_x or stop_f(f_log[-2], f_log[-1]) <= tol_f: # break k += 1 return Result(np.array(x_log), np.array(f_log), np.array(g_norm_log)) # + id="j_Oyg0yHiC-r" colab_type="code" outputId="51b10d0e-4237-4a7b-9d93-4ed108194d8f" colab={"base_uri": "https://localhost:8080/", "height": 300} w = to_w(x_train) beta = np.ones(w.shape[1]) _lambda = 1 params = { 'X': beta, 'f': f, 'f_kwargs': { 'w': w, 'y': y_train, 'eps': 1e-16 }, 'g': f_grad, 'g_kwargs': { 'w': w, 'y': y_train }, 'tol_x': 1e-12, 'tol_f': 1e-12, 'tol_g': 1e-12, 'alpha': 1e-3, 'mxitr': 10000 } ans = barzilai_borwein(**params) print(len(ans.x_log), len(ans.f_log), len(ans.g_norm_log)) # print(ans.x_log[-1]) plt.plot(ans.g_norm_log) # plt.plot(ans.f_log) # + [markdown] id="HD3rZAfsrrBq" colab_type="text" # # + id="bYDgl5KsyUPG" colab_type="code" outputId="26b1cb13-1381-43f5-9bfc-93504f946a69" colab={"base_uri": "https://localhost:8080/", "height": 34} ans.g_norm_log[-1] # + [markdown] id="-RZ5GPUllwGT" colab_type="text" # ## Error # + id="VTbjxK1Mrsym" colab_type="code" colab={} def aprox_error(x, y, beta): w = to_w(x) _pi = pi(w, beta) return np.mean(np.abs((_pi > 0.5) - y)) # + [markdown] id="jlvdW7NG7S02" colab_type="text" # Error de clasificación # + id="VNt0Dumq68rp" colab_type="code" outputId="34c8e743-48c1-465f-b03b-97d8b065fb83" colab={"base_uri": "https://localhost:8080/", "height": 34} aprox_error(x_test, y_test, ans.x_log[-1]) # + id="GohXTnWxuNnO" colab_type="code" outputId="71aaaebb-9874-407c-cab8-e3a1f3b62121" colab={"base_uri": "https://localhost:8080/", "height": 282} sol = np.array(ans.x_log[-1][:-1]) im = sol.reshape(-1, 28) plt.imshow(im) # + id="q75M52razyet" colab_type="code" outputId="8f9c4b53-48cc-4b70-eafe-7b3afbe4a57e" colab={"base_uri": "https://localhost:8080/", "height": 282} sol = np.array(ans.x_log[-1][:-1]) plt.plot(sol) # + id="gt0rFZJ2yQAz" colab_type="code" colab={}
Tarea 4/src/Ejercicio3.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 # --- # # Machine Learning and Statistics for Physicists # Material for a [UC Irvine](https://uci.edu/) course offered by the [Department of Physics and Astronomy](https://www.physics.uci.edu/). # # Content is maintained on [github](github.com/dkirkby/MachineLearningStatistics) and distributed under a [BSD3 license](https://opensource.org/licenses/BSD-3-Clause). # # ##### &#9658; [View table of contents](Contents.ipynb) # %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np import pandas as pd # ## Tensor Computing # Most practical algorithms of ML can be decomposed into small steps where the calculations are expressed with linear algebra, i.e., linear combinations of scalars, vectors and matrices. # # For example, a neural network can be built from layers that each calculate # $$ # \mathbf{x}_\text{out} = \max(0, W \mathbf{x}_\text{in} + \mathbf{b}) \; , # $$ # where $W$ is a matrix, and boldface symbols represent vectors. In typical applications, $\mathbf{x}_\text{out}$ and $\mathbf{x}_\text{in}$ are derived from **data** while $W$ and $\mathbf{b}$ are considered **model parameters**. (This expression is not strictly linear: why?) # # The python numeric and list types can represent arbitrary scalars, vectors, and matrices, but are designed for flexibility instead of efficiency. # # Numpy is instead optimized for the special case where all list elements are numeric values of the same type, which can be organized and accessed very efficiently in memory, with a specialized array type with lots of nice features. One downside of this approach is that most of builtin math functions are duplicated (e.g., `math.sin` and `np.sin`) to work with numpy arrays. # + [markdown] solution2="hidden" solution2_first=true # **EXERCISE:** Complete the function below using numpy to evaluate the neural-network layer defined above: # + solution2="hidden" def xout(W, xin, b): return np.maximum(0, W.dot(xin) + b) # - def xout(W, xin, b): # Add your solution here return 0 # ### Terminology # We frequently use $\mathbf{r} = (x, y, z)$ in physics to represent an *arbitrary* position in three (continuous) dimensions. # # In numpy, we cannot represent an *arbitrary* position but can easily represent a *specific* position, for example: rvec = np.array([0.1, -0.2, 0.3]) # However, `rvec` has only one (discrete) dimension, which we use to access its three array elements with indices 0,1,2: rvec[0], rvec[1], rvec[2] # Note how we use the term **dimension** differently in these two cases! # # All numpy arrays have a `shape` property that specifies the range of indices allowed for each of their (discrete) dimensions: rvec.shape rvec.ndim # Compare with a matrix represented in numpy: matrix = np.identity(3) print(matrix) matrix[1, 0], matrix[1, 1] matrix.shape matrix.ndim # Numpy supports arrays with any (finite) number of (discrete) dimensions. The general name for these arrays is a **tensor** (so, scalars, vectors and matrices are tensors). For example: tensor = np.ones((2, 3, 4)) print(tensor) tensor[0, 0, 0], tensor[1, 2, 3] tensor.shape tensor.ndim # Tensors are used in physics also: for example, the tensor expression $g^{il} \Gamma^m_{ki} x^k$ arises in [contravariant derivatives in General Relativity](https://en.wikipedia.org/wiki/Christoffel_symbols#Covariant_derivatives_of_tensors). What are the **dimensions** of $g$, $\Gamma$ and $x$ in this expression? Note that numpy tensors do not make any distinction between upper or lower indices. # The numpy dimension is sometimes also referred to as the **rank**, but note that [array rank](https://en.wikipedia.org/wiki/Rank_(computer_programming)) is similar to but subtly different from [linear algebra rank](https://en.wikipedia.org/wiki/Rank_(linear_algebra)). # ### Fundamental Operations # #### Tensor Creation # # The most common ways you will create new arrays are: # - Filled with a simple sequence of constant values # - Filled with (reproducible) random values # - Calculated as a mathematical function of existing arrays. # Regular sequence of values shape = (3, 4) c1 = np.zeros(shape) c2 = np.ones(shape) c3 = np.full(shape, -1) c4 = np.arange(12) # Reproducible "random" numbers gen = np.random.RandomState(seed=123) r1 = gen.uniform(size=shape) r2 = gen.normal(loc=-1, scale=2, size=shape) # Calculated as function of existing array. f1 = r1 * np.sin(r2) ** c3 # All the values contained within a tensors have the same [data type](https://docs.scipy.org/doc/numpy-1.15.0/user/basics.types.html), which you can inspect: c1.dtype, c4.dtype # + [markdown] solution2="hidden" solution2_first=true # **EXERCISE:** Try to guess the `dtype` of `c3`, `r2` and `f1`, then check your answer. Deep learning often uses smaller (32 or 16 bit) float data types: what advantages and disadvantages might this have? # + [markdown] solution2="hidden" # **SOLUTION:** The `zeros` and `ones` functions default to `float64`, but `full` uses the type of the provided constant value. Integers are automatically promoted to floats in mixed expressions. # + solution2="hidden" c3.dtype, r2.dtype, f1.dtype # + [markdown] solution2="hidden" # Smaller floats allow more efficient use of limited (GPU) memory and faster calculations, at the cost of some accuracy. Since the training of a deep neural network is inherently noisy, this is generally a good tradeoff. # - # #### Tensor Reshaping # # It is often useful to [reshape](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.reshape.html) a tensor without changing its total size, which can be done very efficiently since the layout of the tensor values in memory does not need to be changed: c4.reshape(c1.shape) # + [markdown] solution2="hidden" solution2_first=true # **EXERCISE:** Predict the result of `c4.reshape(2, 3, 2)` then check your answer. # + solution2="hidden" c4.reshape(2, 3, 2) # - # #### Tensor Broadcasting # # The real power of tensor computing comes from expressions like this: # Add one to each element. c4 + 1 # Scale each column of the 3x4 ones matrix by a different value. np.ones(shape=(3, 4)) * np.arange(4) # The results are not surprising in these examples, but something non-trivial is going on behind the scenes to make this work since we are combining tensors with different shapes. This is called [broadcasting](https://docs.scipy.org/doc/numpy-1.15.0/user/basics.broadcasting.html) and has specific rules for how to handle less obvious cases. # # Broadcasting serves two purposes: # - It allows more compact and easier to understand "vectorized" expressions, where loops over elements in each dimension are implicit. # - It enables automatic optimizations to take advantage of the available hardware, since explicit python loops are generally a bottleneck. # # Not all expressions can be automatically broadcast, even if they seem to make sense. For example: # Scale each row of the 3x4 ones matrix by a different value. try: np.ones(shape=(3, 4)) * np.arange(3) except ValueError as e: print(e) # However, you can usually reshape the inputs to get the desired result: np.ones(shape=(3, 4)) * np.arange(3).reshape(3, 1) # Another useful trick is to use `keepdims=True` with reducing functions, e.g. print(np.ones((4, 3)).sum(axis=1)) print(np.ones((4, 3)).sum(axis=1, keepdims=True)) # To experiment with broadcasting rules, define a function to try broadcasting two arbitrary tensor shapes: def broadcast(shape1, shape2): array1 = np.ones(shape1) array2 = np.ones(shape2) try: array12 = array1 + array2 print('shapes {} {} broadcast to {}'.format(shape1, shape2, array12.shape)) except ValueError as e: print(e) broadcast((1, 3), (3,)) broadcast((1, 2), (3,)) # + [markdown] solution2="hidden" solution2_first=true # **EXERCISE:** Predict the results of the following then check your answers: # ``` # broadcast((3, 1, 2), (3, 2)) # broadcast((2, 1, 3), (3, 2)) # broadcast((3,), (2, 1)) # broadcast((3,), (1, 2)) # broadcast((3,), (1, 3)) # ``` # + solution2="hidden" broadcast((3, 1, 2), (3, 2)) broadcast((2, 1, 3), (3, 2)) broadcast((3,), (2, 1)) broadcast((3,), (1, 2)) broadcast((3,), (1, 3)) # - # ### Tensor Frameworks # #### Numpy # # Numpy is an example of a framework for tensor computing that is widely supported and requires no special hardware. However, it still offers significant performance improvements by eliminating explicit python loops and using memory efficiently. # # For example, let's calculate the opening angle separation between two unit vectors, each specified with (lat, lon) angles in radians (or RA,DEC for astronomers, as implemented [here](https://desisurvey.readthedocs.io/en/latest/api.html#desisurvey.utils.separation_matrix)). The [Haversine formula](https://en.wikipedia.org/wiki/Haversine_formula) is a good way to calculate this quantity. # Generate a large number of random unit vectors for benchmarking (are these uniformly distributed on the sphere?) # + def generate(N, seed=123): gen = np.random.RandomState(seed=123) lats = gen.uniform(low=-np.pi / 2, high=+np.pi / 2, size=N) lons = gen.uniform(low=0, high=2 * np.pi, size=N) plt.plot(lons, lats, '.') return lats, lons lats, lons = generate(N=1000) # - # Use explicit python loops to calculate the (square) matrix of separation angles between all pairs of unit vectors: def separation_matrix_loops(): # Allocate memory for the matrix. N = len(lats) matrix = np.empty((N, N)) for i, (lat1, lon1) in enumerate(zip(lats, lons)): for j, (lat2, lon2) in enumerate(zip(lats, lons)): # Evaluate the Haversine formula for matrix element [i, j]. matrix[i, j] = 2 * np.arcsin(np.sqrt( np.sin(0.5 * (lat2 - lat1)) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(0.5 * (lon2 - lon1)) ** 2)) return matrix # %time S1 = separation_matrix_loops() # Now calculate the same separations using numpy implicit loops: def separation_matrix_numpy(): lat1, lat2 = lats, lats.reshape(-1, 1) lon1, lon2 = lons, lons.reshape(-1, 1) return 2 * np.arcsin(np.sqrt( np.sin(0.5 * (lat2 - lat1)) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(0.5 * (lon2 - lon1)) ** 2)) # %time S2 = separation_matrix_numpy() # Check that both calculations give the same results: np.allclose(S1, S2) # Since this is so much faster, increase the amount of computation (and memory) 100x for a better benchmark: lats, lons = generate(N=10000) # %time S2 = separation_matrix_numpy() # Therefore using implicit numpy loops speeds up the calculation by a factor of about 6.8 / 0.02 = 340. Since we are using the efficient numpy arrays in both cases, the speed up is entirely due to the loops! # #### Other Frameworks: PyTorch and TensorFlow # # Machine learning relies heavily on frameworks that copy the successful numpy design for tensor computing, while adding some important new features: # - Automatic hardware acceleration. # - Automatic calculation of derivatives. # - Efficient deployment to other platforms (mobile, cloud). # # Unlike numpy, the default type in these frameworks is usually a 32-bit float, rather than a 64-bit float. # # The two most popular tensor computing frameworks for machine learning today are [PyTorch](https://pytorch.org/) and [TensorFlow](https://www.tensorflow.org/). Both are large open-source projects, primarily developed by facebook (pytorch) and google (tensorflow). These frameworks were originally quite different, with pytorch preferred for research and tensorflow preferred for large-scale deployment, but they are gradually converging towards similar a feature set. # # Below, we repeat our calculation of the separation matrix with both of these frameworks. You will notice that the new features come with some additional complexity. # #### PyTorch Example import torch device = torch.device("cuda") if torch.cuda.is_available() else "cpu" print(f'Using device: {device}.') lons_pt = torch.tensor(lons, device=device) lats_pt = torch.tensor(lats, device=device) def separation_matrix_torch(): lat1, lat2 = lats_pt, lats_pt.reshape(-1, 1) lon1, lon2 = lons_pt, lons_pt.reshape(-1, 1) return 2 * torch.asin(torch.sqrt( torch.sin(0.5 * (lat2 - lat1)) ** 2 + torch.cos(lat1) * torch.cos(lat2) * torch.sin(0.5 * (lon2 - lon1)) ** 2)) # %time S3 = separation_matrix_torch() np.allclose(S2, S3.numpy()) # #### TensorFlow Example import tensorflow as tf device = 'GPU:0' if tf.config.list_physical_devices('GPU') else 'CPU:0' print(f'Using device: {device}.') with tf.device(device): lons_tf = tf.constant(lons) lats_tf = tf.constant(lats) def separation_matrix_tensorflow(): lat1, lat2 = lats_tf, tf.reshape(lats_tf, [-1, 1]) lon1, lon2 = lons_tf, tf.reshape(lons_tf, [-1, 1]) return 2 * tf.asin(tf.sqrt( tf.sin(0.5 * (lat2 - lat1)) ** 2 + tf.cos(lat1) * tf.cos(lat2) * tf.sin(0.5 * (lon2 - lon1)) ** 2)) # %time S4 = separation_matrix_tensorflow() np.allclose(S2, S4.numpy()) # #### Hardware Acceleration # Tensor computing can be sped up significantly (10-100x) using hardware that is optimized to perform tensor computing by distributing simple calculations ("kernels") across many independent processors ("cores") running in parallel. # # The original driver for such hardware was to accelerate the 3D geometry calculations required to render real time 3D graphics, leading to the first [Graphics Processing Units (GPUs)](https://en.wikipedia.org/wiki/Graphics_processing_unit) in the 1990s. More recently, GPUs have been adopted for purely numerical calculations, with no display attached, leading to the development of specialized programming languages such as [CUDA](https://en.wikipedia.org/wiki/CUDA) and [OpenCL](https://en.wikipedia.org/wiki/OpenCL). # # Currently, one vendor (Nvidia) dominates the use of GPUs for ML with its proprietary CUDA language. Google has also introduced an even more specialized [TPU](https://en.wikipedia.org/wiki/Tensor_processing_unit) architecture. # The table below shows some benchmarks for the separation matrix problem, running on different hardware with different frameworks. The speed ups obtained using PyTorch and TensorFlow with a GPU are typical. The two frameworks provide comparable GPU performance overall, but can differ on specific problems. # # # | Test | Laptop |Server(GPU) | Collab(CPU) | Collab(GPU) | # |------------|--------|------------|-------------|-------------| # | numpy | 2.08s | 1.17s | 10.5s | 10.3s | # | torch | 7.32s | 48.7ms | --- | --- | # | tensorflow | --- | --- | 9.11s | 246ms | # | ratio | 3.5 | 1 / 24 | 0.87 | 1 / 41 | # To benefit from this hardware, you can either add a GPU to a linux server, or use a cloud computing platform. # # Cloud computing is the easiest way to get started. There are some free options, but generally you have to "pay as you go" to do a useful amount of work. Some good starting points are: # - [Google Collaboratory](https://colab.research.google.com/): free research tool with a jupyter notebook front end. # - [PaperSpace](https://www.paperspace.com/): reasonably priced and simple to get started. # - [Amazon Web Services](https://aws.amazon.com/ec2/): free to try, very flexible and relatively complex. # - [Google Cloud](https://cloud.google.com/): comparable to AWS. # # **Note: this is not a complete list, and pricing and capabilities are rapidly changing.** # # If you are considering building your own GPU server, start [here](http://timdettmers.com/2018/11/05/which-gpu-for-deep-learning/). A single server can host 4 GPUs. Here is a single water-cooled [RTX 2080 Ti](https://www.nvidia.com/en-us/geforce/graphics-cards/rtx-2080-ti/) GPU installed in my office: # # ![GPU server](img/TensorComputing/GPU-server.jpg) # ### Automatic Derivatives # In addition to hardware acceleration, a key feature of tensor computing frameworks for ML is their ability to automate the calculation of derivatives, which then enable efficient and accurate gradient-based optimization algorithms. # # In general, a derivate can be implemented in software three ways: # - Analytically (using paper or mathematica) then copied into code: this is the most efficient and accurate but least generalizable. # - Numerically, with [finite difference equations](https://en.wikipedia.org/wiki/Finite_difference): this is the least efficient and accurate, but most generalizable. # - [Automatically](https://en.wikipedia.org/wiki/Automatic_differentiation): a hybrid approach where a small set of primitive functions (sin, cos, log, ...) are handled analytically, then the derivatives of expressions using these primitives are computed on the fly using the chain rule, product rule, etc. This is efficient and accurate, but requires that expressions are built entirely from primitives that support AD. # As a concrete example calculate the (un-normalized) Gaussian distribution # $$ # y(x) = e^{-x^2} # $$ # in PyTorch: x = torch.linspace(-5, 5, 20, requires_grad=True) y = torch.exp(-x ** 2) y # We specify `requires_grad=True` to enable AD for all tensors that depend on `x` (so just `y` in this case). To calculate partial derivatives ("gradients") of `y` wrt `x`, use: y.backward(torch.ones_like(y)) # The tensor `x.grad` now contains $y'(x)$ at each value of `x`: x.grad x_n = x.detach().numpy() yp_n = x.grad.detach().numpy() y_n = y.detach().numpy() plt.plot(x_n, y_n, 'o--', label='$y(x)$') plt.plot(x_n, yp_n, 'o:', label='$y^\prime(x)$') plt.legend(); # Note that these derivatives are calculated to full machine precision and not affected by the coarse spacing in $x$. # [Jax](https://github.com/google/jax) is a relatively new framework for automatic differentiation (developed by google but independent of tensorflow) that relies on "just-in-time" compilation and is designed for ML research. # ### Higher-Level APIs for Tensor Computing # Although TensorFlow and PyTorch are both similar to numpy, they have different APIs so you are forced to choose one to take advantage of their unique features. However, for many calculations they are interchangeable, and a new ecosystem of higher-level APIs is growing to support this. For example, check out: # - [Tensorly](http://tensorly.org/stable/index.html): "*Tensor learning in python*". Includes powerful [decomposition](https://arxiv.org/abs/1711.10781) (generalized PCA) and regression algorithms. # - [einops](https://github.com/arogozhnikov/einops): "*Deep learning operations reinvented*". Supports compact expressions for complex indexing operations ([np.einsum](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html) on steroids). # # Neither of these packages are included in the MLS conda environment, but I encourage you to experiment with them if you want to write framework-independent tensor code.
notebooks/TensorComputing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Copyright (c) 2021, salesforce.com, inc. \ # All rights reserved. \ # SPDX-License-Identifier: BSD-3-Clause \ # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause # **Try this notebook on [Colab](http://colab.research.google.com/github/salesforce/warp-drive/blob/master/tutorials/tutorial-2-warp_drive_sampler.ipynb)!** # # ⚠️ PLEASE NOTE: # This notebook runs on a GPU runtime.\ # If running on Colab, choose Runtime > Change runtime type from the menu, then select `GPU` in the 'Hardware accelerator' dropdown menu. # # Welcome to WarpDrive! # This is the second tutorial on WarpDrive, a PyCUDA-based framework for extremely parallelized multi-agent reinforcement learning (RL) on a single graphics processing unit (GPU). At this stage, we assume you have read our [first tutorial](https://www.github.com/salesforce/warp-drive/blob/master/tutorials/tutorial-1-warp_drive_basics.ipynb) on WarpDrive basics. # # In this tutorial, we describe **CUDASampler**, a lightweight and fast action sampler based on the policy distribution across several RL agents and environment replicas. `CUDASampler` utilizes the GPU to parallelize operations to efficiently sample a large number of actions in parallel. # # Notably: # # 1. It reads the distribution on the GPU through Pytorch and samples actions exclusively at the GPU. There is no data transfer. # 2. It maximizes parallelism down to the individual thread level, i.e., each agent at each environment has its own random seed and independent random sampling process. # 3. It runs much faster than most GPU samplers. For example, it is significantly faster than Pytorch. # # Dependencies # You can install the warp_drive package using # # - the pip package manager, OR # - by cloning the warp_drive package and installing the requirements. # # On Colab, we will do the latter. # + import sys IN_COLAB = "google.colab" in sys.modules if IN_COLAB: # ! git clone https://github.com/salesforce/warp-drive.git % cd warp-drive # ! pip install -e . else: # ! pip install rl_warp_drive # - # # Initialize CUDASampler # + import torch import numpy as np from warp_drive.managers.function_manager import CUDAFunctionManager, CUDASampler from warp_drive.managers.data_manager import CUDADataManager from warp_drive.utils.constants import Constants from warp_drive.utils.data_feed import DataFeed from warp_drive.utils.common import get_project_root _CUBIN_FILEPATH = f"{get_project_root()}/warp_drive/cuda_bin" _ACTIONS = Constants.ACTIONS # - # We first initialize the **CUDADataManager** and **CUDAFunctionManager**. To illustrate the sampler, we first load a pre-compiled binary file called "test_build.cubin". This binary is compiled with inclusion of auxiliary files in `warp_drive/cuda_includes/core` which includes several CUDA core services provided by WarpDrive. These include the backend source code for `CUDASampleController`. # # To make "test_build.fatbin" available, you need go to `warp_drive/cuda_includes` to compile this test cubin by calling # `make compile-test` # # For this notebook demonstration, in the bin folder, we already provide a pre-compiled binary. # # Finally, we initialize **CUDASampler** and assign the random seed. `CUDASampler` keeps independent randomness across all threads and blocks. Notice that `CUDASampler` requires `CUDAFunctionManager` because `CUDAFunctionManager` manages all the CUDA function pointers including to the sampler. Also notice this test binary uses 2 environment replicas and 5 agents. # + # Set logger level e.g., DEBUG, INFO, WARNING, ERROR import logging logging.getLogger().setLevel(logging.INFO) # - cuda_data_manager = CUDADataManager(num_agents=5, episode_length=10, num_envs=2) cuda_function_manager = CUDAFunctionManager( num_agents=cuda_data_manager.meta_info("n_agents"), num_envs=cuda_data_manager.meta_info("n_envs"), ) cuda_function_manager.load_cuda_from_binary_file( f"{_CUBIN_FILEPATH}/test_build.fatbin", default_functions_included=True ) cuda_sampler = CUDASampler(function_manager=cuda_function_manager) cuda_sampler.init_random(seed=None) # # Sampling # ## Actions Placeholder # Now, we feed the **actions_a** placeholder into the GPU. It has the shape `(n_envs=2, n_agents=5)` as expected. Also we make it accessible by Pytorch, because during RL training, actions will be fed into the Pytorch trainer directly. data_feed = DataFeed() data_feed.add_data(name=f"{_ACTIONS}_a", data=[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) cuda_data_manager.push_data_to_device(data_feed, torch_accessible=True) assert cuda_data_manager.is_data_on_device_via_torch(f"{_ACTIONS}_a") # ## Action Sampled Distribution # We define an action **distribution** here. During training, this distribution would be provided by the policy model implemented in Pytorch. The distribution has the shape `(n_envs, n_agents, **n_actions**)`. The last dimension `n_actions` defines the size of the action space for a particular *discrete* action. For example, if we have up, down, left, right and no-ops, `n_actions=5`. # # **n_actions** needs to be registered by the sampler so the sampler is able to pre-allocate a global memory space in GPU to speed up action sampling. This can be done by calling `sampler.register_actions()`. # # In this tutorial, we check if our sampled action distribution follows the given distribution. For example, the distribution [0.333, 0.333, 0.333] below suggests the 1st agent has 3 possible actions and each of them have equal probability. # + cuda_sampler.register_actions( cuda_data_manager, action_name=f"{_ACTIONS}_a", num_actions=3 ) distribution = np.array( [ [ [0.333, 0.333, 0.333], [0.2, 0.5, 0.3], [0.95, 0.02, 0.03], [0.02, 0.95, 0.03], [0.02, 0.03, 0.95], ], [ [0.1, 0.7, 0.2], [0.7, 0.2, 0.1], [0.5, 0.5, 0.0], [0.0, 0.5, 0.5], [0.5, 0.0, 0.5], ], ] ) distribution = torch.from_numpy(distribution).float().cuda() # + # Run 10000 times to collect statistics actions_batch = torch.from_numpy(np.empty((10000, 2, 5), dtype=np.int32)).cuda() for i in range(10000): cuda_sampler.sample(cuda_data_manager, distribution, action_name=f"{_ACTIONS}_a") actions_batch[i] = cuda_data_manager.data_on_device_via_torch(f"{_ACTIONS}_a") actions_batch_host = actions_batch.cpu().numpy() # - actions_env_0 = actions_batch_host[:, 0] actions_env_1 = actions_batch_host[:, 1] print( "Sampled actions distribution versus the given distribution (in bracket) for env 0: \n" ) for agent_id in range(5): print( f"Sampled action distribution for agent_id: {agent_id}:\n" f"{(actions_env_0[:, agent_id] == 0).sum() / 10000.0}({distribution[0, agent_id, 0]}), \n" f"{(actions_env_0[:, agent_id] == 1).sum() / 10000.0}({distribution[0, agent_id, 1]}), \n" f"{(actions_env_0[:, agent_id] == 2).sum() / 10000.0}({distribution[0, agent_id, 2]}) \n" ) # + print( "Sampled actions distribution versus the given distribution (in bracket) for env 1: " ) for agent_id in range(5): print( f"Sampled action distribution for agent_id: {agent_id}:\n" f"{(actions_env_1[:, agent_id] == 0).sum() / 10000.0}({distribution[1, agent_id, 0]}), \n" f"{(actions_env_1[:, agent_id] == 1).sum() / 10000.0}({distribution[1, agent_id, 1]}), \n" f"{(actions_env_1[:, agent_id] == 2).sum() / 10000.0}({distribution[1, agent_id, 2]}) \n" ) # - # ## Action Randomness Across Threads # Another important validation is whether the sampler provides independent randomness across different agents and environment replicas. Given the same policy model for all the agents and environment replicas, we can check if the sampled actions are independently distributed. # # Here, we assign all agents across all envs the same distribution [0.25, 0.25, 0.25, 0.25]. It is equivalent to an uniform action distribution among all actions [0,1,2,3], across 5 agents and 2 envs. Then we check the standard deviation across the agents. data_feed = DataFeed() data_feed.add_data(name=f"{_ACTIONS}_b", data=[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) cuda_data_manager.push_data_to_device(data_feed, torch_accessible=True) assert cuda_data_manager.is_data_on_device_via_torch(f"{_ACTIONS}_b") cuda_sampler.register_actions( cuda_data_manager, action_name=f"{_ACTIONS}_b", num_actions=4 ) distribution = np.array( [ [ [0.25, 0.25, 0.25, 0.25], [0.25, 0.25, 0.25, 0.25], [0.25, 0.25, 0.25, 0.25], [0.25, 0.25, 0.25, 0.25], [0.25, 0.25, 0.25, 0.25], ], [ [0.25, 0.25, 0.25, 0.25], [0.25, 0.25, 0.25, 0.25], [0.25, 0.25, 0.25, 0.25], [0.25, 0.25, 0.25, 0.25], [0.25, 0.25, 0.25, 0.25], ], ] ) distribution = torch.from_numpy(distribution).float().cuda() # + # Run 10000 times to collect statistics. actions_batch = torch.from_numpy(np.empty((10000, 2, 5), dtype=np.int32)).cuda() for i in range(10000): cuda_sampler.sample(cuda_data_manager, distribution, action_name=f"{_ACTIONS}_b") actions_batch[i] = cuda_data_manager.data_on_device_via_torch(f"{_ACTIONS}_b") actions_batch_host = actions_batch.cpu().numpy() # - actions_batch_host actions_batch_host.std(axis=2).mean(axis=0) # To check the independence of randomness among all threads, we can compare it with a Numpy implementation. Here we use `numpy.choice(4, 5)` to repeat the same process for an uniform action distribution among all actions [0,1,2,3], 5 agents and 2 envs. We should see that the variation of Numpy output is very close to our sampler. actions_batch_numpy = np.empty((10000, 2, 5), dtype=np.int32) for i in range(10000): actions_batch_numpy[i, 0, :] = np.random.choice(4, 5) actions_batch_numpy[i, 1, :] = np.random.choice(4, 5) actions_batch_numpy.std(axis=2).mean(axis=0) # ## Running Speed # The total time for sampling includes receiving a new distribution and using this to sample. # Comparing our sampler with [torch.Categorical sampler](https://pytorch.org/docs/stable/distributions.html), # we reach **7-8X** speed up for the distribution above. # # *Note: our sampler runs in parallel across threads, so this speed-up is almost constant when scaling up the number of agents or environment replicas, i.e., increasing the number of used threads.* from torch.distributions import Categorical distribution = np.array( [ [ [0.333, 0.333, 0.333], [0.2, 0.5, 0.3], [0.95, 0.02, 0.03], [0.02, 0.95, 0.03], [0.02, 0.03, 0.95], ], [ [0.1, 0.7, 0.2], [0.7, 0.2, 0.1], [0.5, 0.5, 0.0], [0.0, 0.5, 0.5], [0.5, 0.0, 0.5], ], ] ) distribution = torch.from_numpy(distribution).float().cuda() # + start_event = torch.cuda.Event(enable_timing=True) end_event = torch.cuda.Event(enable_timing=True) start_event.record() for _ in range(1000): cuda_sampler.sample(cuda_data_manager, distribution, action_name=f"{_ACTIONS}_a") end_event.record() torch.cuda.synchronize() print(f"time elapsed: {start_event.elapsed_time(end_event)} ms") # + start_event = torch.cuda.Event(enable_timing=True) end_event = torch.cuda.Event(enable_timing=True) start_event.record() for _ in range(1000): Categorical(distribution).sample() end_event.record() torch.cuda.synchronize() print(f"time elapsed: {start_event.elapsed_time(end_event)} ms") # - # # Learn More and Explore our Tutorials! # Next, we suggest you check out our advanced [tutorial](https://www.github.com/salesforce/warp-drive/blob/master/tutorials/tutorial-3-warp_drive_reset_and_log.ipynb) on WarpDrive's reset and log controller! # # For your reference, all our tutorials are here: # - [A simple end-to-end RL training example](https://www.github.com/salesforce/warp-drive/blob/master/tutorials/simple-end-to-end-example.ipynb) # - [WarpDrive basics](https://www.github.com/salesforce/warp-drive/blob/master/tutorials/tutorial-1-warp_drive_basics.ipynb) # - [WarpDrive sampler](https://www.github.com/salesforce/warp-drive/blob/master/tutorials/tutorial-2-warp_drive_sampler.ipynb) # - [WarpDrive reset and log](https://www.github.com/salesforce/warp-drive/blob/master/tutorials/tutorial-3-warp_drive_reset_and_log.ipynb) # - [Creating custom environments](https://www.github.com/salesforce/warp-drive/blob/master/tutorials/tutorial-4-create_custom_environments.md) # - [Training with WarpDrive](https://www.github.com/salesforce/warp-drive/blob/master/tutorials/tutorial-5-training_with_warp_drive.ipynb)
tutorials/tutorial-2-warp_drive_sampler.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import sys import os from os import path import math import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt from dataclasses import dataclass import json from tqdm import tqdm import plotly.graph_objs as go import pickle pd.set_option('display.max_columns', 500) from PIL import Image mpl.font_manager._rebuild() plt.rcParams['figure.figsize'] = (16 ,9) # %matplotlib inline # %config InlineBackend.figure_formats = {'png', 'retina'} import seaborn as sns # - import re def floor_int(floor_str): try: floor_int = int(re.search("\d+", floor_str).group()) except AttributeError: return -9999 if (floor_str[-1] == "B") or (floor_str[0] == "B"): return int(floor_int * (-1)) else: return int(floor_int -1) floor_int("B12") # + def build_master(): df_dirs = os.listdir("../dataframes/") for df_dir in df_dirs: paths = path.join("../dataframes/", df_dir) df = pd.DataFrame() site_data = {} for (i,p) in enumerate(os.listdir(paths)): floor = p.split("_")[1] floor = floor.split(".")[0] with open(os.path.join(paths, p), 'rb') as f: data_dict = pickle.load(f) for key in ["waypoint_df", "acce_df", "gyro_df", "magn_df", "rot_df", "wifi_df", "ibeacon_df"]: data_dict[key]["floor"] = floor_int(floor) if key == "wifi_df": data_dict[key].rename(columns={'rssi': 'wifi_rssi'}, inplace=True) elif key == "ibeacon_df": data_dict[key].rename(columns={'rssi': 'ibeacon_rssi'}, inplace=True) if key in site_data: site_data[key] = pd.concat([site_data[key], data_dict[key]], axis=0) else: site_data[key] = data_dict[key] site_master_df = site_data["acce_df"] site_master_df = pd.merge(site_master_df, site_data["waypoint_df"], on =[ "timestamp", "path_name", "floor"], how='outer') site_master_df = pd.merge(site_master_df, site_data["gyro_df"], on =[ "timestamp", "path_name", "floor"], how='outer') site_master_df = pd.merge(site_master_df, site_data["magn_df"], on =[ "timestamp", "path_name", "floor"], how='outer') site_master_df = pd.merge(site_master_df, site_data["rot_df"], on =[ "timestamp", "path_name", "floor"], how='outer') site_master_df = pd.merge(site_master_df, site_data["wifi_df"], on =[ "timestamp", "path_name", "floor"], how='outer') site_master_df = pd.merge(site_master_df, site_data["ibeacon_df"], on =[ "timestamp", "path_name", "floor"], how='outer') float_cols = ['acce_x', 'acce_y', 'acce_z','waypoint_x', 'waypoint_y', 'gyro_x', 'gyro_y', 'gyro_z', 'magn_x', 'magn_y', 'magn_z', 'rot_x', 'rot_y', 'rot_z'] site_master_df.loc[:, float_cols] = site_master_df.loc[:, float_cols].astype(np.float32) categorical_cols = ["path_name", "ssid", "bssid","uuid_major_minor"] site_master_df.loc[:, categorical_cols] = site_master_df.loc[:, categorical_cols].astype("category") wifi_df = site_master_df.loc[:, ["timestamp", "ssid","bssid", "wifi_rssi"]].dropna() waypoint_df = site_master_df.loc[:, ["timestamp", "waypoint_x","waypoint_y", "floor"]].dropna() # site_master_df["floor"] = list(map(floor_int, site_master_df["floor"])) display(site_master_df) return site_master_df, waypoint_df, wifi_df master, waypoint, wifi = build_master() # - waypoint
notebooks/Untitled1.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 # --- # # Case8-challenge00_pix2wcs # # Modified version from Case7-0challengef by <NAME>. # # In this note, we estimate the field parameters and distortion parameters from the observed positions on the focal plane in the overlapped plates. We also use reference stars (Gaia stars) whose sky coordinates are known in a certain accuracy. The SIP-convention distortion is considered in this note. # ## Preparation # First, we load the data from https://github.com/xr0038/jasmine_warpfield/tree/master/challenge/case8. # + import astropy.io.ascii as asc import astropy.units as u objects = asc.read('/Users/dkawata/work/obs/projs/JASMINE-Mission/analysis-testing-e2e/jasmine_warpfield/challenge/case8/case8_challenge_00.txt') #consists of x (um), y (um), catalog_id, ra (deg), dec (deg), and field. pointings = asc.read('/Users/dkawata/work/obs/projs/JASMINE-Mission/analysis-testing-e2e/jasmine_warpfield/challenge/case8/case8_challenge_00_pointing.txt') # consists of field, ra (deg), dec (deg), and pa (deg). # - # We can convert the units of x and y from um to pix with assuming the pixel size to be 15 um. However, we will use um unit for the detector coordinates. The input data are created with Sip definition of crpix=[0,0] and origin=1, which map the origin to [0 um, 0 um]. pix_size = 15.*u.um # objects['x'] = (objects['x']/pix_size).si # objects['y'] = (objects['y']/pix_size).si # objects: x (px), y (px), catalog_id, ra (deg), dec (deg), and field. # pointings: field, ra (deg), dec (deg), and pa (deg). # Then, we change the ids for easy handling. # + from astropy.table import unique import numpy as np ids = unique(objects, keys='catalog_id')['catalog_id'] objects.add_column(-1, name='id') for i in range(0, np.size(ids)): pos = np.where(objects['catalog_id']==ids[i]) objects['id'][pos] = i objects.remove_column('catalog_id') objects.rename_column('id', 'catalog_id') # - # Here, we make some arrays for further analysis. One new array is true_radec which stores true ra/dec values. Duplicated information (rows for the same object) is removed, and the rows are sorted with object ids. Another new array is observed_xy. It contains field ids, observed x/y positions on the focal plane, catalog ids. We rename ra, dec to ra_est, dec_est to store the estimated sky positions. # + true_radec = objects['catalog_id', 'ra', 'dec'].copy() true_radec.sort('catalog_id') true_radec = unique(true_radec, keys='catalog_id') # consists of catalog_id, ra (deg), and dec (deg). observed_xy = objects['field', 'x', 'y', 'catalog_id', 'ra', 'dec'].copy() # observed_xy.rename_column('ra', 'ra_est') # observed_xy.rename_column('dec', 'dec_est') observed_xy.add_column(observed_xy['ra'], name='ra_est') observed_xy.add_column(observed_xy['dec'],name='dec_est') # observed_xy will have field, x (px), y (px), catalog_id, and estimated ra/dec (deg). # initializing ra_est and dec_est observed_xy['ra_est'] = 0.0 observed_xy['dec_est'] = 0.0 # - # In addition, we make another array which stores field parameters, ra and dec (deg) of the origin of the pointing and position angle, pa (deg). The plate scale, um pixel scale to deg in the sky, is assumed to be the same value for all plates. At this time, an approximated (initial guess) value is stored in a variable (plate_scale). field_params = pointings.copy() # field, ra (deg), dec (deg), and pa (deg). true_field_params = field_params.copy() # field_params['pa'] -= 240.0 # offset? # plate_scale = 8.e-6*u.deg*(pix_size/u.um).si # in deg/pix plate_scale = 8.e-6*u.deg/u.um print(plate_scale) # Let's check the object distribution on sky. # + import matplotlib.pylab as plt import numpy as np color = ['red', 'blue', 'green', 'orange'] for i in range(0, np.max(field_params['field'])+1): pos = np.where(objects['field']==i) plt.scatter(objects['ra'][pos], objects['dec'][pos], marker='o', facecolor='None', edgecolor=color[i], s=10*i+10) plt.xlabel('ra (deg)') plt.ylabel('dec (deg)') # - # We can see that the data consists of four image plates (different colours indicating the objects observd by the different plantes) and that the overlapped region has a size of about a 1/4 FoV. # We select the objects in the overlapped region for further analysis. Here, we select the regions all 4 plates overlaps, but we can use the region overlapped with at least 2 plates. true_radec_overlap = true_radec.copy() observed_xy_overlap = observed_xy.copy() for cid in true_radec['catalog_id']: if np.count_nonzero(observed_xy['catalog_id']==cid)!=4: # if np.count_nonzero(observed_xy['catalog_id']==cid)<=1: pos = np.where(true_radec_overlap['catalog_id']==cid)[0] true_radec_overlap.remove_rows(pos) pos = np.where(observed_xy_overlap['catalog_id']==cid)[0] observed_xy_overlap.remove_rows(pos) print(' The number of overlapped unique stars =', len(true_radec_overlap)) print(' The total number of observations of these overlapped stars =', len(observed_xy_overlap)) # Let's check the distribution of the selected unique objects. plt.scatter(true_radec_overlap['ra'], true_radec_overlap['dec'], marker='o', facecolor='None', edgecolor='orange') plt.xlabel('ra (deg)') plt.ylabel('dec (deg)') print(len(true_radec_overlap['ra'])) # These objects will be used for the following analysis. # We again modify the catalog id for easy handling. # + ids = unique(true_radec_overlap, keys='catalog_id')['catalog_id'] true_radec_overlap.add_column(-1, name='id') observed_xy_overlap.add_column(-1, name='id') for i in range(0, np.size(ids)): pos = np.where(true_radec_overlap['catalog_id']==ids[i]) true_radec_overlap['id'][pos] = i pos = np.where(observed_xy_overlap['catalog_id']==ids[i]) observed_xy_overlap['id'][pos] = i true_radec_overlap.remove_column('catalog_id') true_radec_overlap.rename_column('id', 'catalog_id') observed_xy_overlap.remove_column('catalog_id') observed_xy_overlap.rename_column('id', 'catalog_id') # - # ## First guess of the positions # At first, we define a wcs constructor, including SIP polynomial distortion convention, https://irsa.ipac.caltech.edu/data/SPITZER/docs/files/spitzer/shupeADASS.pdf and https://docs.astropy.org/en/stable/api/astropy.wcs.Sip.html. # + from astropy.wcs import WCS from astropy.wcs import Sip import astropy.units as u def wcs(ra_ptg, dec_ptg, pa_ptg, scale, a=None, b=None, ap=None, bp=None): w = WCS(naxis=2) w.wcs.crpix=[0,0] w.wcs.cdelt=np.array([-scale, scale]) w.wcs.crval=[ra_ptg, dec_ptg] w.wcs.ctype=["RA---TAN-SIP", "DEC--TAN-SIP"] w.wcs.pc=[[ np.cos(pa_ptg*u.deg), -np.sin(pa_ptg*u.deg)], [np.sin(pa_ptg*u.deg), np.cos(pa_ptg*u.deg)]] # if a is not None and b is not None: w.sip = Sip(a, b, ap, bp, [0, 0]) return w # - # Then, we estimate the sky coordinates from the observed focal-plane positions and (approximated) field parameters. Here, we do not add the distorption, but naively convert pixel coordinate (x, y) to sky coordinate, ($\alpha$, $\delta$) (ra_est, dec_est). for i in range(0, np.size(field_params)): fp = field_params[i] w = wcs(fp['ra'], fp['dec'], fp['pa'], plate_scale.value) pos = np.where(observed_xy_overlap['field']==fp['field']) ret = w.all_pix2world(np.concatenate(([observed_xy_overlap[pos]['x']], [observed_xy_overlap[pos]['y']])).T, 0) observed_xy_overlap['ra_est'][pos] = ret[:, 0] observed_xy_overlap['dec_est'][pos] = ret[:, 1] # Let's check the true positions and estimated positions. plt.scatter(true_radec_overlap['ra'], true_radec_overlap['dec'], marker='x', label='True') plt.scatter(observed_xy_overlap['ra_est'], observed_xy_overlap['dec_est'], marker='+', label='Estimated') print(' number of stars used =', len(observed_xy_overlap['ra_est'])) plt.xlabel('ra (deg)') plt.ylabel('dec (deg)') plt.legend() # Test for distortion with A/B, using the following c and d. # + c = np.zeros(shape=(3, 3)) d = np.zeros(shape=(3, 3)) c[0,2]=-2.34153374723336e-09 c[1,1]=1.5792128155073916e-08 c[1,2]=7.674347291529089e-15 c[2,0]=-4.694743859349522e-09 c[2,1]=5.4256004358596465e-15 c[2,2]=-4.6341769281246224e-21 d[0,2]=-1.913280244657798e-08 d[1,1]=-5.622875292409728e-09 d[1,2]=-1.0128311203344238e-14 d[2,0]=3.1424733259527392e-09 d[2,1]=-9.08024075521211e-15 d[2,2]=-1.4123037013352912e-20 # - # We check if all_pix2world takes into account SIP parameters of A and B by comparing ($\alpha$, $\delta$) converted from (x, y) pixel coordinate without distortion (above observed_xy_overlap['ra_est'] and observed_xy_overlap['dec_est']) and ($\alpha$, $\delta$) converted from (x, y) pixel coordinate with A and B, ra_dist, dec_dist below. # + # print(observed_xy_overlap['ra_est']) c *= 100.0 ra_dist = np.zeros_like(observed_xy_overlap['ra_est']) dec_dist = np.zeros_like(observed_xy_overlap['dec_est']) for i in range(0, np.size(field_params)): fp = field_params[i] w = wcs(fp['ra'], fp['dec'], fp['pa'], plate_scale.value, a=c, b=d) pos = np.where(observed_xy_overlap['field']==fp['field']) ret = w.all_pix2world(np.concatenate(([observed_xy_overlap[pos]['x']], [observed_xy_overlap[pos]['y']])).T, 0) ra_dist[pos] = ret[:,0] dec_dist[pos] = ret[:,1] print(' diff ra=', ra_dist-observed_xy_overlap['ra_est']) print(' diff dec=', dec_dist-observed_xy_overlap['dec_est']) plt.scatter(ra_dist, dec_dist, marker='x', label='Distorted') plt.scatter(observed_xy_overlap['ra_est'], observed_xy_overlap['dec_est'], marker='+', label='No distortion') print(' number of stars used =', len(observed_xy_overlap['ra_est'])) plt.xlabel('ra (deg)') plt.ylabel('dec (deg)') plt.legend() # - # Check if these stars cover the large enough detector region by looking at their (x, y) position in the detector coordinate. plt.scatter(objects['x'], objects['y'], marker='x', label='All', s=5) print(' number of all stars=', len(objects['x'])) plt.scatter(observed_xy_overlap['x'], observed_xy_overlap['y'], marker='+', label='Overlap') plt.xlabel('x (pix)') plt.ylabel('y (pix)') # Here, there are four estimated (ignoring distortion) positions, (observed_xy_overlap['ra_est'], observed_xy_overlap['dec_est']), in the sky coordinate for each unique object. We take their mean values as the first-guess positions and store them in radec_est array. # + from astropy.table import Table radec_est = Table(names=['catalog_id', 'ra_est', 'dec_est'], \ dtype=['int64', 'float64', 'float64']) # units=[None, u.deg, u.deg], \ # dtype=['int64', 'float64', 'float64']) radec_est['ra_est'].unit = u.deg radec_est['dec_est'].unit = u.deg cat_ids = unique(observed_xy_overlap, 'catalog_id')['catalog_id'] for i in cat_ids: pos = np.where(observed_xy_overlap['catalog_id'] == i) ra = np.mean(observed_xy_overlap[pos]['ra_est'])*u.deg dec = np.mean(observed_xy_overlap[pos]['dec_est'])*u.deg radec_est.add_row([i, ra, dec]) # print('radec_est=', radec_est) # - # Let's check the estimated positions. plt.scatter(true_radec_overlap['ra'], true_radec_overlap['dec'], marker='x', label='True') plt.scatter(radec_est['ra_est'], radec_est['dec_est'], marker='+', label='First guess') plt.xlabel('ra (deg)') plt.ylabel('dec (deg)') plt.legend() # ## Parameter adjustment # At first, we define a function which calculates x/y positions from the ra/dec values estimated above and the field/catalog ids. def xy_calculator(observed_xy, field_params, plate_scale, ap, bp, radec_info): # observed_xy: consists of field, x (px), y (px), catalog_id, ra_est (deg), and dec_est(deg). # field_params: consists of field, ra (deg), dec (deg), and pa (deg). # radec_info: consists of catalog_id, ra_est (deg), and dec_est (deg). observed_xy_cp = observed_xy.copy() observed_xy_cp.rename_column('x', 'x_est') observed_xy_cp.rename_column('y', 'y_est') observed_xy_cp['x_est'] = None observed_xy_cp['y_est'] = None observed_xy_cp['ra_est'] = None observed_xy_cp['dec_est'] = None for i in range(0, np.size(radec_info)): pos = np.where(observed_xy_cp['catalog_id']==radec_info[i]['catalog_id']) observed_xy_cp['ra_est'][pos] = radec_info[i]['ra_est'] observed_xy_cp['dec_est'][pos] = radec_info[i]['dec_est'] for i in range(0, np.size(field_params)): fp = field_params[i] w = wcs(fp['ra'], fp['dec'], fp['pa'], plate_scale, ap=ap, bp=bp) pos = np.where(observed_xy_cp['field']==fp['field']) radec0 = np.concatenate(([observed_xy_cp[pos]['ra_est']], [observed_xy_cp[pos]['dec_est']])).T ret = w.sip_foc2pix(w.wcs_world2pix(radec0, 1)-w.wcs.crpix, 1) observed_xy_cp['x_est'][pos] = ret[:, 0] observed_xy_cp['y_est'][pos] = ret[:, 1] return observed_xy_cp['x_est', 'y_est'] # Next, we define a function to map from (x, y) pixel coordinate to ($\alpha$, $\beta$), using A/B Sip distortion parameters using wcs.all_pix2world, https://docs.astropy.org/en/stable/api/astropy.wcs.WCS.html#astropy.wcs.WCS.all_pix2world with input field parameters of $\alpha_{\rm ptgs}$ (deg), $\delta_{\rm ptgs}$ (deg) and pa$_{\rm ptgs}$ (deg) of each field (plate) pointing. This conversion is described as follows. Here, we follow the description at https://www.stsci.edu/itt/review/DrizzlePac/HTML/ch33.html # #### Definition # # CRVAL1: $\alpha_{\rm ptgs}$ right assension at the pointing centre. # # CRVAL2: $\delta_{\rm ptgs}$ declination at the pointing centre. # # CRPIX1: the x reference location of the image plate, corresponding to the pointing centre. We set CRPIX1=0. # # CRPIX2: the yu reference location of the image plate, corresponding to the pointing centre. We set CRPIX2=0. # # wcs compute the sky coordidate, ($\alpha$, $\delta$) of star at (x, y) on the detector as follows. # # We # # $ # \begin{pmatrix} # \alpha \\ # \delta \\ # \end{pmatrix} # = # \begin{pmatrix} # \cos({\rm pa_{ptgs}}) & -\sin({\rm pa_{ptgs}}) \\ # \sin({\rm pa_{ptgs}}) & \cos({\rm pa_{ptgs}}) \\ # \end{pmatrix} # $ def radec_calculator_ab(observed_xy, field_params, plate_scale, a, b): # observed_xy: consists of field, x (px), y (px), catalog_id, ra_est (deg), and dec_est(deg). # field_params: consists of field, ra (deg), dec (deg), and pa (deg). observed_xy_cp = observed_xy.copy() # observed_xy_cp.rename_column('x', 'x_est') # observed_xy_cp.rename_column('y', 'y_est') # observed_xy_cp['x_est'] = None # observed_xy_cp['y_est'] = None observed_xy_cp['ra_est'] = None observed_xy_cp['dec_est'] = None for i in range(0, np.size(field_params)): fp = field_params[i] w = wcs(fp['ra'], fp['dec'], fp['pa'], plate_scale, a=a, b=b) pos = np.where(observed_xy_cp['field']==fp['field']) pix0 = np.concatenate(([observed_xy_cp[pos]['x']], [observed_xy_cp[pos]['y']])).T ret = w.all_pix2world(pix0, 1) # ret = w.sip_pix2foc(w.wcs_pix2world(pix0, 1)-w.wcs.crval, 1) observed_xy_cp['ra_est'][pos] = ret[:, 0] observed_xy_cp['dec_est'][pos] = ret[:, 1] return observed_xy_cp['ra_est', 'dec_est'] # ### Using scipy.optimize least_squares, assuming the pointing sky coordinate, RA, DEC are accurately known. # Define model function to solve with Least Squares. # def model_func(params, n_fields, dim_sip, observed_xy): def model_func(params, ra_ptgs, dec_ptgs, n_fields, dim_sip, observed_xy): # params = (ra_ptgs, dec_ptgs, pa_ptg..., scale, a..., b...) pa_ptgs, scale, a, b =\ np.split(params, [n_fields, n_fields+1,\ n_fields+1+(dim_sip+1)**2]) # ra_ptgs, dec_ptgs, pa_ptgs, scale, a, b =\ # np.split(params, [n_fields, 2*n_fields, 3*n_fields, 3*n_fields+1,\ # 3*n_fields+1+(dim_sip+1)**2]) field_params = Table(data=[ra_ptgs, dec_ptgs, pa_ptgs, -np.ones(shape=(np.size(ra_ptgs)))],\ names=['ra', 'dec', 'pa', 'field'],\ dtype=['float64', 'float64', 'float64', 'int64']) # names=['ra', 'dec', 'pa', 'field'],\ # units=[u.deg, u.deg, u.deg, None],\ # dtype=['float64', 'float64', 'float64', 'int64']) field_params['ra'].unit = u.deg field_params['dec'].unit = u.deg field_params['pa'].unit = u.deg field_params['field'] = np.arange(0, np.size(field_params)) # use copy of observed_xy observed_xy_cp = observed_xy.copy() a_matrix = np.reshape(a, (dim_sip+1, dim_sip+1)) b_matrix = np.reshape(b, (dim_sip+1, dim_sip+1)) # mns = np.concatenate(((0, 1), np.arange(dim_sip+1, 2*(dim_sip)+1))) # for mn in mns: # for m in range(np.max([0, mn-dim_sip]), np.min([mn+1, dim_sip+1])): # n = mn - m # ap_matrix[m, n] = 0 # bp_matrix[m, n] = 0 # a_matrix[0, 0] = 0.0 # a_matrix[0, 1] = 0.0 # a_matrix[1, 0] = 0.0 # b_matrix[0, 0] = 0.0 # b_matrix[0, 1] = 0.0 # b_matrix[1, 0] = 0.0 m, n = np.indices((dim_sip+1, dim_sip+1)) mn = m + n a_matrix = a_matrix * (1.e-3**mn) b_matrix = b_matrix * (1.e-3**mn) # compute ra/dec from x/y with the parameters. ret = radec_calculator_ab(observed_xy_cp, field_params, scale[0], \ a_matrix, b_matrix) observed_xy_cp['ra_est'] = ret['ra_est'] observed_xy_cp['dec_est'] = ret['dec_est'] # compute the mean ra/dec for unique stars cat_ids = unique(observed_xy_cp, 'catalog_id')['catalog_id'] ra_mean = np.zeros_like(observed_xy_cp['ra_est']) dec_mean = np.zeros_like(observed_xy_cp['ra_est']) for i in cat_ids: pos = np.where(observed_xy_cp['catalog_id'] == i) ra_mean[pos] = np.mean(observed_xy_cp[pos]['ra_est'])*u.deg dec_mean[pos] = np.mean(observed_xy_cp[pos]['dec_est'])*u.deg radec_est = np.concatenate((observed_xy_cp['ra_est'], observed_xy_cp['dec_est'])) radec_est_mean = np.concatenate((ra_mean, dec_mean)) residuals = radec_est - radec_est_mean return residuals # Next, we execute the least-square calculation to derive the field parameters and sky positions of the objects in the overlapped region. # + from scipy.optimize import least_squares import time dim_sip = 4 a = np.zeros(shape=(dim_sip+1, dim_sip+1)) b = np.zeros(shape=(dim_sip+1, dim_sip+1)) # constructing a_init (initial parameter set). # a_init = np.array(np.concatenate((field_params['ra'], field_params['dec'], field_params['pa'], \ # [plate_scale.value], a.flatten(), b.flatten()))) # This must be an ndarray. a_init = np.array(np.concatenate((field_params['pa'], \ [plate_scale.value], a.flatten(), b.flatten()))) # This must be an ndarray. print(' # of fitting parameters =', len(a_init)) # constraining ra/dec values in 'observed' between -180 and 180 deg. # measured = np.concatenate((observed_xy_overlap['x'], observed_xy_overlap['y'])) # print(' # of data points =', len(measured)) #pos = np.where(measured>180.) #measured[pos] -= 360. #pos = np.where(measured<-180.) #measured[pos] += 360. start = time.time() # result = least_squares(model_func, a_init, loss='linear', args=(np.size(field_params), \ # dim_sip, observed_xy_overlap), \ # verbose=2) result = least_squares(model_func, a_init, loss='linear', args=(field_params['ra'], \ field_params['dec'], np.size(field_params), dim_sip, observed_xy_overlap), \ verbose=2) print(' time=',time.time()-start) ## pa should be a positive value between 0 and 360. #if result[3] < 0: # result[3] = -result[3] # result[2] = result[2] + 180.0 # #if result[2] > 360.0 or result[2] < 0.0: # result[2] = result[2]%360.0 # - # ### Checking results # #### Preparation # + n_fields = np.size(field_params) n_objects = np.size(radec_est) true_ra_ptgs = true_field_params['ra'].data true_dec_ptgs = true_field_params['dec'].data true_pa_ptgs = true_field_params['pa'].data # ra_ptgs, dec_ptgs, pa_ptgs, scale, a, b =\ # np.split(result.x, [n_fields, 2*n_fields, 3*n_fields, 3*n_fields+1,\ # 3*n_fields+1+(dim_sip+1)**2]) pa_ptgs, scale, a, b =\ np.split(result.x, [n_fields, n_fields+1,\ n_fields+1+(dim_sip+1)**2]) ra_ptgs = field_params['ra'].data dec_ptgs = field_params['dec'].data a_matrix = np.reshape(a, (dim_sip+1, dim_sip+1)) b_matrix = np.reshape(b, (dim_sip+1, dim_sip+1)) # A/B scaling m, n = np.indices((dim_sip+1, dim_sip+1)) mn = m + n a_matrix = a_matrix * (1.e-3**mn) b_matrix = b_matrix * (1.e-3**mn) fit_field_params = Table(data=[ra_ptgs, dec_ptgs, pa_ptgs, -np.ones(shape=(np.size(ra_ptgs)))],\ names=['ra', 'dec', 'pa', 'field'],\ dtype=['float64', 'float64', 'float64', 'int64']) fit_field_params['ra'].unit = u.deg fit_field_params['dec'].unit = u.deg fit_field_params['pa'].unit = u.deg fit_field_params['field'] = np.arange(0, np.size(field_params)) # - # #### Pointings print(' pointing centre (fit) ra, dec (deg) =', ra_ptgs, dec_ptgs) print(' pointing centre (true) ra, dec (deg) =', true_ra_ptgs, true_dec_ptgs) print(' difference ra, dec (deg) =', ra_ptgs-true_ra_ptgs, dec_ptgs-true_dec_ptgs) # #### Pointings position angles print(' position angle (fit) (deg) =', pa_ptgs) print(' position angle (true) (deg) =', true_pa_ptgs) print(' difference =', pa_ptgs-true_pa_ptgs) # #### Scale (deg/pix) scale print(' true scale =',(1e-6/7.3/np.pi*180.0)*u.deg/u.um) # print(' true scale =',(1e-6/7.3/np.pi*180.0)*u.deg*(pix_size/u.um).si) # #### A/B print(' derived A/B matrices = ', a_matrix, b_matrix) # #### Object positions # + print(' field params=', fit_field_params) radec_objs = radec_calculator_ab(observed_xy_overlap, fit_field_params, scale[0], a_matrix, b_matrix) plt.scatter(true_radec_overlap['ra'], true_radec_overlap['dec'], marker='x', label='True') plt.scatter(radec_est['ra_est'], radec_est['dec_est'], marker='+', label='Initial guess') plt.scatter(radec_objs['ra_est'], radec_objs['dec_est'], marker='.', label='Final estimation') plt.xlabel('ra (deg)') plt.ylabel('dec (deg)') plt.title('Object positions') plt.legend() # - # #### Position difference # + from astropy.coordinates import SkyCoord distlist = [] print(np.shape(radec_objs)) for i in range(0, np.size(radec_objs)): c1 = SkyCoord(radec_objs['ra_est'][i]*u.deg, radec_objs['dec_est'][i]*u.deg) c2 = SkyCoord(observed_xy_overlap['ra'][i]*u.deg, observed_xy_overlap['dec'][i]*u.deg) distlist.append(c1.separation(c2).arcsec) distlist = np.array(distlist) # - #plt.hist(np.log10(distlist)) plt.hist(distlist) plt.xlabel("Residual (arcsec)") plt.ylabel("Number") dra = ((radec_objs['ra_est']-observed_xy_overlap['ra']).data)*u.deg ddec = ((radec_objs['dec_est']-observed_xy_overlap['dec']).data)*u.deg dra_arcsec = dra.to_value(u.arcsec) ddec_arcsec = ddec.to_value(u.arcsec) plt.scatter(dra_arcsec, ddec_arcsec, marker='x') plt.xlabel('dRA (arcsec)') plt.ylabel('dDEC (arcsec)') #plt.xlim([-0,8, 0.0]) #plt.ylim([-0.8, 0.0]) # ## Not fixing pointing RA, DEC, but use the reference stars. # First, we define the model function to evaluate the difference in the sky coordinate of i-th stars, (ra, dec)i, from the individual plate, j-th plate, coordinates, (x, y)ij and the residual between (ra, dec)i and (ra, dec)k, for k-th reference stars whose (ra, dec)k is known from the other observation, e.g. Gaia. def model_wrefs_func(params, n_fields, dim_sip, observed_xy, radec_refstars): # params = (ra_ptgs, dec_ptgs, pa_ptg..., scale, a..., b...) ra_ptgs, dec_ptgs, pa_ptgs, scale, a, b =\ np.split(params, [n_fields, 2*n_fields, 3*n_fields, 3*n_fields+1,\ 3*n_fields+1+(dim_sip+1)**2]) field_params = Table(data=[ra_ptgs, dec_ptgs, pa_ptgs, -np.ones(shape=(np.size(ra_ptgs)))],\ names=['ra', 'dec', 'pa', 'field'],\ dtype=['float64', 'float64', 'float64', 'int64']) # names=['ra', 'dec', 'pa', 'field'],\ # units=[u.deg, u.deg, u.deg, None],\ # dtype=['float64', 'float64', 'float64', 'int64']) field_params['ra'].unit = u.deg field_params['dec'].unit = u.deg field_params['pa'].unit = u.deg field_params['field'] = np.arange(0, np.size(field_params)) # use copy of observed_xy observed_xy_cp = observed_xy.copy() a_matrix = np.reshape(a, (dim_sip+1, dim_sip+1)) b_matrix = np.reshape(b, (dim_sip+1, dim_sip+1)) # mns = np.concatenate(((0, 1), np.arange(dim_sip+1, 2*(dim_sip)+1))) # for mn in mns: # for m in range(np.max([0, mn-dim_sip]), np.min([mn+1, dim_sip+1])): # n = mn - m # ap_matrix[m, n] = 0 # bp_matrix[m, n] = 0 # a_matrix[0, 0] = 0.0 # a_matrix[0, 1] = 0.0 # a_matrix[1, 0] = 0.0 # b_matrix[0, 0] = 0.0 # b_matrix[0, 1] = 0.0 # b_matrix[1, 0] = 0.0 # normalisation. m, n = np.indices((dim_sip+1, dim_sip+1)) mn = m + n a_matrix = a_matrix * (1.e-3**mn) b_matrix = b_matrix * (1.e-3**mn) # compute ra/dec from x/y with the parameters. ret = radec_calculator_ab(observed_xy_cp, field_params, scale[0], \ a_matrix, b_matrix) observed_xy_cp['ra_est'] = ret['ra_est'] observed_xy_cp['dec_est'] = ret['dec_est'] # compute the mean ra/dec for unique stars cat_ids = unique(observed_xy_cp, 'catalog_id')['catalog_id'] ra_mean = np.zeros_like(observed_xy_cp['ra_est']) dec_mean = np.zeros_like(observed_xy_cp['ra_est']) for i in cat_ids: pos = np.where(observed_xy_cp['catalog_id'] == i) ra_mean[pos] = np.mean(observed_xy_cp[pos]['ra_est'])*u.deg dec_mean[pos] = np.mean(observed_xy_cp[pos]['dec_est'])*u.deg # reference stars' measured mean ra, dec to be compared # with the ra, dec of reference stars. radec_est_refstars = radec_refstars.copy() radec_est_refstars.rename_column('ra', 'ra_est') radec_est_refstars.rename_column('dec', 'dec_est') for i,id in enumerate(radec_refstars['catalog_id']): # print('i, id=', i, id) # print(ra_mean[observed_xy_cp['catalog_id'] == id][0]) radec_est_refstars[i]['ra_est'] = ra_mean[observed_xy_cp['catalog_id'] == id][0] radec_est_refstars[i]['dec_est'] = dec_mean[observed_xy_cp['catalog_id'] == id][0] radec_est = np.concatenate((observed_xy_cp['ra_est'], observed_xy_cp['dec_est'], \ radec_refstars['ra'], radec_refstars['dec'])) radec_est_mean = np.concatenate((ra_mean, dec_mean, radec_est_refstars['ra_est'], \ radec_est_refstars['dec_est'])) residuals = radec_est - radec_est_mean return residuals # Pick the reference stars from true_radec_overlap of overlap stars. # + # print(' true_radec_overlap =', true_radec_overlap) print(' len =', len(true_radec_overlap)) # number of reference stars n_refstars = 10 pos = np.random.choice(len(true_radec_overlap), size=n_refstars, replace=False) radec_refstars = true_radec_overlap[pos] print(radec_refstars) # - # Now, let's run least_squares and get the distortion parameters with the reference stars' constraints. # + from scipy.optimize import least_squares import time dim_sip = 4 a = np.zeros(shape=(dim_sip+1, dim_sip+1)) b = np.zeros(shape=(dim_sip+1, dim_sip+1)) # constructing a_init (initial parameter set). a_init = np.array(np.concatenate((field_params['ra'], field_params['dec'], \ field_params['pa'], \ [plate_scale.value], a.flatten(), b.flatten()))) # This must be an ndarray. # a_init = np.array(np.concatenate((field_params['pa'], \ # [plate_scale.value], a.flatten(), b.flatten()))) # This must be an ndarray. print(' # of fitting parameters =', len(a_init)) print(' size of reference stars =', np.size(radec_refstars['catalog_id'])) start = time.time() result = least_squares(model_wrefs_func, a_init, loss='linear', args= \ (np.size(field_params), dim_sip, observed_xy_overlap, \ radec_refstars), verbose=2) print(' time=',time.time()-start) # - # ## Checking restuls # #### Preparation # + n_fields = np.size(field_params) n_objects = np.size(radec_est) true_ra_ptgs = true_field_params['ra'].data true_dec_ptgs = true_field_params['dec'].data true_pa_ptgs = true_field_params['pa'].data ra_ptgs, dec_ptgs, pa_ptgs, scale, a, b =\ np.split(result.x, [n_fields, 2*n_fields, 3*n_fields, 3*n_fields+1,\ 3*n_fields+1+(dim_sip+1)**2]) # pa_ptgs, scale, a, b =\ # np.split(result.x, [n_fields, n_fields+1,\ # n_fields+1+(dim_sip+1)**2]) #ra_ptgs = field_params['ra'].data # dec_ptgs = field_params['dec'].data a_matrix = np.reshape(a, (dim_sip+1, dim_sip+1)) b_matrix = np.reshape(b, (dim_sip+1, dim_sip+1)) # A/B scaling m, n = np.indices((dim_sip+1, dim_sip+1)) mn = m + n a_matrix = a_matrix * (1.e-3**mn) b_matrix = b_matrix * (1.e-3**mn) fit_field_params = Table(data=[ra_ptgs, dec_ptgs, pa_ptgs, -np.ones(shape=(np.size(ra_ptgs)))],\ names=['ra', 'dec', 'pa', 'field'],\ dtype=['float64', 'float64', 'float64', 'int64']) fit_field_params['ra'].unit = u.deg fit_field_params['dec'].unit = u.deg fit_field_params['pa'].unit = u.deg fit_field_params['field'] = np.arange(0, np.size(field_params)) # - # #### Pointings RA, DEC, position angle and scale print(' pointing centre (fit) ra, dec (deg) =', ra_ptgs, dec_ptgs) print(' pointing centre (true) ra, dec (deg) =', true_ra_ptgs, true_dec_ptgs) print(' difference ra, dec (deg) =', ra_ptgs-true_ra_ptgs, dec_ptgs-true_dec_ptgs) print(' position angle (fit) (deg) =', pa_ptgs) print(' position angle (true) (deg) =', true_pa_ptgs) print(' difference =', pa_ptgs-true_pa_ptgs) print(' scale (fit, true) =', scale, (1e-6/7.3/np.pi*180.0)*u.deg/u.um) print(' difference =', scale-(1e-6/7.3/np.pi*180.0)) # Object positions # + radec_objs = radec_calculator_ab(observed_xy_overlap, fit_field_params, scale[0], a_matrix, b_matrix) plt.scatter(true_radec_overlap['ra'], true_radec_overlap['dec'], marker='x', label='True') plt.scatter(radec_est['ra_est'], radec_est['dec_est'], marker='+', label='Initial guess') plt.scatter(radec_objs['ra_est'], radec_objs['dec_est'], marker='.', label='Final estimation') plt.scatter(radec_refstars['ra'], radec_refstars['dec'], marker='o', \ label='Reference stars') plt.xlabel('ra (deg)') plt.ylabel('dec (deg)') plt.title('Object positions') plt.legend() # - # Position differences # + from astropy.coordinates import SkyCoord distlist = [] print(np.shape(radec_objs)) for i in range(0, np.size(radec_objs)): c1 = SkyCoord(radec_objs['ra_est'][i]*u.deg, radec_objs['dec_est'][i]*u.deg) c2 = SkyCoord(observed_xy_overlap['ra'][i]*u.deg, observed_xy_overlap['dec'][i]*u.deg) distlist.append(c1.separation(c2).arcsec) distlist = np.array(distlist) #plt.hist(np.log10(distlist)) plt.hist(distlist) plt.xlabel("Residual (arcsec)") plt.ylabel("Number") # - dra = ((radec_objs['ra_est']-observed_xy_overlap['ra']).data)*u.deg ddec = ((radec_objs['dec_est']-observed_xy_overlap['dec']).data)*u.deg dra_arcsec = dra.to_value(u.arcsec) ddec_arcsec = ddec.to_value(u.arcsec) plt.scatter(dra_arcsec, ddec_arcsec, marker='x') plt.xlabel('dRA (arcsec)') plt.ylabel('dDEC (arcsec)') #plt.xlim([-0,8, 0.0]) #plt.ylim([-0.8, 0.0]) # #### Apply the field parameters to all the objects. # + print(' total # of stars =', len(observed_xy)) radec_allobjs = radec_calculator_ab(observed_xy, fit_field_params, \ scale[0], a_matrix, b_matrix) plt.scatter(observed_xy['ra'], observed_xy['dec'], marker='x', label='True') plt.scatter(radec_allobjs['ra_est'], radec_allobjs['dec_est'], marker='.', label='Final estimation') plt.scatter(radec_refstars['ra'], radec_refstars['dec'], marker='o', \ label='Reference stars') plt.xlabel('ra (deg)') plt.ylabel('dec (deg)') plt.title('Object positions') plt.legend() # + distlist = [] print(np.shape(radec_allobjs)) for i in range(0, np.size(radec_allobjs)): c1 = SkyCoord(radec_allobjs['ra_est'][i]*u.deg, radec_allobjs['dec_est'][i]*u.deg) c2 = SkyCoord(observed_xy['ra'][i]*u.deg, observed_xy['dec'][i]*u.deg) distlist.append(c1.separation(c2).arcsec) distlist = np.array(distlist) #plt.hist(np.log10(distlist)) plt.hist(distlist) plt.xlabel("Residual (arcsec)") plt.ylabel("Number") # - dra = ((radec_allobjs['ra_est']-observed_xy['ra']).data)*u.deg ddec = ((radec_allobjs['dec_est']-observed_xy['dec']).data)*u.deg dra_arcsec = dra.to_value(u.arcsec) ddec_arcsec = ddec.to_value(u.arcsec) plt.scatter(dra_arcsec, ddec_arcsec, marker='x') plt.xlabel('dRA (arcsec)') plt.ylabel('dDEC (arcsec)') #plt.xlim([-0,8, 0.0]) #plt.ylim([-0.8, 0.0]) # ## With observatioal errors. # We add the observational errors for both JASMINE observations and reference stars, Gaia stars. We first add the position error + displacement for observed_xy_overlap. Then, later we will add the noise to observed_xy (all observations). The displacement for the same observation of stars should be the same between observed_xy and observed_xy_overlap. However, for now for the simplification of set up, we use independent one. # JASMINE pixel position uncertainty, let's set to 1/300 pix pix_size = 15.*u.um xy_error_jasmine = (1.0/300)*pix_size print(' JASMINE pix error (um) =', xy_error_jasmine) # Reference stars ra, dec error, let's set to 0.02 mas radec_error_refstars = (0.2*u.mas).to(u.deg) print(' Reference stars error (deg) =', radec_error_refstars) # + # add errors to JASMINE pix position # for overlap stars observed_xy_overlap.rename_column('x', 'x0') observed_xy_overlap.rename_column('y', 'y0') observed_xy_overlap.add_column(observed_xy_overlap['x0'], name='x') observed_xy_overlap.add_column(observed_xy_overlap['x0'], name='y') observed_xy_overlap['x'] = np.random.normal(observed_xy_overlap['x0'], xy_error_jasmine) observed_xy_overlap['y'] = np.random.normal(observed_xy_overlap['y0'], xy_error_jasmine) # store the noise observed_xy_overlap.add_column(observed_xy_overlap['x'], name='xy_err') # - observed_xy_overlap['xy_err'] = xy_error_jasmine # + # for all stars observed_xy.rename_column('x', 'x0') observed_xy.rename_column('y', 'y0') observed_xy.add_column(observed_xy['x0'], name='x') observed_xy.add_column(observed_xy['x0'], name='yt') observed_xy['x'] = np.random.normal(observed_xy['x0'], xy_error_jasmine) observed_xy['y'] = np.random.normal(observed_xy['y0'], xy_error_jasmine) observed_xy.add_column(observed_xy['x'], name='xy_err') # - observed_xy['xy_err'] = xy_error_jasmine # + # add errors to reference stars radec_refstars.rename_column('ra', 'ra0') radec_refstars.rename_column('dec', 'dec0') radec_refstars.add_column(radec_refstars['ra0'], name='ra') radec_refstars.add_column(radec_refstars['dec0'], name='dec') # print(' ra before noise =', radec_refstars['ra']) radec_refstars['ra'] = np.random.normal(radec_refstars['ra0'], radec_error_refstars) radec_refstars['dec'] = np.random.normal(radec_refstars['dec0'], radec_error_refstars) # print(' ra w/added noise =', radec_refstars['ra'].to_value(u.mas)) # store the noise radec_refstars.add_column(radec_refstars['ra'], name='radec_err') # - radec_refstars['radec_err'] = radec_error_refstars def model_wrefs_werr_func(params, n_fields, dim_sip, observed_xy, radec_refstars): # params = (ra_ptgs, dec_ptgs, pa_ptg..., scale, a..., b...) ra_ptgs, dec_ptgs, pa_ptgs, scale, a, b =\ np.split(params, [n_fields, 2*n_fields, 3*n_fields, 3*n_fields+1,\ 3*n_fields+1+(dim_sip+1)**2]) field_params = Table(data=[ra_ptgs, dec_ptgs, pa_ptgs, -np.ones(shape=(np.size(ra_ptgs)))],\ names=['ra', 'dec', 'pa', 'field'],\ dtype=['float64', 'float64', 'float64', 'int64']) # names=['ra', 'dec', 'pa', 'field'],\ # units=[u.deg, u.deg, u.deg, None],\ # dtype=['float64', 'float64', 'float64', 'int64']) field_params['ra'].unit = u.deg field_params['dec'].unit = u.deg field_params['pa'].unit = u.deg field_params['field'] = np.arange(0, np.size(field_params)) # use copy of observed_xy observed_xy_cp = observed_xy.copy() a_matrix = np.reshape(a, (dim_sip+1, dim_sip+1)) b_matrix = np.reshape(b, (dim_sip+1, dim_sip+1)) # mns = np.concatenate(((0, 1), np.arange(dim_sip+1, 2*(dim_sip)+1))) # for mn in mns: # for m in range(np.max([0, mn-dim_sip]), np.min([mn+1, dim_sip+1])): # n = mn - m # ap_matrix[m, n] = 0 # bp_matrix[m, n] = 0 # a_matrix[0, 0] = 0.0 # a_matrix[0, 1] = 0.0 # a_matrix[1, 0] = 0.0 # b_matrix[0, 0] = 0.0 # b_matrix[0, 1] = 0.0 # b_matrix[1, 0] = 0.0 # normalisation. m, n = np.indices((dim_sip+1, dim_sip+1)) mn = m + n a_matrix = a_matrix * (1.e-3**mn) b_matrix = b_matrix * (1.e-3**mn) # compute ra/dec from x/y with the parameters. ret = radec_calculator_ab(observed_xy_cp, field_params, scale[0], \ a_matrix, b_matrix) observed_xy_cp['ra_est'] = ret['ra_est'] observed_xy_cp['dec_est'] = ret['dec_est'] # compute the mean ra/dec for unique stars cat_ids = unique(observed_xy_cp, 'catalog_id')['catalog_id'] ra_mean = np.zeros_like(observed_xy_cp['ra_est']) dec_mean = np.zeros_like(observed_xy_cp['dec_est']) # compute weights from error in xy (um) -> radec (deg) w_observed_xy = 1.0/(observed_xy_cp['xy_err']*scale[0]) for i in cat_ids: pos = np.where(observed_xy_cp['catalog_id'] == i) ra_mean[pos] = np.average(observed_xy_cp[pos]['ra_est'], \ weights=w_observed_xy[pos])*u.deg dec_mean[pos] = np.average(observed_xy_cp[pos]['dec_est'], \ weights=w_observed_xy[pos])*u.deg # reference stars' measured mean ra, dec to be compared # with the ra, dec of reference stars. radec_est_refstars = radec_refstars.copy() radec_est_refstars.rename_column('ra', 'ra_est') radec_est_refstars.rename_column('dec', 'dec_est') # compute weights for reference stars w_refstars = 1.0/(radec_refstars['radec_err']) for i,id in enumerate(radec_refstars['catalog_id']): # print('i, id=', i, id) # print(ra_mean[observed_xy_cp['catalog_id'] == id][0]) radec_est_refstars[i]['ra_est'] = ra_mean[observed_xy_cp['catalog_id'] == id][0] radec_est_refstars[i]['dec_est'] = dec_mean[observed_xy_cp['catalog_id'] == id][0] radec_est = np.concatenate((observed_xy_cp['ra_est'], observed_xy_cp['dec_est'], \ radec_refstars['ra'], radec_refstars['dec'])) radec_est_mean = np.concatenate((ra_mean, dec_mean, radec_est_refstars['ra_est'], \ radec_est_refstars['dec_est'])) w_all = np.concatenate((w_observed_xy, w_observed_xy, w_refstars, w_refstars)) residuals = w_all*(radec_est - radec_est_mean) return residuals # Let's run least squares. # + from scipy.optimize import least_squares from scipy.optimize import leastsq import time dim_sip = 4 a = np.zeros(shape=(dim_sip+1, dim_sip+1)) b = np.zeros(shape=(dim_sip+1, dim_sip+1)) # constructing a_init (initial parameter set). a_init = np.array(np.concatenate((field_params['ra'], field_params['dec'], \ field_params['pa'], \ [plate_scale.value], a.flatten(), b.flatten()))) # This must be an ndarray. # a_init = np.array(np.concatenate((field_params['pa'], \ # [plate_scale.value], a.flatten(), b.flatten()))) # This must be an ndarray. print(' # of fitting parameters =', len(a_init)) print(' size of reference stars =', np.size(radec_refstars['catalog_id'])) start = time.time() result = least_squares(model_wrefs_werr_func, a_init, loss='linear', args= \ (np.size(field_params), dim_sip, observed_xy_overlap, \ radec_refstars), verbose=2) # result = least_squares(model_wrefs_werr_func, a_init, args= \ # (np.size(field_params), dim_sip, observed_xy_overlap, \ # radec_refstars)) print(' time=',time.time()-start) # - # ## Checking results # Extract the results. # + n_fields = np.size(field_params) n_objects = np.size(radec_est) true_ra_ptgs = true_field_params['ra'].data true_dec_ptgs = true_field_params['dec'].data true_pa_ptgs = true_field_params['pa'].data ra_ptgs, dec_ptgs, pa_ptgs, scale, a, b =\ np.split(result.x, [n_fields, 2*n_fields, 3*n_fields, 3*n_fields+1,\ 3*n_fields+1+(dim_sip+1)**2]) # pa_ptgs, scale, a, b =\ # np.split(result.x, [n_fields, n_fields+1,\ # n_fields+1+(dim_sip+1)**2]) #ra_ptgs = field_params['ra'].data # dec_ptgs = field_params['dec'].data print(' a and b matrices before scaling=', a, b) a_matrix = np.reshape(a, (dim_sip+1, dim_sip+1)) b_matrix = np.reshape(b, (dim_sip+1, dim_sip+1)) # A/B scaling m, n = np.indices((dim_sip+1, dim_sip+1)) mn = m + n a_matrix = a_matrix * (1.e-3**mn) b_matrix = b_matrix * (1.e-3**mn) fit_field_params = Table(data=[ra_ptgs, dec_ptgs, pa_ptgs, -np.ones(shape=(np.size(ra_ptgs)))],\ names=['ra', 'dec', 'pa', 'field'],\ dtype=['float64', 'float64', 'float64', 'int64']) fit_field_params['ra'].unit = u.deg fit_field_params['dec'].unit = u.deg fit_field_params['pa'].unit = u.deg fit_field_params['field'] = np.arange(0, np.size(field_params)) # - # Evaluate fitting. We follow https://www.fixes.pub/program/444521.html. # + from scipy import linalg, optimize chi2dof= np.sum(result.fun**2)/(result.fun.size -result.x.size) print(' Xi^2/dof =', chi2dof) J= result.jac print(' shape of J =', np.shape(J)) # this does not work. # cov= np.linalg.inv(J.T.dot(J)) # var= np.sqrt(np.diagonal(cov)) # print(' parameter variances =', var) U, s, Vh= linalg.svd(result.jac, full_matrices=False) tol= np.finfo(float).eps*s[0]*max(result.jac.shape) w= s > tol cov= (Vh[w].T/s[w]**2) @ Vh[w] # robust covariance matrix cov *= chi2dof perr= np.sqrt(np.diag(cov)) # 1sigma uncertainty on fitted parameters # extract errors ra_ptgs_err, dec_ptgs_err, pa_ptgs_err, scale_err, a_err, b_err =\ np.split(perr, [n_fields, 2*n_fields, 3*n_fields, 3*n_fields+1,\ 3*n_fields+1+(dim_sip+1)**2]) # A/B scaling a_err_matrix = np.reshape(a_err, (dim_sip+1, dim_sip+1)) b_err_matrix = np.reshape(b_err, (dim_sip+1, dim_sip+1)) # A/B scaling m, n = np.indices((dim_sip+1, dim_sip+1)) mn = m + n a_err_matrix = a_err_matrix * (1.e-3**mn) b_err_matrix = b_err_matrix * (1.e-3**mn) print(' parameter values =', ra_ptgs, dec_ptgs, pa_ptgs, scale, a_matrix, b_matrix) print(' parameter variances =', ra_ptgs_err, dec_ptgs_err, pa_ptgs_err, scale_err, \ a_err_matrix, b_err_matrix) # - # #### Pointings RA, DEC, position angle and scale print(' pointing centre (fit) ra, dec (deg) =', ra_ptgs, dec_ptgs) print(' pointing centre (true) ra, dec (deg) =', true_ra_ptgs, true_dec_ptgs) print(' difference ra, dec (deg) =', ra_ptgs-true_ra_ptgs, dec_ptgs-true_dec_ptgs) print(' uncertainty ra, dec pointings =', ra_ptgs_err, dec_ptgs_err) print(' position angle (fit) (deg) =', pa_ptgs) print(' position angle (true) (deg) =', true_pa_ptgs) print(' difference =', pa_ptgs-true_pa_ptgs) print(' uncertainty =', pa_ptgs_err) print(' scale (fit, true) =', scale, (1e-6/7.3/np.pi*180.0)*u.deg/u.um) print(' difference =', scale-(1e-6/7.3/np.pi*180.0)) print(' uncertainty =', scale_err) # #### Objects positions # + radec_objs = radec_calculator_ab(observed_xy_overlap, fit_field_params, scale[0], a_matrix, b_matrix) plt.scatter(true_radec_overlap['ra'], true_radec_overlap['dec'], marker='x', label='True') plt.scatter(radec_est['ra_est'], radec_est['dec_est'], marker='+', label='Initial guess') plt.scatter(radec_objs['ra_est'], radec_objs['dec_est'], marker='.', label='Final estimation') plt.scatter(radec_refstars['ra0'], radec_refstars['dec0'], marker='o', \ label='Reference stars') plt.xlabel('ra (deg)') plt.ylabel('dec (deg)') plt.title('Object positions') plt.legend() # + distlist = [] print(np.shape(radec_objs)) for i in range(0, np.size(radec_objs)): c1 = SkyCoord(radec_objs['ra_est'][i]*u.deg, radec_objs['dec_est'][i]*u.deg) c2 = SkyCoord(observed_xy_overlap['ra'][i]*u.deg, observed_xy_overlap['dec'][i]*u.deg) distlist.append(c1.separation(c2).arcsec) distlist = np.array(distlist) #plt.hist(np.log10(distlist)) plt.hist(distlist) plt.xlabel("Residual (arcsec)") plt.ylabel("Number") # - dra = ((radec_objs['ra_est']-observed_xy_overlap['ra']).data)*u.deg ddec = ((radec_objs['dec_est']-observed_xy_overlap['dec']).data)*u.deg dra_arcsec = dra.to_value(u.arcsec) ddec_arcsec = ddec.to_value(u.arcsec) plt.scatter(dra_arcsec, ddec_arcsec, marker='x') plt.xlabel('dRA (arcsec)') plt.ylabel('dDEC (arcsec)') # #### Apply to all the data, taking into account uncertainties of their position and parameter uncertainties. # We shall run Monte Carlo by randomly displacing the position of stars and distortion parameters. # + n_mc = 100 n_stars = len(observed_xy) print(' total # of stars =', n_stars) ra_allobjs_samp = np.empty((n_stars, n_mc)) dec_allobjs_samp = np.empty((n_stars, n_mc)) observed_xy_try = observed_xy.copy() # flattened uncertainties of a, b matrix a_flat = a_matrix.flatten() b_flat = b_matrix.flatten() a_err = a_err_matrix.flatten() b_err = b_err_matrix.flatten() for i in range(n_mc): # displace observed_xy positions observed_xy_try['x'] = np.random.normal(observed_xy['x'], observed_xy['xy_err']) observed_xy_try['y'] = np.random.normal(observed_xy['y'], observed_xy['xy_err']) # displace the parameters ra_ptgs_try = np.random.normal(ra_ptgs, ra_ptgs_err) dec_ptgs_try = np.random.normal(dec_ptgs, dec_ptgs_err) pa_ptgs_try = np.random.normal(pa_ptgs, pa_ptgs_err) scale_try = np.random.normal(scale, scale_err) a_try = np.random.normal(a_flat, a_err) b_try = np.random.normal(b_flat, b_err) a_matrix_try = np.reshape(a_try, (dim_sip+1, dim_sip+1)) b_matrix_try = np.reshape(b_try, (dim_sip+1, dim_sip+1)) fit_field_params_try = Table(data=[ra_ptgs_try, dec_ptgs_try, pa_ptgs_try, \ -np.ones(shape=(np.size(ra_ptgs)))],\ names=['ra', 'dec', 'pa', 'field'],\ dtype=['float64', 'float64', 'float64', 'int64']) fit_field_params_try['ra'].unit = u.deg fit_field_params_try['dec'].unit = u.deg fit_field_params_try['pa'].unit = u.deg fit_field_params_try['field'] = np.arange(0, np.size(field_params)) radec_allobjs_try = radec_calculator_ab(observed_xy_try, fit_field_params_try, \ scale_try[0], a_matrix_try, b_matrix_try) ra_allobjs_samp[:, i] = radec_allobjs_try['ra_est'] dec_allobjs_samp[:, i] = radec_allobjs_try['dec_est'] ra_allobjs_mean = np.mean(ra_allobjs_samp, axis=1) ra_allobjs_std = np.std(ra_allobjs_samp, axis=1) dec_allobjs_mean = np.mean(dec_allobjs_samp, axis=1) dec_allobjs_std = np.std(dec_allobjs_samp, axis=1) # error from the true value ra_allobjs_err = ra_allobjs_mean-observed_xy['ra'] dec_allobjs_err = dec_allobjs_mean-observed_xy['dec'] plt.scatter(ra_allobjs_err, ra_allobjs_std, marker='x', label='RA') plt.scatter(dec_allobjs_err, dec_allobjs_std, marker='.', label='DEC') print(' RA mean standard deviation of measurements (arcsec) =', \ (np.mean(ra_allobjs_std)*u.deg).to_value(u.arcsec)) print(' RA standard deviation from the true values (arcsec) =', (np.std(ra_allobjs_err)*u.deg).to_value(u.arcsec)) print(' DEC mean standard deviation of measurements (arcsec) =', (np.mean(dec_allobjs_std)*u.deg).to_value(u.arcsec)) print(' DEC standard deviation from the true values (arcsec)=', (np.std(dec_allobjs_err)*u.deg).to_value(u.arcsec)) plt.xlabel('deviatoin from the true radec(deg)') plt.ylabel('standar deviation of measurement (deg)') plt.title('Object positions') plt.legend() # -
case8_challenge_00_pix2wcs.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 __future__ import print_function import findspark findspark.init() findspark.find() import pyspark findspark.find() from pyspark.sql import SparkSession from pyspark.ml.feature import StringIndexer from pyspark.ml.feature import CountVectorizer if __name__ == "__main__": spark = SparkSession\ .builder\ .appName("countVectorizer")\ .getOrCreate() documentDF = spark.createDataFrame([ ("Let's see an example of countVectorizer".split(" "),), ("We will use pyspark library my name is my name is ".split(" "),), ("countVectorizer is important for NLP".split(" "),) ], ["sentence"]) documentDF.show() documentDF.show(truncate=False) df = spark.createDataFrame([(0, ["a", "b", "c"]), (1, ["a", "b", "b", "c", "a"])],["label", "raw"]) cv = CountVectorizer(inputCol="raw", outputCol="vectors") model = cv.fit(df) model.transform(df).show(truncate=False) count_vector = CountVectorizer(inputCol="sentence", outputCol="count_vector") count_vector model = count_vector.fit(documentDF) result = model.transform(documentDF) result.show(truncate=False) spark.stop()
Downloaded file/countVectorizer.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 online from ai2thor.controller import Controller # Kitchens: FloorPlan1 - FloorPlan30 # Living rooms: FloorPlan201 - FloorPlan230 # Bedrooms: FloorPlan301 - FloorPlan330 # Bathrooms: FloorPLan401 - FloorPlan430 # KITCHEN_OBJECT_CLASS_LIST = [ # "Toaster", # "Microwave", # "Fridge", # "CoffeeMaker", # "GarbageCan", # "Box", # "Bowl", # ] # LIVING_ROOM_OBJECT_CLASS_LIST = [ # "Pillow", # "Laptop", # "Television", # "GarbageCan", # "Box", # "Bowl", # ] # BEDROOM_OBJECT_CLASS_LIST = ["HousePlant", "Lamp", "Book", "AlarmClock"] # BATHROOM_OBJECT_CLASS_LIST = ["Sink", "ToiletPaper", "SoapBottle", "LightSwitch"] controller = Controller(scene='FloorPlan1', gridSize=0.25) # + # MODEL_PATH_DICT = {'SAVN' : 'pretrained_models/savn_pretrained.dat', # 'NON_ADAPTIVE_A3C': 'pretrained_models/nonadaptivea3c_pretrained.dat', # 'GCN':'pretrained_models/gcn_pretrained.dat' } # GLOVE_FILE = './data/thor_glove/glove_map300d.hdf5' # ACTION_LIST = ['MoveAhead', 'RotateLeft', 'RotateRight', 'LookUp', 'LookDown', 'Done'] epi = online.Episode(controller, target='Cup', model_name='SAVN', model_path='pretrained_models/savn_pretrained.dat', glove_file_path='./data/thor_glove/glove_map300d.hdf5') for i in range(40): epi.step() # - event = controller.step(action='MoveAhead') test_frame = event.frame # + epi2 = online.Episode(controller, target='Cup', model_name='SAVN', model_path='pretrained_models/savn_pretrained.dat', glove_file_path='./data/thor_glove/glove_map300d.hdf5') epi2.isolated_step(test_frame) # -
test_import_online.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 # --- # + [markdown] colab_type="text" id="y-8QoaJmXd8Z" # # DL Indaba Practical 2 # # Feedforward Neural Networks on Real Data & Best Practices # *Developed by <NAME>, <NAME> & <NAME>.* # # **Introduction** # # In this practical we will move on and discuss best practices for building and training models on real world data (the famous MNIST dataset of hand-written images of digits). We will develop a deep, fully-connected ("feed-forward") neural network model that can classify these images with around 98% accuracy (close to state-of-the-art for feedforward models on this dataset). # # **Learning objectives**: # # Understanding the issues involved in implementing and applying deep neural networks in practice (w/ a focus on TensorFlow). In particular: # # * Implementation sanity checking details & controlled overfitting on a small training set. # # * Training deep neural networks. Understand: # * Conceptually how the backprop algorithm efficiently computes model gradients by applying the chain rule and applying dynamic programming (saving intermediate computations). # * Overfitting and how to use regularization to avoid it (Weight decay/L2 and dropout). # * Knowing when to stop training (early stopping). # # * Understand the need for hyperparameter tuning in finding good architectures and training settings. # # **What is expected of you:** # # * We have included rough time estimates of how long you should aim to spend on the important sections below. # * Step through the notebook answering the questions by discussing them with your lab partner. # * Execute each cell in turn & fill in the missing code by pair-programming with your lab partner. # * 5 min before the end, pair up with someone else and make sure you both understand the concepts listed in "Learning Objectives" above. If not, please speak to the tutors! # + [markdown] colab_type="text" id="5JQ4eAF7X2tK" # # Setups and Imports # + [markdown] colab_type="text" id="G2tOik9MR8_O" # For this practical, we will work with the [famous MNIST dataset of handwritten digits](http://yann.lecun.com/exdb/mnist/). The task is to classify which digit a particular image represents. Luckily, since MNIST is a very popular dataset, TensorFlow has some built-in functions to download it. # # The MNIST dataset consists of pairs of images (28x28 matrices) and labels. Each label # is represented as a (sparse) binary vector of length 10 with a 1 in position `i` iff the image represents digit `i`, and 0 elsewhere. This is what the "one_hot" parameter you see below does. # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 153, "output_extras": [{"item_id": 4}]} colab_type="code" executionInfo={"elapsed": 8487, "status": "ok", "timestamp": 1503657242635, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="IYrNES0hD6Mi" outputId="258b73ac-670c-4b30-9b67-7fbe07be7c4b" # Import TensorFlow and some other libraries we'll be using. import datetime import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Download the MNIST dataset onto the local machine. mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # + [markdown] colab_type="text" id="Xdz38ZyZE3vW" # # Visualizing the MNIST data # + [markdown] colab_type="text" id="AmblsKmbl9sY" # Let's visualize a few of the digits (from the training set): # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 208, "output_extras": [{"item_id": 1}]} colab_type="code" executionInfo={"elapsed": 999, "status": "ok", "timestamp": 1503055879874, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="JpAbMODcG1se" outputId="76aa84c7-ee87-45ba-e73d-1476f54ec647" from matplotlib import pyplot as plt plt.ioff() # %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # Helper plotting routine. def display_images(gens, title=""): fig, axs = plt.subplots(1, 10, figsize=(25, 3)) fig.suptitle(title, fontsize=14, fontweight='bold') for i in xrange(10): reshaped_img = (gens[i].reshape(28, 28) * 255).astype(np.uint8) axs.flat[i].imshow(reshaped_img) #axs.flat[i].axis('off') return fig, axs batch_xs, batch_ys = mnist.train.next_batch(10) list_of_images = np.split(batch_xs, 10) _ = display_images(list_of_images, "Some Examples from the Training Set.") plt.show() # + [markdown] colab_type="text" id="DrVjQKHlT2m4" # # Building a Feed-Forward Neural Network # # In this section, we will build a neural network that takes the raw MNIST pixels as inputs and outputs 10 values, which we will interpret as the probability that the input image belongs to one of the 10 digit classes (0 through 9). Along the way, the data will pass through the hidden layers and activation functions we encountered in the first practical. # # **NOTE**: Standard feedforward neural network architectures can be summarised by chaining together the number of neurons in each layer, e.g. "784-500-300-10" would be a net with 784 input neurons, followed by a layer with 500 neurons, then 300, and finally 10 output classes. # + [markdown] colab_type="text" id="T2L7D76zYZZv" # ## Build the model (30min) # # We want to explore the different choices and some of the best practices of training feedforward neural networks on the MNIST dataset. In this practical we will only be using "fully connected" (also referred to as "FC", "affine", or "dense") layers (i.e. no convolutional layers). So let's first write a little helper function to construct these: # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="my3WeXTdEt34" def _dense_linear_layer(inputs, layer_name, input_size, output_size): """ Builds a layer that takes a batch of inputs of size `input_size` and returns a batch of outputs of size `output_size`. Args: inputs: A `Tensor` of shape [batch_size, input_size]. layer_name: A string representing the name of the layer. input_size: The size of the inputs output_size: The size of the outputs Returns: out, weights: tuple of layer outputs and weights. """ # Name scopes allow us to logically group together related variables. # Setting reuse=False avoids accidental reuse of variables between different runs. with tf.variable_scope(layer_name, reuse=False): # Create the weights for the layer layer_weights = tf.get_variable("weights", shape=[input_size, output_size], dtype=tf.float32, initializer=tf.random_normal_initializer()) # Create the biases for the layer layer_bias = tf.get_variable("biases", shape=[output_size], dtype=tf.float32, initializer=tf.random_normal_initializer()) ## IMPLEMENT-ME: (1) outputs = ... return (outputs, layer_weights) # + [markdown] colab_type="text" id="LTFPjWj7FqJy" # Now let's use this to construct a linear softmax classifier as before, which we will expand into a near state-of-the-art feed-forward model for MNIST. We first create an abstract `BaseSoftmaxClassifier` base class that houses common functionality between the models. Each specific model will then provide a `build_model` method that represents the logic of that specific model. # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="oaHvemlxVeIi" class BaseSoftmaxClassifier(object): def __init__(self, input_size, output_size, l2_lambda): # Define the input placeholders. The "None" dimension means that the # placeholder can take any number of images as the batch size. self.x = tf.placeholder(tf.float32, [None, input_size]) self.y = tf.placeholder(tf.float32, [None, output_size]) self.input_size = input_size self.output_size = output_size self.l2_lambda = l2_lambda self._all_weights = [] # Used to compute L2 regularization in compute_loss(). # You should override these in your build_model() function. self.logits = None self.predictions = None self.loss = None self.build_model() def get_logits(self): return self.logits def build_model(self): # OVERRIDE THIS FOR YOUR PARTICULAR MODEL. raise NotImplementedError("Subclasses should implement this function!") def compute_loss(self): """All models share the same softmax cross-entropy loss.""" assert self.logits is not None # Ensure that logits has been created! # IMPLEMENT-ME: (2) # HINT: This time, use the TensorFlow function tf.nn.softmax_cross_entropy_with_logits rather than # implementing it manually like we did in Prac1 data_loss = ... reg_loss = 0. for w in self._all_weights: # IMPLEMENT-ME: (3) # HINT: TensorFlow has a built-in function for this too! tf.nn.l2_loss reg_loss += ... return data_loss + self.l2_lambda * reg_loss def accuracy(self): # Calculate accuracy. assert self.predictions is not None # Ensure that pred has been created! # IMPLEMENT-ME: (4) # HINT: Look up the tf.equal and tf.argmax functions correct_prediction = ... accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) return accuracy # + [markdown] colab_type="text" id="JVqOqr8qKApu" # If we wanted to reimplement the linear softmax classifier from before, we just need to override `build_model()` to perform one projection from the input to the output logits, like this: # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="jLVw-NWEKBI9" class LinearSoftmaxClassifier(BaseSoftmaxClassifier): def __init__(self, intput_size, output_size, l2_lambda): super(LinearSoftmaxClassifier, self).__init__(input_size, output_size, l2_lambda) def build_model(self): # The model takes x as input and produces output_size outputs. self.logits, weights = _dense_linear_layer( self.x, "linear_layer", self.input_size, self.output_size) self._all_weights.append(weights) self.predictions = tf.nn.softmax(self.logits) self.loss = self.compute_loss() # + [markdown] colab_type="text" id="A1Lxtrw0KnmW" # In order to build a ***deeper*** model, let's add several layers with multiple transformations and rectied linear units (relus): # # ```python # def build_model(self): # # The first layer takes x as input and has n_hidden_1 outputs. # layer1, weights1 = _build_linear_layer(self.x, "layer1", self.input_size, self.num_hidden_1) # self._all_weights.append(weights1) # layer1 = tf.nn.relu(layer1) # # # The second layer takes layer1's output as its input and has num_hidden_2 outputs. # layer2, weights2 = _build_linear_layer(layer1, "layer2", self.num_hidden_1, self.num_hidden_2) # self._all_weights.append(weights2) # layer2 = tf.nn.relu(layer2) # # # The final layer is our predictions and goes from num_hidden_2 inputs to # # num_classes outputs. The outputs are "logits" (un-normalised scores). # self.logits, weights3 = _build_linear_layer(layer2, "output", self.num_hidden_2, self.output_size) # self._all_weights.append(weights3) # # self.pred = tf.nn.softmax(self.logits) # self.loss = self.compute_loss(self.logits, self.y) # ``` # # **Note: Instead of writing special classes for linear nets (0 hidden layers), 1 hidden layer nets, 2 hidden layer nets, etc., we can generalize this as follows:** # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="QVCIXYUrHXai" class DNNClassifier(BaseSoftmaxClassifier): """DNN = Deep Neural Network - now we're doing Deep Learning! :)""" def __init__(self, input_size=784, # There are 28x28 = 784 pixels in MNIST images hidden_sizes=[], # List of hidden layer dimensions, empty for linear model. output_size=10, # There are 10 possible digit classes act_fn=tf.nn.relu, # The activation function to use in the hidden layers l2_lambda=0.): # The strength of regularisation, off by default. self.hidden_sizes = hidden_sizes self.act_fn = act_fn super(DNNClassifier, self).__init__(input_size, output_size, l2_lambda) def build_model(self): prev_layer = self.x prev_size = self.input_size for layer_num, size in enumerate(self.hidden_sizes): layer_name = "layer_" + str(layer_num) ## IMPLEMENT-ME: (5) # HINT: Use the linear function we defined earlier! layer, weights = ... self._all_weights.append(weights) ## IMPLEMENT-ME: (6) # HINT: What do we still need to do after doing the "linear" part? layer = ... prev_layer, prev_size = layer, size # The final layer is our predictions and goes from prev_size inputs to # output_size outputs. The outputs are "logits", un-normalised scores. self.logits, out_weights = _dense_linear_layer(prev_layer, "output", prev_size, self.output_size) self._all_weights.append(out_weights) self.predictions = tf.nn.softmax(self.logits) self.loss = self.compute_loss() # + [markdown] colab_type="text" id="aHkH_jEc9C3j" # We can now create a linear model, i.e. a 784-10 architecture (note that there is only one possible linear model going from 784 inputs to 10 outputs), as follows: # # ```python # tf_linear_model = DNNClassifier(input_size=784, hidden_sizes=[], output_size=10) # ``` # # We can create a deep neural network (DNN, also called a "multi-layer perceptron") model, e.g. a 784-512-10 architecture (there can be many others...), as follows: # # ```python # tf_784_512_10_model = DNNClassifier(input_size=784, hidden_sizes=[512], output_size=10) # ``` # # and so forth. # # **NOTE: Make sure you understand how this works before you move on.** # + [markdown] colab_type="text" id="kVynk3SWzUg_" # ## Sanity Checks (5-10 min) # # ### Dealing with randomness # # Pseudo-random number generators start from some value (the 'seed') and generate numbers which appear to be random. It is good practise to seed RNGs with a fixed value to encourage reproducibility of results. We do this in NumPy by using `np.random.seed(1234)`, where `1234` is your chosen seed value. # # In TensorFlow we can set a *graph-level* seed (global, using `tf.set_random_seed(1234)`) or an *op-level* seed (passed in to each op via the `seed` argument, to override the graph-level seed.) # # Next we need to initialize the parameters of our model. We do *not* want to initialize all weights to be the same. # # **QUESTION**: Can you think of why this might be a bad idea? (Think about a simple MLP with one input and 2 hidden units and one output. Look at the contributions via each weight connection to the activations on the hidden layer. Now let those weights be equal. How does that affect the contributions? How does that affect the update that backprop would propose for each weight? Do you see any problems?) # # The simplest approach is to **initialize weights (W's) to small random values**. For ReLUs specifically, it is recommended to initialize weights to `np.random.randn(n) * sqrt(2.0/n)`, where `n` is the number of inputs to that layer (neuron on the previous layer) (see [He et al., 2015](https://arxiv.org/pdf/1502.01852.pdf) for more information). This initialization encourages the distributions over ReLU activations to have roughly the same variance at each layer, which in turn ensures that useful gradient information gets sent back during backpropagation. # # Biases are not that sensitive to initialization and can be initialized to 0s or small random numbers. # # ### Check the loss of a random model # # When we have a new model, it's always a good idea to do a quick sanity check. A random model that predicts C classes on random data should have no reason for preferring either class, i.e., on average its loss (negative log-likelihood) should be $-\log(1/C) = -\log(C^{-1}) = \log(C)$. # # **NOTE**: TF actually computes the cross-entropy on the *logits* for numerical stability reasons (logs of small numbers blow up quickly..). This means we'll get a different value from `tf.nn.softmax_cross_entropy_with_logits`. So for this check we will just manually compute the cross-entropy (negative log-likelihood). # # The second thing to check is that adding the L2 loss (a strictly positive value), should *increase* total loss (here we'll just use the TF cross-entropy as provided). # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 408, "output_extras": [{"item_id": 2}]} colab_type="code" executionInfo={"elapsed": 1026, "status": "ok", "timestamp": 1503657319275, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="DUMQp9kw0Isx" outputId="b8d7a421-e489-4b54-a896-aa2da2435020" tf.set_random_seed(1234) np.random.seed(1234) # Generate a batch of 100 "images" of 784 pixels consisting of Gaussian noise. x_rnd = np.random.randn(100, 784) print "Sample of random data:\n", x_rnd[:5,:] # Print the first 5 "images" print "Shape: ", x_rnd.shape # Generate some random one-hot labels. y_rnd = np.eye(10)[np.random.choice(10, 100)] print "Sample of random labels:\n", y_rnd[:5,:] print "Shape: ", y_rnd.shape # Model without regularization. tf.reset_default_graph() tf_linear_model = DNNClassifier(l2_lambda=0.0) x, y = tf_linear_model.x, tf_linear_model.y with tf.Session() as sess: # Initialize variables. init = tf.global_variables_initializer() sess.run(init) avg_cross_entropy = -tf.log(tf.reduce_mean(tf_linear_model.predictions)) loss_no_reg = tf_linear_model.loss manual_avg_xent, loss_no_reg = sess.run([avg_cross_entropy, loss_no_reg], feed_dict={x : x_rnd, y: y_rnd}) # Sanity check: Loss should be about log(10) = 2.3026 print '\nSanity check manual avg cross entropy: ', manual_avg_xent print 'Model loss (no reg): ', loss_no_reg # Model with regularization. tf.reset_default_graph() tf_linear_model = DNNClassifier(l2_lambda=1.0) x, y = tf_linear_model.x, tf_linear_model.y with tf.Session() as sess: # Initialize variables. init = tf.global_variables_initializer() sess.run(init) loss_w_reg = tf_linear_model.loss.eval(feed_dict={x : x_rnd, y: y_rnd}) # Sanity check: Loss should go up when you add regularization print 'Sanity check loss (with regularization, should be higher): ', loss_w_reg # + [markdown] colab_type="text" id="X0YXZ-u284tK" # ## Compute the gradients: Backpropagation Review # # Once one has implemented the model and checked that the loss produces sensible outputs it is time to create the training loop. For this, we will need to obtain the gradients of the loss wrt each model parameter. We've already looked at this in detail in practical 1, where we performed this manually. One of the great benefits of using a library like TensorFlow, is that it can automatically derive the gradients wrt any parameter in the graph (using `tf.gradients()`). # # In the previous practical we saw that there is a common pattern to deriving the gradients in neural networks: # # 1. propagate activations forward through the network ("make a prediction" $\Rightarrow$ `fprop`), # 2. compute an error delta ("see how far we're off") , and # 3. propagate errors backwards to update the weights ("update the weights to do better next time" $\Rightarrow$ `backprop`). # # It turns out that for deeper networks, ***this pattern repeats for every new layer***. Take a deep breath, and let's dive in, starting with fprop: # # ### FPROP # # Conceptually, forward propagation is very simple: Starting with the input `x`, we repeatedly apply an affine function and a non-linearity to arrive at the output $a^L = \sigma^L(W^{L-1}\sigma^{L-1}( \ldots \sigma(W^1x + b^1) \dots ) + b^{L-1})$. # # Mathematically, forward propagation comes down to a **composition of functions**. So for two layers, the output activation $a^2$ is the composition of the function $a^1 = f^1(x)$ and $a^2 = f^2(a^1)$ $\Rightarrow$ $a^2 = f^2(f^1(x))$. # # **NOTE**: We save both the pre-activations (before the non-linearity) *and* the (post-)activations (after the nonlinearity). We'll need these for the backprop phase! # # In code it looks like this: # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="BKxO41QtW0ka" # PSEUDOCODE: def fprop(x, weights, biases, per_layer_nonlinearities): # Initialise the input. We pretend inputs are the first pre- and post-activations. z = a = x cache = [(z, a)] # We'll save z's and a's for the backprop phase. for W, b, act_fn in zip(weights, biases, per_layer_nonlinearities): z = np.dot(W, a) + b # "pre-activations" / logits a = act_fn(z) # "outputs" / (post-)activations of the current layer # NOTE: We save both pre-activations and (post-)activations for the backwards phase! cache.append((z, a) return cache # Per-layer pre- and post-activations. # + [markdown] colab_type="text" id="yeQ6_uE5asVK" # ### BACKPROP # # Given a loss or error function $E$ at the output (e.g. cross-entropy), we then need the derivative of the loss wrt each of the model parameters in order to train the network (decrease the loss). Mathematically, this comes down to the derivative of a composition of functions, and from calculus we know we have the [chain rule](https://en.wikipedia.org/wiki/Chain_rule) for that: If $a = f(g(x))$, then $\frac{\partial a}{\partial x} = \frac{\partial f}{\partial g} \frac{\partial g}{\partial x}$. # # In order to get the gradients on some intermediate parameter $\theta^i = \{W^i, b^i\}$ in layer $i$, we just apply the chain rule over all $L$ 'layers' of this composition of functions (the neural network) to derive the intermediate gradients: # # \begin{aligned} # \frac{\partial E}{\partial \theta^{(i)}} # &= \underbrace{ \frac{\partial E}{\partial z^{(L)}} \frac{\partial z^{(L)}}{\partial z^{(L-1)}} \ldots \frac{\partial z^{(i+2)}}{\partial z^{(i+1)}}}_{\triangleq \delta^{(i+1)}} \frac{\partial z^{(i+1)}}{\partial \theta^{(i)}} \\ # &= \delta^{(i+1)} \frac{\partial z^{(i+1)}}{\partial \theta^{(i)}} # \end{aligned} # # We have glossed a little over the fact that we are dealing with matrices and vectors, for the sake of brevity. But please see these two great resources: # * For a step-by-step walk-through of the mechanics of backpropagation, see [this great resource](http://cs224d.stanford.edu/lecture_notes/notes3.pdf). # * For a great brush-up on the mechanics of vector calculus, see [this fantastic note](https://web.stanford.edu/class/cs224n/lecture_notes/cs224n-2017-gradient-notes.pdf) (for the same course). # # **NOTE**: # * $E$ is the error/loss function at the output. # * $W^{(i)}$ is an intermediate weight matrix mapping activations from layer $i$ to pre-activations $z^{(i+1)}$ at layer $i+1$. # * The derivative with respect to the *inputs* of layer $i$ are called deltas and is defined as $\delta^{(i)} \triangleq \frac{\partial E}{\partial z^{(i)}}$. # * $\delta^i$ is a vector (the size of the layer $i$), and is the result of the deltas at the output $\delta^L$ (dE/dlogits) multiplied by a product of [Jacobian matrices](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant). If you don't understand this statement, just think of $\delta^i_j$ as the contribution that unit $j$ in layer $i$ made to the total error $E$. Also, read up on this in the resources linked above. # * **NB**: $z^{(i)}$ are the pre-activations ("logits" at the output layer)! # * $\frac{\partial z^{(i+1)}}{\partial W^{(i)}} = \frac{\partial (W^{(i)}a^i + b^i)}{\partial W^{(i)}} = a^i$. # * Likewise, $\frac{\partial z^{(i+1)}}{\partial b^{(i)}} = 1$ (check this for yourself). # # # **QUESTIONS**: # 1. What is the shape of $\frac{\partial E}{\partial \mathbb{W}^{(i)}}$? # * Convince yourself (now or later) that $\frac{\partial E}{\partial W^{(i)}_{jk}} = \delta^{(i+1)}_k {a^i_j}$ (a scalar), and therefore $\frac{\partial E}{\partial \mathbb{W}^{(i)}} = \mathbb{\delta}^{(i+1)} {\mathbb{a}^i}^T$ (outer product of two vectors, therefore a matrix of the same shape as $W^i$). # * **In words: The gradient on weights $W^i$ at layer $i$ is the outer product of the deltas-vector from the layer above $\delta^{(i+1)}$ and the activations vector from the layer below $a^i$.** # # 2. What is the shape of $\frac{\partial E}{\partial \mathbb{b}^{(i)}}$? # * Convince yourself (now or later) that $\frac{\partial E}{\partial \mathbb{b}^{(i)}} = \mathbb{\delta}^{(i+1)}$ (a vector of the same length as $b^i$). # * **In words: The gradient on biases $b^i$ at layer $i$ is equal to the deltas at the layer above**. # 3. Make sure you understand why we save the `(z,a)`'s during fprop, and how we use them during backprop. # # # Note that we need to compute the deltas at every layer, and $\delta^i$ share all the terms of $\delta^{(i+1)}$ (which we've already computed), except one. Backprop has one more trick up its sleeve, and that is to *reuse previously computed values to save computation* (this is called [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming)). For the deltas, this comes down to computing $\delta^{(i)}$ given $\delta^{(i+1)}$. We won't show the full derivation (but we again use the chain rule, see the notes linked above) to arrive at: # # \begin{align} # \delta^{(i)} &= \frac{\partial E}{\partial z^{(i)}} \\ # &= \ldots \\ # &= \underbrace{ \left[ \delta^{(i+1)} {\mathbb{W}^{(i)}}^T \right] }_\textrm{Map the global delta 'backwards' through W up to layer $i$} \circ \underbrace{ \sigma'(z^{(i)}) }_\textrm{Correct for the local errors at this layer.}. # \end{align} # # **In words: The delta on the current layer $i$ is the delta on the layer above $\delta^{(i+1)}$ multiplied by the transpose weights matrix between the two layers $W^i$ to yield a vector, scaled by the element-wise multiplication of $\sigma'(z^{(i)})$ (the derivative of the non-linearity applied to the original pre-activations).** # # **QUESTIONs**: Look at the code below and make sure you understand (at least conceptually) how this works. # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="_tNoN3q4azpx" # PSEUDOCODE def backprop(target, fprop_cache, weights): # Pop/remove the model prediction (last activation `a` we computed above) # off the cache we created during the fprop phase. (_, pred) = fprop_cache.pop() # Intialise delta^{L} (at the output layer) as dE/dz (cross-entropy). delta_above = (target - pred) grads = [] # Unroll backwards from the output: for (z_below, a_below), W_between in reversed(zip(fprop_cache, weights)): # Compute dE/dW: Wgrad = np.dot(delta_above, a_below.T) # Outer product # Compute dE/db: bgrad = delta_above # Save these: grads.append((Wgrad, bgrad)) # Update for the *next* iteration/layer. Note the elem-wise multiplication. # Note the use of z_below, the preactivations in the layer below! # delta^i = delta^{(i+1)}.(W^i)^T .* sigma'(z_i): delta_above = np.dot(delta_above, W_between.T) * dsigmoid(z_below) grads.reverse() return grads # + [markdown] colab_type="text" id="EvvygszheFJ1" # Ppphhhhhheeeeewwwww, ok, come up for a breather. We know. This takes a while to wrap your head around. For now, just try to get the high-level picture! Depending on your background, this may well be the toughest part of the week. # # **BACKPROP SUMMARY NOTE**: It helps to have a good idea of what backprop does, and for this it helps to work through one example by hand (see the linked notes above). But you don't need to understand every detail above for the rest of this and the following lectures. The good news is that in practise you won't compute gradients by hand, and all of the above is done for us by `tf.gradients()` (or the similar function in other packages)! # # **BACKPROP FINAL QUESTION**: Take a few minutes to explain the high-level details of the backprop algorithm to your neighbour. Try to understand how fprop is essentially just a composition of functions applied to the input, and backprop 'peels off' those compositions one by one by following the chain rule. In the process it avoids recomputation by saving activations during fprop, and computing deltas during backprop. Be sure to ask the tutors if you're stuck! # # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="McPVC7ejezyZ" """ # PSEUDOCODE: biases, weights = [b1, b2], [W1, W2] x, y = ..., ... non_linearities = [relu, softmax] fprop_cache = fprop(x, weights, biases, non_linearities) grads = backprop(y, fprop_cache, weights) """ # + [markdown] colab_type="text" id="lCu7TiQ7Lygf" # ## Training deep neural networks (10min) # # Now that we have a model with a loss and gradients, let's write a function to train it! This will be largely similar to the `train_tf_model()` function (same name, see below) from the previous practical. However, we are introducing several new concepts in this practical: # # * how to update parameters using different optimizers, # * model complexity and how to match this to your data: # * recognizing overfitting # * adding regularization (L2, dropout) # * knowing when to stop training: early stopping, # # As we go through these concepts, we will show how to use them in our training function. # # ### Optimizers # # Training neural networks involves solving an optimization problem. **Stochastic gradient-based methods** are by far the most popular family of techniques that are being used for this. These methods evaluate the gradient of the loss on a small part of the data (called a **mini-batch**), and then propose a small change to the weights based on the current sample (and some maintain running averages over the previous steps), that reduces the loss, before moving on to another sample of the data: # # ``` # step = optimizer(grad(cost), learning_rate, ...) # new_weights = old_weights + step # ``` # # The oldest algorithm is stochastic gradient descent, but there are many others (Adagrad, AdaDelta, RMSProp, ADAM, etc.). As a general rule of thumb, ADAM or SGD with Momentum tend to work quite well out of the box, but this depends on your model and your data! See these two great blog posts for more on this: # # * http://ruder.io/optimizing-gradient-descent/ # * https://medium.com/towards-data-science/types-of-optimization-algorithms-used-in-neural-networks-and-ways-to-optimize-gradient-95ae5d39529f # # In our code, we can select different optimization functions by passing in a different optimizer to `train_tf_model` (see the full list here: https://www.tensorflow.org/api_guides/python/train#Optimizers) as follows: # # ```python # # optimizer = tf.train.RMSProp(...) # results_tuple = train_tf_model(optimizer_fn=optimizer, ...) # ``` # # ### Training / validation / test splits # # When training supervised machine learning models, the goal is to build a model that will perform well on some test task with data that we'll obtain some time in the future. Unfortunately, until we solve time-travel, we don't yet have access to that data. So how do we train a model on data we have now, to perform well on some (unseen) data from the future? This, in a nutshell, is the statistical learning problem: we want to train a data on available data to **generalize** to unseen test data. # # The way we approach this is to take a dataset that we do have, and split it into a **training**, **validation**, and **test set** (split). Typically we will use ratios of 80/10/10 for example. We then train our model on the training set only, and use the validation set to make all kinds of decisions about architectural selection, hyperparameters, etc. When we're done, we evaluate our model and report its accuracy on the **test set only**. # # **NOTE**: We (typically) do not train on the validation set, and we **never** train on the test set. Think about why training on the test set might be a bad thing? # # ### Model complexity, overfitting & regularization # # **Overfitting** occurs when improving the model's training loss (its performance on training data) comes at the expense of its **generalisation ability** (its performance on unseen test data). Generally it is a symptom of the **model complexity** increasing to fit the peculiarities (outliers) of the training data too accurately, causing it not to generalize well to new unseen (test) data. Overfitting is usually indicated when: # # * training & validation loss starts decreasing at different rates, # * validation error starts increasing while training error still goes down, # * training error reaches 0. # # **Underfitting** is the opposite: when a model cannot fit the training data well enough (usually a sign to train for longer or add more parameters to the model). # # You can think of complexity as how "wiggly" or "wrinkly" the decision boundary that the model can represent is. We can increase model complexity by adding more layers (i.e. more parameters). We can control or reduce the model complexity of an architecture using a family of techniques called **regularisers**. We've already encountered L2-regularisation (also called **weight-decay**), where we penalise the model for having very large weights. Another option is L1 regularization (which encourages sparsity of weights). Another very popular current technique is called **dropout** (we'll look at this in more detail in Practical 3). There are many others, but these two are the most popular. # # We will only be using L2 regularization in this practical. It can be set by passing a non-zero value to `l2_lambda` when constructing a `DNNClassifier` instance. # # ### Early stopping # # Neural networks are nonlinear models and can have very complicated optimization landscapes. Stochastic gradient based methods for optimizing these loss functions do not proceed monotonically (i.e. does not just keep going up). Sometimes the loss can go down for a while before it goes up to reach a better part of parameter space later. How do we know when to stop training? # # **Early stopping** is one technique that helps with this. It is added to the training routine and means that we periodically evaluate the model's performance on the validation set (***Crucially! not the test set. Why?***). If the performance on the validation set starts becoming worse we know we have reached the point of overfitting (usually), so it usually makes sense to stop training and not waste any more computations. The `train_tf_model` function we build has an early-stopping feature that you can enable by passing the `stop_early=True` parameter. Have a look at the code to see how this is done. # # ![early stopping](images/early_stopping.png "Diagram illustrating early stopping using validation results") # # For this practical, we just implemented the most basic idea of early stopping: stop training as soon as the model starts doing worse on validation data. However, there are different ways of implementing this idea. Two of the most popular are # # * "early stopping with patience": don't stop training immediately once validation accuracy degrades, but wait for P more epochs, and reset P if the model starts improving again within this timeframe, # * training for T epochs, and simply selecting the best model based on validation score over the entire T epochs. # # **QUESTION**: What are the pros and cons of these different methods? # # # # ## Wrapping these ideas into the training function (10-15min) # # The training function below implements all the ideas we discussed above. # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="gCADIJteG816" class MNISTFraction(object): """A helper class to extract only a fixed fraction of MNIST data.""" def __init__(self, mnist, fraction): self.mnist = mnist self.num_images = int(mnist.num_examples * fraction) self.image_data, self.label_data = mnist.images[:self.num_images], mnist.labels[:self.num_images] self.start = 0 def next_batch(self, batch_size): start = self.start end = min(start + batch_size, self.num_images) self.start = 0 if end == self.num_images else end return self.image_data[start:end], self.label_data[start:end] # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="C52suFUDsami" def train_tf_model(tf_model, session, # The active session. num_epochs, # Max epochs/iterations to train for. batch_size=50, # Number of examples per batch. keep_prob=1.0, # (1. - dropout) probability, none by default. train_only_on_fraction=1., # Fraction of training data to use. optimizer_fn=None, # The optimizer we want to use report_every=1, # Report training results every nr of epochs. eval_every=1, # Evaluate on validation data every nr of epochs. stop_early=True, # Use early stopping or not. verbose=True): # Get the (symbolic) model input, output, loss and accuracy. x, y = tf_model.x, tf_model.y loss = tf_model.loss accuracy = tf_model.accuracy() # Compute the gradient of the loss with respect to the model parameters # and create an op that will perform one parameter update using the specific # optimizer's update rule in the direction of the gradients. if optimizer_fn is None: optimizer_fn = tf.train.AdamOptimizer() optimizer_step = optimizer_fn.minimize(loss) # Get the op which, when executed, will initialize the variables. init = tf.global_variables_initializer() # Actually initialize the variables (run the op). session.run(init) # Save the training loss and accuracies on training and validation data. train_costs = [] train_accs = [] val_costs = [] val_accs = [] if train_only_on_fraction < 1: mnist_train_data = MNISTFraction(mnist.train, train_only_on_fraction) else: mnist_train_data = mnist.train prev_c_eval = 1000000 # Main training cycle. for epoch in range(num_epochs): avg_cost = 0. avg_acc = 0. total_batch = int(train_only_on_fraction * mnist.train.num_examples / batch_size) # Loop over all batches. for i in range(total_batch): batch_x, batch_y = mnist_train_data.next_batch(batch_size) # Run optimization op (backprop) and cost op (to get loss value), # and compute the accuracy of the model. feed_dict = {x: batch_x, y: batch_y} if keep_prob < 1.: feed_dict["keep_prob:0"] = keep_prob _, c, a = session.run( [optimizer_step, loss, accuracy], feed_dict=feed_dict) # Compute average loss/accuracy avg_cost += c / total_batch avg_acc += a / total_batch train_costs.append((epoch, avg_cost)) train_accs.append((epoch, avg_acc)) # Display logs per epoch step if epoch % report_every == 0 and verbose: print "Epoch:", '%04d' % (epoch+1), "Training cost=", \ "{:.9f}".format(avg_cost) if epoch % eval_every == 0: val_x, val_y = mnist.validation.images, mnist.validation.labels feed_dict = {x : val_x, y : val_y} if keep_prob < 1.: feed_dict['keep_prob:0'] = 1.0 c_eval, a_eval = session.run([loss, accuracy], feed_dict=feed_dict) if verbose: print "Epoch:", '%04d' % (epoch+1), "Validation acc=", \ "{:.9f}".format(a_eval) if c_eval >= prev_c_eval and stop_early: print "Validation loss stopped improving, stopping training early after %d epochs!" % (epoch + 1) break prev_c_eval = c_eval val_costs.append((epoch, c_eval)) val_accs.append((epoch, a_eval)) print "Optimization Finished!" return train_costs, train_accs, val_costs, val_accs # + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="AecVBHLe2USG" # Helper functions to plot training progress. def my_plot(list_of_tuples): """Take a list of (epoch, value) and split these into lists of epoch-only and value-only. Pass these to plot to make sure we line up the values at the correct time-steps. """ plt.plot(*zip(*list_of_tuples)) def plot_multi(values_lst, labels_lst, y_label, x_label='epoch'): # Plot multiple curves. assert len(values_lst) == len(labels_lst) plt.subplot(2, 1, 2) for v in values_lst: my_plot(v) plt.legend(labels_lst, loc='upper left') plt.xlabel(x_label) plt.ylabel(y_label) plt.show() # + [markdown] colab_type="text" id="hyJG8AQPL_BH" # ## Wrapping everything together and verifying that it works (10min) # # Once we have a training function, it is usually a good idea to train on a small amount of your data first to verify that everything is indeed working. We can put all the pieces together to achieve this as follows: # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 289, "output_extras": [{"item_id": 4}]} colab_type="code" executionInfo={"elapsed": 1198, "status": "ok", "timestamp": 1503071394643, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="guiSbTOIMAUm" outputId="32e73f8e-81de-4a8c-d7bb-1bd2286f8050" ##### BUILD MODEL ##### tf.reset_default_graph() # Clear the graph. model = DNNClassifier() # Choose model hyperparameters. with tf.Session() as sess: ##### TRAIN MODEL ##### train_losses, train_accs, val_losses, val_accs = train_tf_model( model, session=sess, num_epochs=10, train_only_on_fraction=1e-1, optimizer_fn=tf.train.GradientDescentOptimizer(learning_rate=1e-3), report_every=1, eval_every=2, stop_early=False) ##### EVALUATE MODEL ON TEST DATA ##### # Get the op which calculates model accuracy. accuracy_op = model.accuracy() # Get the symbolic accuracy operation # Connect the MNIST test images and labels to the model input/output # placeholders, and compute the accuracy given the trained parameters. accuracy = accuracy_op.eval(feed_dict = {model.x: mnist.test.images, model.y: mnist.test.labels}) print "Accuracy on test set:", accuracy # + [markdown] colab_type="text" id="kCJs9hNt9LFV" # Instead of just training and checking that the loss goes down, it is usually a good idea to try to **overfit a small subset of your training data**. We will do this below by training a 1 hidden layer network on a subset of the MNIST training data, by setting the `train_only_on_fraction` training hyperparameter to 0.05 (i.e. 5%). We turn off early stopping for this. The following diagram illustrates the difference between under-fitting and over-fitting. Note that the diagram is idealised and it's not always this clear in practice! # # ![overfitting](images/over_and_under_fitting.png "Over and Under Fitting") # # **QUESTION**: Why do we turn off early-stopping? # # In the rest of this practical, we will explore the effects of different model hyperparameters and different training choices, so let's wrap everything together to emphasize these different choices, and then train a simple model for a few epochs on 5% of the data to verify that everything works and that we can overfit a small portion of the data. # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 3109, "output_extras": [{"item_id": 14}, {"item_id": 25}, {"item_id": 26}, {"item_id": 27}]} colab_type="code" executionInfo={"elapsed": 6426, "status": "ok", "timestamp": 1503068187309, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="SvA0W9wTuFbD" outputId="c03d1f7d-550a-48d1-d94a-e337b03e902f" # NOTE THE CODE TEMPLATE BELOW WRAPS ALL OF THE ABOVE CODE, AND EXPOSES ONLY THE # DIFFERENT HYPERPARAMETER CHOICES. MAKE SURE YOU UNDERSTAND EXACTLY HOW # THE ABOVE CODE WORKS FIRST. TO SAVE SOME SPACE, WE WILL COPY AND MODIFY THE # CODE BELOW TO BUILD AND TRAIN DIFFERENT MODELS IN THE REST OF THIS PRACTICAL. # YOU CAN USE WHICHEVER VERSION YOU PREFER FOR YOUR OWN EXPERIMENTS. # Helper to wrap building, training, evaluating and plotting model accuracy. def build_train_eval_and_plot(build_params, train_params, verbose=True): tf.reset_default_graph() m = DNNClassifier(**build_params) with tf.Session() as sess: # Train model on the MNIST dataset. train_losses, train_accs, val_losses, val_accs = train_tf_model( m, sess, verbose=verbose, **train_params) # Now evaluate it on the test set: accuracy_op = m.accuracy() # Get the symbolic accuracy operation # Calculate the accuracy using the test images and labels. accuracy = accuracy_op.eval({m.x: mnist.test.images, m.y: mnist.test.labels}) if verbose: print "Accuracy on test set:", accuracy # Plot losses and accuracies. plot_multi([train_losses, val_losses], ['train', 'val'], 'loss', 'epoch') plot_multi([train_accs, val_accs], ['train', 'val'], 'accuracy', 'epoch') ret = {'train_losses': train_losses, 'train_accs' : train_accs, 'val_losses' : val_losses, 'val_accs' : val_accs, 'test_acc' : accuracy} return m, ret #################################CODE TEMPLATE################################## # Specify the model hyperparameters (NOTE: All the defaults can be omitted): model_params = { #'input_size' : 784, # There are 28x28 = 784 pixels in MNIST images 'hidden_sizes' : [512], # List of hidden layer dimensions, empty for linear model. #'output_size' : 10, # There are 10 possible digit classes #'act_fn' : tf.nn.relu, # The activation function to use in the hidden layers 'l2_lambda' : 0. # Strength of L2 regularization. } # Specify the training hyperparameters: training_params = {'num_epochs' : 100, # Max epochs/iterations to train for. #'batch_size' : 100, # Number of examples per batch, 100 default. #'keep_prob' : 1.0, # (1. - dropout) probability, none by default. 'train_only_on_fraction' : 5e-2, # Fraction of training data to use, 1. for everything. 'optimizer_fn' : None, # Optimizer, None for Adam. 'report_every' : 1, # Report training results every nr of epochs. 'eval_every' : 2, # Evaluate on validation data every nr of epochs. 'stop_early' : False, # Use early stopping or not. } # Build, train, evaluate and plot the results! trained_model, training_results = build_train_eval_and_plot( model_params, training_params, verbose=True # Modify as desired. ) ###############################END CODE TEMPLATE################################ # + [markdown] colab_type="text" id="J-YKo75RW1iO" # Above we plot the training loss vs the validation loss and the training accuracy vs the validation accuracy on only 5% (`train_only_on_fraction=5e-3`) of the training data (so that it doesn't take too long, and also so that our model can overfit easier). We see that the loss is coming down and the accuracies are going up, as expected! By training on a small subset of the training data, we established that # # * the data that the model is being trained on is hopefully not corrupt (this can happen during preprocessing, loading, etc), # * our loss and gradients are likely correct, # * our optimizer seems to do the right thing, # * and generally, that our code probably works! # # **NOTE**: Notice the point where training loss/accuracy continues to improve, but validation accuracy starts to plateau? That is the point where the model starts to **overfit** the training data. # # + [markdown] colab_type="text" id="32oVqFziKYcv" # # Architectural Choices (15min) # # ## Depth # # ### A Linear 784-10 Model # # Let's evaluate the simple linear model trained on the full dataset and then add layers to see what effect this will have on the accuracy. # # **NOTE**: If you're unsure what the "784-10" notation means, scroll up and re-read the section on "Building a Feed-forward Neural Network" where we explain that. # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 1528, "output_extras": [{"item_id": 27}, {"item_id": 28}, {"item_id": 29}, {"item_id": 30}]} colab_type="code" executionInfo={"elapsed": 24080, "status": "ok", "timestamp": 1502999087933, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="mChxOFJnL_kt" outputId="ab2184b1-64b2-4166-e638-9ef35a99c663" # %%time # Train the linear model on the full dataset. ################################################################################ # Specify the model hyperparameters. model_params = {'l2_lambda' : 0.} # Specify the training hyperparameters: training_params = {'num_epochs' : 50, # Max epochs/iterations to train for. 'optimizer_fn' : None, # Now we're using Adam. 'report_every' : 1, # Report training results every nr of epochs. 'eval_every' : 1, # Evaluate on validation data every nr of epochs. 'stop_early' : True } # Build, train, evaluate and plot the results! trained_model, training_results = build_train_eval_and_plot( model_params, training_params, verbose=True # Modify as desired. ) ################################################################################ # + [markdown] colab_type="text" id="dnaNJvLpYp9F" # ~91% is quite a bad score on MNIST! Now let's build a deeper model, to improve on that score. # # ### 1 hidden layer: 784-512-10 Architecture w/ L2 # # Notice that we add a bit of L2-regularization to our model. # # **QUESTION**: What does that do? What is the effect of removing it? Try it! # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 2293, "output_extras": [{"item_id": 49}, {"item_id": 50}, {"item_id": 51}, {"item_id": 52}, {"item_id": 53}]} colab_type="code" executionInfo={"elapsed": 64958, "status": "ok", "timestamp": 1503008137397, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="26XgusXy8OTs" outputId="6e4c8098-3ded-40ca-9281-ebbfc7862953" # %%time # Specify the model hyperparameters (NOTE: All the defaults can be omitted): model_params = { 'hidden_sizes' : [512], # List of hidden layer dimensions, empty for linear model. 'l2_lambda' : 1e-3 # Strength of L2 regularization. } # Specify the training hyperparameters: training_params = { 'num_epochs' : 50, # Max epochs/iterations to train for. 'report_every' : 1, # Report training results every nr of epochs. 'eval_every' : 1, # Evaluate on validation data every nr of epochs. 'stop_early' : True # Use early stopping or not. } # Build, train, evaluate and plot the results! trained_model, training_results = build_train_eval_and_plot( model_params, training_params, verbose=True # Modify as desired. ) # + [markdown] colab_type="text" id="vhfzBJHw_ep6" # **97.7%** is a much more decent score! The 1 hidden layer model gives a much better score than the linear model, so let's see if we can do better by adding another layer! # + [markdown] colab_type="text" id="qJ_Ec2df8YNj" # ### Going deeper! A 784-512-512-10 architecture w/ L2 # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 4044, "output_extras": [{"item_id": 49}, {"item_id": 98}, {"item_id": 100}, {"item_id": 101}, {"item_id": 102}, {"item_id": 103}]} colab_type="code" executionInfo={"elapsed": 166883, "status": "ok", "timestamp": 1502969316725, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="3jALpxhzC6yc" outputId="874ec485-034b-44e5-a771-65bbd620a817" # %%time # Specify the model hyperparameters (NOTE: All the defaults can be omitted): model_params = { 'hidden_sizes' : [512, 512], # List of hidden layer dimensions, empty for linear model. 'l2_lambda' : 1e-3 # Strength of L2 regularization. } # Specify the training hyperparameters: training_params = { 'num_epochs' : 200, # Max epochs/iterations to train for. 'report_every' : 1, # Report training results every nr of epochs. 'eval_every' : 1, # Evaluate on validation data every nr of epochs. 'stop_early' : True, # Use early stopping or not. } # Build, train, evaluate and plot the results! trained_model, training_results = build_train_eval_and_plot( model_params, training_params, verbose=True # Modify as desired. ) # + [markdown] colab_type="text" id="4F5tXNkiHSOQ" # You should get around **97.4**%. Shouldn't deeper do better?! Why is it that the 2-hidden layer model # # * ***took much longer to train*** (2min 46s versus 1min 3s on our system), and # * ***got roughly the same accuracy*** as the 1 hidden layer model (sometimes worse)? # # This illustrates the **fundamental difficulty of training deep networks** that have plagued deep learning research for decades (and to some extent, still do): # # > ***Although deeper networks can give you more powerful models, training those models to find the right parameters is not always easy & takes a lot of computing power (time)!*** # # For a long time people just believed it wouldn't work because a) fewer people tried to make it work, and those who did b) didn't have enough data or computing power to really explore the vast space of hyperparameters. These days, we have more data and more compute power, however one can never have 'enough' resources :) This is where the art of doing proper hyper-parameter selection comes in. In fact, we should be able to squeeze out another percentage point or so by choosing better: # # * Optimizer + its hyperparams (learning rate, momentum rates, etc) # * batch-size, # * choice of regularization. # # For a new problem, we will typically spend most of our time exploring these choices, usually just by launching many different training runs (hopefully in parallel and using GPUs!) and keeping the best ones. # # + [markdown] colab_type="text" id="tzyUXqInbqaB" # # EXTRA: How to Choose Architectures? # # How does one design new architectures? Should you use: # # * a tapered architecture (large-medium-small), # * a "regular" (like the Levi's :) architecture (large-med-med-...-small), # * a "bottlenecked" architecutre (large-small-large)? # * an "over-complete" architecture (small-large-small). # # Unfortunately it mostly comes down to just developing your own intuition over time, and trying different approaches in hyperparameter search. # # However, a good pattern to follow in general is something like the following: # # 1. Start with a basic architecture and overfit a portion of your training data. # 2. As you train on more data, add capacity and prevent overfitting by # * Adding more units to the hidden layer (often times wide still beats deep) # * Add one or two more hidden layers, trying some architectural choices mentioned above. # * Add dropout. # # The goal is to match your architecture to your data, meaning you have just enough capacity to fit the data, but not too much to easily overfit. The easiest way to do this is to gradually build up the capacity of your model in this way. # + [markdown] colab_type="text" id="vkrPMrQoSfK0" # # EXTRA: Hyperparameter Selection (USE A GPU INSTANCE FOR THIS) # # ## Random grid-search # # Most of the deep learning practitioner's time will be spent training and evaluating new model architectures with different hyperparameter combinations. General rules of thumb exist, but often times change for each new architecture or dataset. Several approaches exist for automatic hyperparameter selection (grid search, random search, Bayesian methods). In practice, most people just use a **randomized grid-search** approach to try out different hyperparams, where one defines sensible values for each hyperparameter, and then randomly samples from the (cross-product space) of all of these possible combinations. This space grows exponentially, making exhaustive search infeasible for all but the simplest models. In practice, randomized search have also been found to find the best values, quicker (see [Bergstra and Bengio 2009](http://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf) if you're interested in the details). # # Below, we will illustrate the basic idea with a skeleton randomized grid search implementation. In practice, one would launch these different runs in parallel on a computing cluster, making it easier to explore multiple options at the same time. Here, we would just try out a few different options to get a sense for how that would work. # # **NOTE**: We will keep the models small here (so we won't get SOTA results), in order to keep the training times reasonable, but to illustrate how dependent results are on these choices. # # **Architecture Selection**: Let's consider 1 and 2-hidden layer models. For each layer, we'll try out [128, 256] neurons per layer. We'll stick to ReLUs for this. # # **Hyperparameters**: Let's pick SGD with Momentum as our optimizer (a good, stable workhorse), with a fixed computational budget of 20 training epochs. We'll need to pick ranges for the following: # * *learning rate*: we'll use a log-scale from 1e-5 to 1. # * *momentum coefficient*: we'll use a log-scale from 5e-1 (0.5) to 1. # * *L2 regularization*: we'll use a log-scale from 1e-5 to 1. # # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 71, "output_extras": [{"item_id": 1}]} colab_type="code" executionInfo={"elapsed": 522, "status": "ok", "timestamp": 1503658401647, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="kyf_7dWqd_p1" outputId="cb4464de-cff7-4eee-a798-e11eaef911ec" def sample_log_scale(v_min=1e-6, v_max=1.): '''Sample uniformly on a log-scale from 10**v_min to 10**v_max.''' return np.exp(np.random.uniform(np.log(v_min), np.log(v_max))) def sample_model_architecture_and_hyperparams(max_num_layers=2, lr_min=1e-6, lr_max=1., mom_min=0.5, mom_max=1., l2_min=1e-4, l2_max=1.): '''Generate a random model architecture & hyperparameters.''' # Sample the architecture. num_layers = np.random.choice(range(1, max_num_layers+1)) hidden_sizes = [] layer_ranges=[128, 256] for l in range(num_layers): hidden_sizes.append(np.random.choice(layer_ranges)) # Sample the training parameters. l2_lambda = sample_log_scale(l2_min, l2_max) lr = sample_log_scale(lr_min, lr_max) mom_coeff = sample_log_scale(mom_min, mom_max) # Build base model definitions: model_params = { 'hidden_sizes' : hidden_sizes, 'l2_lambda' : l2_lambda} # Specify the training hyperparameters: training_params = { 'num_epochs' : 20, 'optimizer_fn' : tf.train.MomentumOptimizer( learning_rate=lr, momentum=mom_coeff), 'report_every' : 1, 'eval_every' : 1, 'stop_early' : True} return model_params, training_params # TEST THIS: Run this cell a few times and look at the different outputs. # Each of these will be a different model trained with different hyperparameters. m, t = sample_model_architecture_and_hyperparams() print m print t # + [markdown] colab_type="text" id="VPXaIIZteNU-" # We will play around with the strength of the L2 regularization. Let's use SGD+Momentum, and run for a fixed budget of 20 epochs: # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 1108, "output_extras": [{"item_id": 10}]} colab_type="code" executionInfo={"elapsed": 189573, "status": "ok", "timestamp": 1503227140737, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="Kyb7EOJWiehX" outputId="f221c2a9-4443-4a6d-977c-5b65e5087b74" results = [] # Perform a random search over hyper-parameter space this many times. NUM_EXPERIMENTS = 10 for i in range(NUM_EXPERIMENTS): # Sample the model and hyperparams we are using. model_params, training_params = sample_model_architecture_and_hyperparams() print "RUN: %d out of %d:" % (i, NUM_EXPERIMENTS) print "Sampled Architecture: \n", model_params print "Hyper-parameters:\n", training_params # Build, train, evaluate model, performance = build_train_eval_and_plot( model_params, training_params, verbose=False) # Save results results.append((performance['test_acc'], model_params, training_params)) # Display (best?) results/variance/etc: results.sort(key=lambda x : x[0], reverse=True) # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 207, "output_extras": [{"item_id": 1}]} colab_type="code" executionInfo={"elapsed": 65, "status": "ok", "timestamp": 1503228968350, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="A6E0f3M02xB9" outputId="87d3d8a3-36dc-4f5a-d720-4ef6762f986a" for r in results: print r # Tuples of (test_accuracy, model_hyperparameters, training_hyperparameters) # + [markdown] colab_type="text" id="cgu2OxMS41sF" # **Notice the huuuuge variance in the test accuracies!** This is just a toy run, but hopefully it illustrates how important choosing the right architectures and training hyperparameters is to getting good results in deep learning. # # Below, we've included some hyperparameter settings which achieve near state-of-the-art results. # + [markdown] colab_type="text" id="bsCJW0_gRFX8" # # EXTRA: Known Good Models # + [markdown] colab_type="text" id="x0pO_4fQm8xi" # ## 784-500-300-10 w/ L2 + SGD + Momentum # # **Best so far: 98.02% test accuracy when we ran this (well, in one of our training runs :).** # + colab={"autoexec": {"startup": false, "wait_interval": 0}, "height": 3602, "output_extras": [{"item_id": 49}, {"item_id": 88}, {"item_id": 89}, {"item_id": 90}, {"item_id": 91}]} colab_type="code" executionInfo={"elapsed": 129328, "status": "ok", "timestamp": 1503057210512, "user": {"displayName": "<NAME>", "photoUrl": "//lh4.googleusercontent.com/-6znVyM1oxdg/AAAAAAAAAAI/AAAAAAAAABI/vEPo2Ce7Rpc/s50-c-k-no/photo.jpg", "userId": "102606466886131565871"}, "user_tz": -60} id="J1spLw65l7mY" outputId="ac425ebc-96c1-4025-e493-ad3818bfc5b8" # %%time # Specify the model hyperparameters (NOTE: All the defaults can be omitted): model_params = { 'hidden_sizes' : [500, 300], # List of hidden layer dimensions, empty for linear model. 'l2_lambda' : 1e-3 # Strength of L2 regularization. } # Specify the training hyperparameters: training_params = {'num_epochs' : 100, # Max epochs/iterations to train for. 'optimizer_fn' : tf.train.MomentumOptimizer(learning_rate=2e-3, momentum=0.98), 'report_every' : 1, # Report training results every nr of epochs. 'eval_every' : 1, # Evaluate on validation data every nr of epochs. 'stop_early' : True, # Use early stopping or not. } # Build, train, evaluate and plot the results! trained_model, training_results = build_train_eval_and_plot( model_params, training_params, verbose=True # Modify as desired. ) # + [markdown] colab_type="text" id="tB5r6-oLTzgE" # # NB: Before you go (5min) # # Pair up with someone else and go through the questions in "Learning Objectives" at the top. Take turns explaining each of these to each other, and be sure to ask the tutors if you're both unsure! # + [markdown] colab_type="text" id="3ryLRtd2XfeX" # # Additional Resources # # # + [markdown] colab_type="text" id="PTnXEgI1oMY9" # * TensorFlow Debugging (useful tips and code patterns): https://github.com/wookayin/tensorflow-talk-debugging # # + [markdown] colab_type="text" id="0ZrPt_Ao3z1U" # # Feedback # # Please send any bugs and comments to <EMAIL>.
practical2.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.7 64-bit (''alpacaenv'': conda)' # metadata: # interpreter: # hash: 6a6a73cfb8d5d2b61b0375d533efbc3906bb01b2f10ea48f8a8d12f081066e28 # name: python3 # --- # # Boller Mr. Si Strategy # (Bollinger Bands, MACD, and RSI Strategy) Designed to pay the bills # # + import pandas as pd from stockstats import StockDataFrame as Sdf from libs import connections # Instantiate connection trader = connections.alpaca_trading_connection() # Asset ticker symbol = 'GOOG' # Date range of historical data start_date = pd.Timestamp("2020-09-01", tz="America/New_York").isoformat() end_date = pd.Timestamp("2020-11-17", tz="America/New_York").isoformat() # Capture profit and loss pnl = [] buy_price = 0 sell_price = 0 # Get ticker data stock_df = trader.get_asset_history(symbol, '1D', 500, start_date, end_date).df # Sort columns for stockdataframe data = stock_df[symbol][['open', 'close', 'high', 'low', 'volume']] # Change from pandas dataframe to stockdataframe stock = Sdf.retype(data) # Signal line signal = stock['macds'] # The MACD that need to cross the signal line to give you a Buy/Sell signal macd = stock['macd'] # Since you need at least two days in the for loop listLongShort = ["No data"] for i in range(1, len(signal)): # If the MACD crosses the signal line upward if macd[i] > signal[i] and macd[i - 1] <= signal[i - 1]: listLongShort.append("BUY") buy_price = stock['close'][i] # The other way around elif macd[i] < signal[i] and macd[i - 1] >= signal[i - 1]: listLongShort.append("SELL") # Calculate profit or loss and capture sell_price = stock['close'][i] if (buy_price != 0): pnl.append(sell_price - buy_price) # Do nothing if not crossed else: listLongShort.append("HOLD") stock['Advice'] = listLongShort #pnl = pd.DataFrame(pnl) #pnl.rename(columns={0: 'PnL'}, inplace=True) #pnl_sum = pnl['PnL'].sum() # The advice column means "Buy/Sell/Hold" at the end of this day or # at the beginning of the next day, since the market will be closed print(stock['Advice']) #print(f'PnL: {pnl_sum: 0.4f}') # + # Import necessary libraries import pandas as pd from libs import connections, strategies # Instantiate variables ticker_symbol = 'GOOG' timeframe = '1D' num_intervals = 1000 starting_date = '2020-11-17' ending_date = '2020-11-17' # Setup connection to Alpaca trader = connections.alpaca_trading_connection() # Get ticker data stock_df = trader.get_asset_history(ticker_symbol, timeframe, num_intervals, starting_date, ending_date).df print(stock_df['GOOG']) # - # Get all active tradable asset symbols from Alpaca securities = trader.get_all_assets_to_trade() # + from statsmodels.tsa.seasonal import seasonal_decompose tradable_symbols = [] # Assign only tradable symbols to list for security in securities: tradable_symbols.append(security.symbol) # Sort the symbols tradable_symbols = sorted(tradable_symbols) #historical_data = trader.get_asset_history(tradable_symbols, '1D', 1000, '2019-11-30', '2020-11-30') #seasonal_decompose() # -
scratch.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.2 64-bit # name: python3 # --- # # Working with the `TonnageListAPI` # ## Setup # Install the Signal Ocean SDK: # !pip install signal-ocean # Set your subscription key, acquired here: [https://apis.signalocean.com/profile](https://apis.signalocean.com/profile) signal_ocean_api_key = "" # replace with your subscription key # ## Retrieving a historical tonnage list # First, we need to create an instance of the `TonnageListAPI`: # + from signal_ocean import Connection from signal_ocean.tonnage_list import TonnageListAPI connection = Connection(signal_ocean_api_key) api = TonnageListAPI(connection) # - # # Then, we need to determine the parameters of the **historical tonnage list** (**HTL**). In order to fetch an HTL, we will need to specify: # - a loading port, # - a vessel class, # - a time frame. # # Ports and vessel classes can be retrieved through the `get_ports` and `get_vessel_classes` methods: api.get_vessel_classes() # Ports can be looked up by their name using the `PortFilter`: # + from signal_ocean.tonnage_list import PortFilter api.get_ports(PortFilter(name_like="rot")) # - # And so can vessel classes with the use of the `VesselClassFilter`: # + from signal_ocean.tonnage_list import VesselClassFilter api.get_vessel_classes(VesselClassFilter(name_like="MAX")) # - # Note that the search is case-insensitive and does not require specifying exact names. # # We want our HTL to contain Aframax vessels in Ceyhan, with a 6-day forward laycan end, for the last 90 days: # + from datetime import timedelta, date vessel_class_filter = VesselClassFilter(name_like="aframax") vessel_class = api.get_vessel_classes(vessel_class_filter)[0] port_filter = PortFilter(name_like="ceyhan") port = api.get_ports(port_filter)[0] laycan_end_in_days = 6 today = date.today() start_date = today - timedelta(days=5) # - # With the parameters above, we can now request an HTL: # + from signal_ocean.tonnage_list import DateRange htl = api.get_historical_tonnage_list( port, vessel_class, laycan_end_in_days, DateRange(start_date, today) ) # - # The resulting historical tonnage list is a Python object that contains a collection of tonnage lists, each of which has a timestamp and a collection of vessel data. The tonnage lists are ordered by date in descending order: yesterdays_tl = htl[1] print("Date:", yesterdays_tl.date) print("Vessel count:", len(yesterdays_tl.vessels)) print("Example vessel:", yesterdays_tl.vessels[0]) # The result can also be converted into a Pandas data frame: data_frame = htl.to_data_frame() data_frame # ### Example 1 - Plotting a supply trend # The data frame format makes it very easy to generate a supply trend plot. # # We'll generate a supply trend from the beginning of the year, but we'll also filter the vessel list by looking for vessels that: # - are pushed, # - have a market deployment type of "Relet" or "Spot", # - their commercial status is available, cancelled or failed, # - are crude oil tankers (their vessel subclass is "Dirty"), # - their AIS information is no older than 5 days. # # Filtering can be achieved by creating an instance of a `VesselFilter` and passing it to the `get_historical_tonnage_list` method. A `VesselFilter` meeting the above criteria will look as follows: # + from signal_ocean.tonnage_list import ( VesselFilter, PushType, MarketDeployment, CommercialStatus, VesselSubclass, ) vessel_filter = VesselFilter( push_types=[PushType.PUSHED], market_deployments=[MarketDeployment.RELET, MarketDeployment.SPOT], commercial_statuses=[ CommercialStatus.AVAILABLE, CommercialStatus.CANCELLED, CommercialStatus.FAILED, ], vessel_subclass=VesselSubclass.DIRTY, latest_ais_since=5, ) # - # Note the usage of the `PushType`, `MarketDeployment`, `CommercialStatus`, and `VesselSubclass`. These are enum-like classes that contain constants for all the possible values for a given `VesselFilter` parameter. To list the available values for any of the classes, just invoke `list()` on the class: list(CommercialStatus) # You can use these values directly or use a corresponding class member: CommercialStatus.ON_SUBS == 'On Subs' # Let's get the HTL for our filter: # + beginning_of_year = date(today.year, 1, 1) htl_for_supply_trend = api.get_historical_tonnage_list( port, vessel_class, laycan_end_in_days, DateRange(start_date, today), vessel_filter=vessel_filter, ) supply_trend_data_frame = htl_for_supply_trend.to_data_frame() supply_trend_data_frame # - # Now, we can generate the plot: # + from signal_ocean.tonnage_list import IndexLevel supply_trend = supply_trend_data_frame.groupby( IndexLevel.DATE, sort=True ).size() plot = supply_trend.plot() plot.set_ylabel("Vessel count") plot # - # ### Example 2 - Generating an Excel sheet # The data frame can be easily saved as an Excel file by using Pandas's built-in `to_excel()` function. # # Before we do that, we need to remove all the time zone information from all timestamps in the data frame. This is because Excel does not support storing time zone information along with timestamps. However, Signal Ocean's SDK always provides time zone information to make all timestamp-based computation unambiguous. # + from signal_ocean.tonnage_list import Column without_time_zones = ( supply_trend_data_frame.reset_index() .astype( { IndexLevel.DATE: "datetime64[ns]", Column.OPEN_DATE: "datetime64[ns]", Column.ETA: "datetime64[ns]", Column.LATEST_AIS: "datetime64[ns]", } ) .set_index([IndexLevel.DATE, IndexLevel.IMO]) ) # - # Now, we can generate the Excel file: without_time_zones.to_excel('htl.xlsx') # ## Retrieving a live tonnage list # Retrieving a live tonnage list is almost exactly the same as getting a historical one except, instead of using the `get_historical_tonnage_list` method, you use the `get_tonnage_list` method and you don't pass a `DateRange` as an argument. The `get_tonnage_list` method returns a single `TonnageList` that contains live vessel data. # # Because of this similarity, we can reuse the parameters we used for our HTL queries: tonnage_list = api.get_tonnage_list( port, vessel_class, laycan_end_in_days, vessel_filter ) tonnage_list # We can also convert the resulting tonnage list to a data frame: tonnage_list.to_data_frame()
docs/examples/jupyter/Tonnage List API/Working with the TonnageListAPI.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/maicken/crying_cat_generator/blob/main/crying_cat_generator.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="bobQZ-QYpdZh" # # Clone git # + colab={"base_uri": "https://localhost:8080/"} id="fIWo_YL_nfzw" outputId="065c7cc4-3ba2-4b63-bd6d-6118af47be3a" # !git clone https://github.com/maicken/crying_cat_generator.git # %cd crying_cat_generator # + colab={"base_uri": "https://localhost:8080/"} id="nzL9gC3tn4iX" outputId="3b3249cc-1f34-4232-d0ed-fd90c63a0f21" # !pip install -e . # + id="FBNP1yBSu4on" # !mkdir images # + [markdown] id="1L2re6QHpgOO" # # Add images for testing # # In the menu in your left (Files), add your cat image to the following path: # # "/crying_cat_generator/images" # # # + [markdown] id="HfU46sLF132X" # # Run code # + colab={"base_uri": "https://localhost:8080/"} id="7SNfOSbsogfd" outputId="862be0a2-ce65-4fb5-c018-4906782748b0" # !python src/crying_cat_generator.py -f 'images' # + [markdown] id="UTohxsVs16iW" # # Visualize Results # # You can find the final output in the folder "results" # + id="SX4NM17SrUcJ"
crying_cat_generator.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.0.0 # language: julia # name: julia-1.0 # --- # # 矩阵分解与其他妙用 # 该教程由<NAME>所做的工作改编而成 # # ## 大纲 # - 矩阵分解 # - 特殊矩阵 # - 一般化线性代数 # 正式开始之前,让我们先来建立一个线性系统,并利用`LinearAlgebra`库来进行矩阵分解或处理特殊矩阵。 using LinearAlgebra A = rand(3, 3) x = fill(1, (3,)) b = A * x # ## 矩阵分解 # # #### LU分解 # 在Julia中,我们可以使用`lufact`进行LU分解: # ```julia # PA = LU # ``` # 其中`P`是置换矩阵,`L`是对角全为1的下三角矩阵(单位下三角矩阵),`U`是上三角矩阵。 # # Julia可以计算LU分解,并定义一个复合分解数据类型用以储存分解后的结果。 Alu = lu(A) typeof(Alu) # 可以通过这个类的特殊属性来调取分解出来的矩阵: Alu.P Alu.L Alu.U # Julia可以对储存分解结果的对象派发方法。 # # 比如,在解算当前的线性系统时,我们既可以使用原本的矩阵,也可以使用分解运算所生成的对象: A\b Alu\b # 相似地,要计算矩阵`A`的行列式,既可以使用原本的矩阵,也可以使用分解运算所生成的对象: det(A) ≈ det(Alu) # #### QR分解 # # 在Julia中,可以使用`qrfact`来计算QR分解: # ``` # A=QR # ``` # # 其中`Q`是正交阵/酉矩阵,`R`是上三角矩阵。 Aqr = qr(A) # 与LU分解类似,矩阵`Q`和`R`可以通过以下语句从QR分解对象中调取: Aqr.Q Aqr.R # #### 特征分解 # 特征分解、奇异值分解(SVD)、Hessenberg分解、Schur分解的结果都是以`Factorization`类型来储存的。 # # 以下语句可用于计算特征值: Asym = A + A' AsymEig = eigen(Asym) # 通过特殊索引,可以从Eigen类型中提取计算得到的特征值和特征向量: AsymEig.values AsymEig.vectors # 再一次地,当分解结果被储存为特定的类型时,我们可以对它使用派发方法,也可以编写一些具有针对性的方法以充分利用矩阵分解的性质。例如,$A^{-1}=(V\Lambda V^{-1})^{-1}=V\Lambda^{-1}V^{-1}$。 inv(AsymEig)*Asym # ## 特殊矩阵结构 # 矩阵结构在线性代数中有着尤为重要的作用。让我们通过一个大型线性系统来看看它到底有*多重要*吧: n = 1000 A = randn(n,n); # 通常,Julia可以自动推断出特殊矩阵结构: Asym = A + A' issymmetric(Asym) # 但有时浮点误差会阻碍这一功能: Asym_noisy = copy(Asym) Asym_noisy[1,2] += 5eps() issymmetric(Asym_noisy) # 幸运的是,我们可以使用`Diagonal`(对角)、`Triangular`(三角)、`Symmetric`(对称)、`Hermitian`(厄米/自共轭矩阵)、`Tridiagonal`(三对角)、`SymTridiagonal`(对称三对角)等函数显式地定义特殊矩阵。 Asym_explicit = Symmetric(Asym_noisy); # 现在,我们来比较Julia在计算`Asym`、`Asym_noisy`和`Asym_explicit`的特征值时各自需要多长时间: @time eigvals(Asym); @time eigvals(Asym_noisy); @time eigvals(Asym_explicit); # 在这个示例中,对`Asym_noisy`使用`Symmetric()`使得我们的运算效率提高了`5倍` :) # #### 一个“大”问题 # 用`Tridiagonal`和`SymTridiagonal`类型储存三对角矩阵让我们得以处理有可能非常庞大的三对角问题。对于下面的示例问题而言,如果矩阵被储存为一个(稠密的)`Matrix`类型,那么一台笔记本电脑的配置将会不足以支持该问题的解算。 n = 1_000_000; A = SymTridiagonal(randn(n), randn(n-1)); @time eigmax(A) # ## 一般化线性代数 # 要在语言中添加对数值化的线性代数的支持,常规的手段是包装BLAS和LAPACK中的子程序。对于含有`Float32`、`Float64`、`Complex{Float32}`或`Complex{Float64}`等类型的元素的矩阵,这正是Julia的处理方式。 # # 然而,Julia也支持一般化的线性代数。运用这一特性的其中一个例子便是处理有理数矩阵和向量。 # #### 有理数 # Julia内嵌有对有理数的支持。使用双斜杠以构建一个有理数: 1//2 # #### 示例:有理数线性方程组 # 下面的例子将会演示如何在不将矩阵元素转化为浮点类型的前提下求解一个含有有理数的线性方程组。在处理有理数时,数值溢出很容易成为一个问题,因此我们使用`BigInt`类型: Arational = Matrix{Rational{BigInt}}(rand(1:10, 3, 3))/10 x = fill(1, 3) b = Arational*x Arational\b lu(Arational) # ### 练习 # # #### 11.1 # 求解矩阵A的特征值 # # ``` # A = # [ # 140 97 74 168 131 # 97 106 89 131 36 # 74 89 152 144 71 # 168 131 144 54 142 # 131 36 71 142 36 # ] # ``` # 并将它赋给变量`A_eigv`。 using LinearAlgebra # + deletable=false editable=false hide_input=true nbgrader={"checksum": "f9f16fdef201ed372323a291f1dd1346", "grade": true, "grade_id": "cell-4d5f60c8a814c789", "locked": true, "points": 0, "schema_version": 1, "solution": false} @assert A_eigv == [-128.49322764802145, -55.887784553056875, 42.7521672793189, 87.16111477514521, 542.4677301466143] # - # #### 11.2 # 由`A`的特征值构建一个`Diagonal`(对角)矩阵。 # + deletable=false editable=false hide_input=true nbgrader={"checksum": "3ca676f6282c1a7c214ab2cb9f9b322d", "grade": true, "grade_id": "cell-3b000a3710c9c263", "locked": true, "points": 1, "schema_version": 1, "solution": false} @assert A_diag == [-128.493 0.0 0.0 0.0 0.0; 0.0 -55.8878 0.0 0.0 0.0; 0.0 0.0 42.7522 0.0 0.0; 0.0 0.0 0.0 87.1611 0.0; 0.0 0.0 0.0 0.0 542.468] # - # #### 11.3 # 由`A`构建一个`LowerTriangular`(下三角)矩阵,并将其储存为`A_lowertri`。 # + deletable=false editable=false hide_input=true nbgrader={"checksum": "b3b1a272343a05082f378a5e1aa3426d", "grade": true, "grade_id": "cell-b76cee2b4a8777da", "locked": true, "points": 0, "schema_version": 1, "solution": false} @assert A_lowertri == [140 0 0 0 0; 97 106 0 0 0; 74 89 152 0 0; 168 131 144 54 0; 131 36 71 142 36] # - # ### 反馈与评价(英文): # https://tinyurl.com/introJuliaFeedback # 完成练习后请点击顶部的`Validate`按钮。
zh-cn/intro-to-julia-ZH/12.矩阵分解与其他妙用.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (Ubuntu Linux) # language: python # name: python3 # --- # # The Astro 300 Python programming style guide # ![XKCD Style](http://imgs.xkcd.com/comics/code_quality.png) # This notebook is a summary of the python programming style we will use in # Astro 300. # # **Half** of your grade, on each assignment, # will be based on how well your code follows these guidelines. # # These guidelines are a small subset of the # [PEP 8](https://www.python.org/dev/peps/pep-0008/) # programming style used by python developers. # `|--------|---------|---------|---------|---------|---------|---------|---------` # # Variable Names # # - use only lowercase letters [a-z] and underscores [ _ ] # - no blank spaces between the characters # - avoid using a single character as a variable name # - The purpose of the variable should be obvious from its name # ### *An Example:* # # You want to find the kinetic energy of a particle with mass 10 and velocity 20: # # $$ \mathrm{Kinetic\ Energy}\ = \frac{1}{2}\ mv^2 $$ # + # Good - Full credit mass_particle = 10.0 velocity_particle = 20.0 kinetic_energy = 0.5 * mass_particle * (velocity_particle ** 2) print(kinetic_energy) # + # Bad - Half credit at best x = 10.0 y = 20.0 print(0.5*x*y**2) # + # Really bad - no credit print(0.5*10*20**2) # - # `|--------|---------|---------|---------|---------|---------|---------|---------` # # Function Names # # Use the same guidelines as for variable names # + # Good def find_kinetic_energy(mass_part, velocity_part): kinetic_energy = 0.5 * mass_part * velocity_part ** 2 return(kinetic_energy) # + # Bad def KE(x,y): return(0.5*x*y**2) # + # Good mass_particle = 10.0 velocity_particle = 20.0 kinetic_energy = find_kinetic_energy(mass_particle,velocity_particle) print(kinetic_energy) # + # Bad print(KE(10,20)) # - # `|--------|---------|---------|---------|---------|---------|---------|---------` # # Line Length # # - Limit all lines to a maximum of 79 characters # - The piece that seperates the sections in this notebook is 79 characters long # - If you have to scroll horizontally - your line is too long # # The preferred way of wrapping long lines is by using Python's implied line continuation # inside parentheses (), brackets [] and braces {}. # # Long lines can be broken over multiple lines by wrapping expressions in parentheses. # ### *An Example:* # + # Some variables to use in an equation gross_wages = 50000 taxable_interest = 1000 dividends = 50 qualified_dividends = 10 ira_deduction = 2000 student_loan_interest = 3000 medical_deduction = 1000 # + # Good income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest - medical_deduction) print(income) # + # Bad income = gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest - medical_deduction print(income) # - # ### Long text can be wrapped in `"""` quote_the_raven = """ Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore— While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door. "Tis some visiter," I muttered, "tapping at my chamber door— Only this and nothing more." """ print(quote_the_raven) # `|--------|---------|---------|---------|---------|---------|---------|---------` # ## Spaces # # - Use spaces around math symbols # # `Yes: my_answer = 2 + 4` # # `No: my_answer=2+4` # # # - Avoid spaces inside parentheses, brackets or braces, except after commas. # # `Yes: my_answer = spam(ham[1], {eggs: 2})` # # `No: my_answer = spam( ham[ 1 ], { eggs: 2 } )` # # # You should always try to make your code as readable as possible. # # ### Feel free to break any of these rules if it makes your code easier to understand by *someone who has never seen your code.*
StyleGuide.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 # --- # + # # !wget https://raw.githubusercontent.com/huseinzol05/malay-dataset/master/sentiment/news-sentiment/sentiment-data-v2.csv # + # # !wget https://f000.backblazeb2.com/file/malay-dataset/sentiment/positive/strong-positives.json # # !wget https://f000.backblazeb2.com/file/malay-dataset/sentiment/negative/strong-negatives-2.json # + # # !wget https://raw.githubusercontent.com/huseinzol05/malay-dataset/master/sentiment/translate/multidomain-sentiment/bm-amazon.json # # !wget https://raw.githubusercontent.com/huseinzol05/malay-dataset/master/sentiment/translate/multidomain-sentiment/bm-imdb.json # # !wget https://raw.githubusercontent.com/huseinzol05/malay-dataset/master/sentiment/translate/multidomain-sentiment/bm-yelp.json # - from malaya.text.bpe import WordPieceTokenizer tokenizer = WordPieceTokenizer('BERT.wordpiece', do_lower_case = False) # tokenizer.tokenize('halo nama sayacomel') # + import random from unidecode import unidecode import re normalized_chars = {} chars = '‒–―‐—━—-▬' for char in chars: normalized_chars[ord(char)] = '-' chars = '«»“”¨"' for char in chars: normalized_chars[ord(char)] = '"' chars = "’'ʻˈ´`′‘’\x92" for char in chars: normalized_chars[ord(char)] = "'" chars = '̲_' for char in chars: normalized_chars[ord(char)] = '_' chars = '\xad\x7f' for char in chars: normalized_chars[ord(char)] = '' chars = '\n\r\t\u200b\x96' for char in chars: normalized_chars[ord(char)] = ' ' laughing = { 'huhu', 'haha', 'gagaga', 'hihi', 'wkawka', 'wkwk', 'kiki', 'keke', 'huehue', 'hshs', 'hoho', 'hewhew', 'uwu', 'sksk', 'ksks', 'gituu', 'gitu', 'mmeeooww', 'meow', 'alhamdulillah', 'muah', 'mmuahh', 'hehe', 'salamramadhan', 'happywomensday', 'jahagaha', 'ahakss', 'ahksk' } def make_cleaning(s, c_dict): s = s.translate(c_dict) return s def cleaning(string): """ use by any transformer model before tokenization """ string = unidecode(string) string = ' '.join( [make_cleaning(w, normalized_chars) for w in string.split()] ) string = re.sub('\(dot\)', '.', string) string = ( re.sub(re.findall(r'\<a(.*?)\>', string)[0], '', string) if (len(re.findall(r'\<a (.*?)\>', string)) > 0) and ('href' in re.findall(r'\<a (.*?)\>', string)[0]) else string ) string = re.sub( r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', ' ', string ) chars = '.,/' for c in chars: string = string.replace(c, f' {c} ') string = re.sub(r'[ ]+', ' ', string).strip().split() string = [w for w in string if w[0] != '@'] x = [] for word in string: word = word.lower() if any([laugh in word for laugh in laughing]): if random.random() >= 0.5: x.append(word) else: x.append(word) string = [w.title() if w[0].isupper() else w for w in x] return ' '.join(string) # + import pandas as pd from sklearn.preprocessing import LabelEncoder import re from unidecode import unidecode df = pd.read_csv('sentiment-data-v2.csv') Y = LabelEncoder().fit_transform(df.label) texts = df.iloc[:,1].tolist() labels = Y.tolist() assert len(labels) == len(texts) # + import json with open('bm-amazon.json') as fopen: amazon = json.load(fopen) with open('bm-imdb.json') as fopen: imdb = json.load(fopen) with open('bm-yelp.json') as fopen: yelp = json.load(fopen) texts += amazon['negative'] labels += [0] * len(amazon['negative']) texts += amazon['positive'] labels += [1] * len(amazon['positive']) texts += imdb['negative'] labels += [0] * len(imdb['negative']) texts += imdb['positive'] labels += [1] * len(imdb['positive']) texts += yelp['negative'] labels += [0] * len(yelp['negative']) texts += yelp['positive'] labels += [1] * len(yelp['positive']) # + with open('strong-positives.json') as fopen: positives = json.load(fopen) positives = random.sample(positives, 500000) len(positives) # + with open('strong-negatives.json') as fopen: negatives = json.load(fopen) negatives = random.sample(negatives, 500000) len(negatives) # - texts += negatives labels += [0] * len(negatives) texts += positives labels += [1] * len(positives) # + from tqdm import tqdm for i in tqdm(range(len(texts))): texts[i] = cleaning(texts[i]) # + actual_t, actual_l = [], [] for i in tqdm(range(len(texts))): if len(texts[i]) > 2: actual_t.append(texts[i]) actual_l.append(labels[i]) # + from tqdm import tqdm input_ids, input_masks = [], [] for text in tqdm(actual_t): tokens_a = tokenizer.tokenize(text) tokens = ["[CLS]"] + tokens_a + ["[SEP]"] input_id = tokenizer.convert_tokens_to_ids(tokens) input_mask = [1] * len(input_id) input_ids.append(input_id) input_masks.append(input_mask) # + import pickle with open('sentiment-fastformer.pkl', 'wb') as fopen: pickle.dump([input_ids, actual_l], fopen) # -
session/sentiment/preprocess-fastformer.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 restaurants = pd.read_csv('NYC_RestaurantInspection_deduped.csv') restaurants.head() restaurants.info() # ### Top Fast Food Chains (top 5) # https://www.qsrmagazine.com/content/ranking-top-50-fast-food-chains-america # # McDonald's # Subway # Taco Bell # Chick-Fil-A # Wendy's # Burger King # KFC # Arby's # Popeyes # ##### McDonald's McDonalds = restaurants[restaurants['DBA'].str.contains('MCDONALD', case = False, na = False)] McDonalds['DBA'].unique() print("McDonald's count: ", McDonalds['DBA'].count()) # ##### Domino's dominos = restaurants[restaurants['DBA'].str.contains('DOMINOS', case = False, na = False)] dominos['DBA'].unique() print("Subway count: ", subway['DBA'].count()) # ##### Taco Bell tacobell = restaurants[restaurants['DBA'].str.contains('TACO BELL', case = False, na = False)] tacobell['DBA'].unique() print("Taco Bell count: ", tacobell['DBA'].count()) # ##### Chick-Fil-A chickfila = restaurants[restaurants['DBA'].str.contains('CHICK-FIL-A', case = False, na = False)] chickfila['DBA'].unique() print("Chick-Fil-A count: ", chickfila['DBA'].count()) # ##### Wendy's wendys = restaurants[restaurants['DBA'].str.contains('WENDY', case = False, na = False)] wendys['DBA'].unique() print("Wendy's count: ", wendys['DBA'].count()) # ##### Burger King bk = restaurants[restaurants['DBA'].str.contains('BURGER KING', case = False, na = False)] bk['DBA'].unique() print("Wendy's count: ", wendys['DBA'].count()) # ##### KFC kfc = restaurants[restaurants['DBA'].str.contains('KFC', case = False, na = False)] kfc['DBA'].unique() print("KFC count: ", kfc['DBA'].count()) # ##### Arby's arbys = restaurants[restaurants['DBA'].str.contains('ARBY', case = False, na = False)] arbys['DBA'].unique() print("Arby's count: ", arbys['DBA'].count()) # ##### Popeyes popeyes = restaurants[restaurants['DBA'].str.contains('POPEYES', case = False, na = False)] popeyes['DBA'].unique() print("Popeyes count: ", popeyes['DBA'].count())
fast_food_name_variations.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: juxta (Python3) # language: python # name: juxta # --- # %load_ext pycodestyle_magic # %pycodestyle_on import pandas as pd df = pd.read_csv('..\\src\\extraneous_datasets\\finaldataset.csv') print(df.columns) final0318 = pd.read_csv('..\\src\\extraneous_datasets\\final_0318.csv') print(final0318.columns) weather = df[['city', 'Coldday_Count', 'Hotday_Count', 'Rainday_Count']] weather.head() final = final0318.merge(weather).drop(columns='Unnamed: 0') final.columns final.head() final.to_csv('..\\src\\extraneous_datasets\\final_0427.csv')
findurcity/notebooks/Weather - Anika.ipynb
import apache_beam as beam import os import shutil import tensorflow as tf import tensorflow_model_analysis as tfma from tensorflow_transform.beam.tft_beam_io import transform_fn_io from tensorflow_transform.coders import example_proto_coder from tensorflow_transform.saved import saved_transform_io from tensorflow_transform.tf_metadata import dataset_schema # Edit the following, **replacing `<YOUR_BUCKET_PATH>` and `<WORKFLOW_NAME>` with the correct values**. You can find the name of a given workflow by looking at the `argo submit` output, or in the Argo UI. The workflow name is also reflected in the Kubernetes pod names. OUTPUT_PATH_PREFIX = 'gs://<YOUR_BUCKET_PATH>/<WORKFLOW_NAME>/' tfma_result1 = tfma.load_eval_result( output_path= OUTPUT_PATH_PREFIX + 'tfma/output') tfma_result2 = tfma.load_eval_result( output_path=OUTPUT_PATH_PREFIX + 'tfma2/output') tfma.view.render_slicing_metrics( tfma_result1, slicing_column='trip_start_hour') tfma.view.render_slicing_metrics( tfma_result2, slicing_column='trip_start_hour') # + # An empty slice spec means the overall slice, that is, the whole dataset.# An em OVERALL_SLICE_SPEC = tfma.SingleSliceSpec() # Data can be sliced along a feature column # In this case, data is sliced along feature column trip_start_hour. FEATURE_COLUMN_SLICE_SPEC = tfma.SingleSliceSpec(columns=['trip_start_hour']) # Data can be sliced by crossing feature columns # In this case, slices are computed for trip_start_day x trip_start_month. FEATURE_COLUMN_CROSS_SPEC = tfma.SingleSliceSpec(columns=['trip_start_day', 'trip_start_month']) # Metrics can be computed for a particular feature value. # In this case, metrics is computed for all data where trip_start_hour is 12. FEATURE_VALUE_SPEC = tfma.SingleSliceSpec(features=[('trip_start_hour', 12)]) # It is also possible to mix column cross and feature value cross. # In this case, data where trip_start_hour is 12 will be sliced by trip_start_day. COLUMN_CROSS_VALUE_SPEC = tfma.SingleSliceSpec(columns=['trip_start_day'], features=[('trip_start_hour', 12)]) ALL_SPECS = [ OVERALL_SLICE_SPEC, FEATURE_COLUMN_SLICE_SPEC, FEATURE_COLUMN_CROSS_SPEC, FEATURE_VALUE_SPEC, COLUMN_CROSS_VALUE_SPEC ] # - # Show metrics sliced by COLUMN_CROSS_VALUE_SPEC above. tfma.view.render_slicing_metrics(tfma_result1, slicing_spec=COLUMN_CROSS_VALUE_SPEC) # Show overall metrics. tfma.view.render_slicing_metrics(tfma_result1) # Show overall metrics. tfma.view.render_slicing_metrics(tfma_result2) # Visualize the results in a Time Series. In this case, we are showing the slice specified. eval_results_from_disk = tfma.load_eval_results([ OUTPUT_PATH_PREFIX + 'tfma/output', OUTPUT_PATH_PREFIX + 'tfma2/output' ], tfma.constants.MODEL_CENTRIC_MODE) tfma.view.render_time_series(eval_results_from_disk, FEATURE_VALUE_SPEC) # Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
ml/kubeflow-pipelines/components/dataflow/tfma/tfma_expers.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 # --- # + # # %sh # wget https://raw.githubusercontent.com/fivethirtyeight/data/master/police-killings/police_killings.csv # + import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # %matplotlib inline police_killings = pd.read_csv("police_killings.csv") police_killings.head() # - print(police_killings.columns.values) print(police_killings["raceethnicity"].value_counts()) # ### Shootings by race # + raceethnicity_killings = police_killings["raceethnicity"].value_counts() raceethnicity_killings.plot(kind="bar") plt.show() plt.close() # - # ### Shootings by regional income # + # Filter "-" records income = police_killings[police_killings["p_income"] != "-"] print("police_killings: {0}".format(police_killings.shape)) print("income: {0}".format(income.shape)) # Convert p_income data type to integer income["p_income"] = income["p_income"].astype(int) print(police_killings["p_income"].dtypes) print(income["p_income"].dtypes) # Plot a histogram income["p_income"].hist(bins=20) plt.show() plt.close() # - # ### Shootings by state # + # https://www.census.gov/popest/data/state/asrh/2015/files/SCPRC-EST2015-18+POP-RES.csv state_pop = pd.read_csv("SCPRC-EST2015-18+POP-RES.csv") state_pop.head() # - state_pop.dtypes print(police_killings["state_fp"].head()) print(state_pop["STATE"].head()) counts = police_killings["state_fp"].value_counts() # + # Create new dataframe states = pd.DataFrame({ "STATE": counts.index, "shootings": counts }) states.head() # + # Join shootings with state population states = states.merge(state_pop[["STATE", "NAME", "POPESTIMATE2015"]], on="STATE") states.head() # + # Create population (in millions) column states["pop_millions"] = states["POPESTIMATE2015"] / 1000000 states.head() # + # Create shootings per million people column states["rate"] = states["shootings"] / states["pop_millions"] states = states.sort_values(by="rate", ascending=False) states.head() # - # ### State by state differences # + share = ["share_black", "share_white", "share_hispanic"] share_filter = (police_killings["share_black"] != "-") & (police_killings["share_white"] != "-") & \ (police_killings["share_hispanic"] != "-") pk = police_killings[share_filter] print(police_killings.shape) print(pk.shape) pk[share] = pk[share].astype(float) # + highest_10 = states["STATE"].head(10) lowest_10 = states["STATE"].tail(10) highest_10_df = police_killings[police_killings["state_fp"].isin(highest_10)] lowest_10_df = police_killings[police_killings["state_fp"].isin(lowest_10)] print(highest_10_df.shape) print(lowest_10_df.shape) print(highest_10_df.head()) print(lowest_10_df.head()) # + highest_mean = pd.Series(highest_10_df.mean(), name="highest") lowest_mean = pd.Series(lowest_10_df.mean(), name="lowest") compared_mean = pd.concat([highest_mean, lowest_mean], axis=1) pd.options.display.float_format = '{:20,.2f}'.format print(compared_mean) # -
Data Exploration/Guided Project - Police killings.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="sp7D0ktn5eiG" # ## Tweet Emotion Recognition: Natural Language Processing with TensorFlow # # --- # # Dataset: [Tweet Emotion Dataset](https://github.com/dair-ai/emotion_dataset) # # This is a starter notebook for the guided project [Tweet Emotion Recognition with TensorFlow](https://www.coursera.org/projects/tweet-emotion-tensorflow) # # A complete version of this notebook is available in the course resources # # --- # # ## Task 1: Introduction # + [markdown] id="cprXxkrMxIgT" # ## Task 2: Setup and Imports # # 1. Installing Hugging Face's nlp package # 2. Importing libraries # + id="5agZRy-45i0g" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627385262570, "user_tz": 0, "elapsed": 5213, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="59608c57-6b92-4d14-a321-96484bd5e1ed" # !pip install nlp # + id="yKFjWz6e5eiH" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627385272973, "user_tz": 0, "elapsed": 6319, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="3a1ad01e-18e4-434a-e4bb-69c13988e9d8" # %matplotlib inline import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import nlp import random def show_history(h): epochs_trained = len(h.history['loss']) plt.figure(figsize=(16, 6)) plt.subplot(1, 2, 1) plt.plot(range(0, epochs_trained), h.history.get('accuracy'), label='Training') plt.plot(range(0, epochs_trained), h.history.get('val_accuracy'), label='Validation') plt.ylim([0., 1.]) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(range(0, epochs_trained), h.history.get('loss'), label='Training') plt.plot(range(0, epochs_trained), h.history.get('val_loss'), label='Validation') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() def show_confusion_matrix(y_true, y_pred, classes): from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_true, y_pred, normalize='true') plt.figure(figsize=(8, 8)) sp = plt.subplot(1, 1, 1) ctx = sp.matshow(cm) plt.xticks(list(range(0, 6)), labels=classes) plt.yticks(list(range(0, 6)), labels=classes) plt.colorbar(ctx) plt.show() print('Using TensorFlow version', tf.__version__) # + [markdown] id="7JsBpezExIga" # ## Task 3: Importing Data # # 1. Importing the Tweet Emotion dataset # 2. Creating train, validation and test sets # 3. Extracting tweets and labels from the examples # + id="0YHOvjAu5eiL" colab={"base_uri": "https://localhost:8080/", "height": 333, "referenced_widgets": ["4f7207af82394abc8cad23ba168d892d", "f391c9c0b4c7441585fe87bed5188292", "2aa9728fcb8f410db203a073ffbfca29", "265ca572fdb7474fa1ad1049d6557205", "6d50e066b0a1450bb0b9e28e206e6187", "ff52a696288440068d78b93d7d953752", "d53aa219e1f441b5a3beca3a650fe26f", "6385a85b718c474b9ca8d861d4b746e3", "994e46bea02d465c8c1ff90e806175d0", "c86ba4aeb5d5444896f157ca0d32eeaa", "2e7e99650a4d4eb7a114da36011d119d", "7c7554448a1743caa4649acb3ebe33b3", "e2da9f355c5a4f13a9f08db2b8c96285", "2376d7e5520f4634a705ce0e0b8c5874", "325c785340344fa2a55ca58cf9cc53a5", "f3e40e7c443844e1b855e2c245561e0a", "<KEY>", "7b5a87a179cd4e0d8b6f9ed55c58550c", "<KEY>", "e43fab0063804ad09ae30cfce9cf9623", "d10f3edced204943961a9e7720258b4b", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "ddeaa0f4aa1843dd97f8a3c88531e301", "d3798b365e5d45f8a1b82c1ebb63830e", "<KEY>", "2fb8f77de1134a9d906c82e91b436090", "<KEY>", "<KEY>", "<KEY>", "7312e2e9d6b747acb91e1be221f520be", "3242faba1d4a41d5855a2ad18312ab18", "<KEY>", "<KEY>", "<KEY>", "3f479fb500714aa895de16d6d9fb2426", "<KEY>", "b8c60ad78d1f4241b37a043bb3c9e931", "<KEY>", "a450b7497e0747fe89dcfe3cda5648ca", "e96e3915ffc84bd4b4e264be53eb097e", "<KEY>", "<KEY>", "91cea4a298ec453ab8494edec5b528e2", "<KEY>", "92b4b92541ce4c1abf9d41079d379ed0", "6390eef983714e60afd60a38444770ce", "da86bab2745e41b793a93c3aaea74606", "d409a31cb17143fabe82fffc8684dedb", "<KEY>", "280524895231486786ef9111b83311ec", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "6d21818f01d64c53892ccbef0420afe2", "<KEY>", "<KEY>", "fe6a3a111dce476886cc63760690624d"]} executionInfo={"status": "ok", "timestamp": 1627385285559, "user_tz": 0, "elapsed": 4303, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="201ef53f-b851-4d63-d5f8-d5b48c46130a" dataset=nlp.load_dataset('emotion') # + id="2s0h541FxIgc" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627385304054, "user_tz": 0, "elapsed": 101, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="4ef04992-6830-4ebb-96ad-648d78aa8c03" dataset # + id="z7eCnxU25eiN" train=dataset['train'] val=dataset['validation'] test=dataset['test'] # + id="oDYXMfZy5eiP" def get_tweet(data): tweets=[x['text'] for x in data] labels=[x['label'] for x in data] return tweets,labels # + id="jeq3-vSB5eiR" tweets,labels=get_tweet(train) # + id="bHD3Tk0J5eiU" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627385651462, "user_tz": 0, "elapsed": 106, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="7e103c6d-cd49-435e-9047-305c8b94a475" tweets[0],labels[0] # + [markdown] id="gcAflLv6xIgp" # ## Task 4: Tokenizer # # 1. Tokenizing the tweets # + id="qfX5-ResxIgq" from tensorflow.keras.preprocessing.text import Tokenizer # + id="cckUvwBo5eif" tokenizer =Tokenizer(num_words=10000,oov_token='<UNK>') tokenizer.fit_on_texts(tweets) # + colab={"base_uri": "https://localhost:8080/"} id="2cHsJzVyxtOA" executionInfo={"status": "ok", "timestamp": 1627386258657, "user_tz": 0, "elapsed": 173, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="50b56169-0574-45d3-8e80-d0feae25927f" tokenizer.texts_to_sequences([tweets[0]]) # + [markdown] id="i3Bqm7b2xIgu" # ## Task 5: Padding and Truncating Sequences # # 1. Checking length of the tweets # 2. Creating padded sequences # + id="mLvf_WFZxIgu" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627386719162, "user_tz": 0, "elapsed": 407, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="3a3bb57f-5950-4371-9b21-3d6d97fbbd5c" lengths=[len(t.split(' ')) for t in tweets] plt.hist(lengths,bins=len(set(lengths))) plt.show() # + id="EOi5lIE3xIgx" maxlen=50 from tensorflow.keras.preprocessing.sequence import pad_sequences # + id="Q9J_Iemf5eiq" def get_sequences(tokenizer,tweets): sequences=tokenizer.texts_to_sequences(tweets) padded=pad_sequences(sequences,truncating='post',padding='post',maxlen=maxlen) return padded # + id="eglH77ky5ei0" padded_train_seq=get_sequences(tokenizer,tweets) # + id="iGR473HA5ei7" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627389162958, "user_tz": 0, "elapsed": 189, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="55804008-f107-4c71-8832-f70db50f1cf3" padded_train_seq[0] # + [markdown] id="BURhOX_KxIg8" # ## Task 6: Preparing the Labels # # 1. Creating classes to index and index to classes dictionaries # 2. Converting text labels to numeric labels # + id="SufT2bpD5ejE" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627389576952, "user_tz": 0, "elapsed": 292, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="31651e10-9173-42a8-a437-fb0da7c2f0b7" classes= set(labels) print(classes) # + id="rpwzL88I7YSm" colab={"base_uri": "https://localhost:8080/", "height": 265} executionInfo={"status": "ok", "timestamp": 1627389639163, "user_tz": 0, "elapsed": 105, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="5c4ee0f1-537d-4f6a-e19a-846539b6173f" plt.hist(labels,bins=11) plt.show() # + id="dNLF6rXL5ejN" class_to_index=dict((c,i) for i,c in enumerate(classes)) index_to_class=dict((v,k) for k,v in class_to_index.items()) # + id="_08InVyM5ejc" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627389976359, "user_tz": 0, "elapsed": 104, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="c09ac063-9f09-4ff6-99d7-33bb1b0823e6" class_to_index # + id="gpeDoA6gxIhE" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627389989156, "user_tz": 0, "elapsed": 198, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="8c5d9299-d6a9-467a-c349-dc2b38af8a13" index_to_class # + id="Jq0WJYsP5ejR" names_to_ids = lambda labels:np.array([class_to_index.get(x) for x in labels]) # + id="v15KnrNC5ejW" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627390153867, "user_tz": 0, "elapsed": 114, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="da2a9197-61a0-4d4d-96e3-b3aa205747fb" train_labels = names_to_ids(labels) print(train_labels[0]) # + [markdown] id="c-v0Mnh8xIhP" # ## Task 7: Creating the Model # # 1. Creating the model # 2. Compiling the model # + id="OpewXxPQ5eji" model=tf.keras.models.Sequential([ tf.keras.layers.Embedding(10000,16,input_length=maxlen), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(20,return_sequences=True)), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(20)), tf.keras.layers.Dense(6,activation='softmax') ]) model.compile( loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'] ) # + colab={"base_uri": "https://localhost:8080/"} id="CHMFI0JGFF0b" executionInfo={"status": "ok", "timestamp": 1627391297775, "user_tz": 0, "elapsed": 118, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="08028a15-c5f2-4c91-8a1f-4cbddbffa9ca" model.summary() # + [markdown] id="1HST_CHjxIhR" # ## Task 8: Training the Model # # 1. Preparing a validation set # 2. Training the model # + id="Ff7F3hCK5ejm" val_tweets,val_labels=get_tweet(val) val_seq=get_sequences(tokenizer,val_tweets) val_labels=names_to_ids(val_labels) # + id="hlMKaZ3H5ejr" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627391756859, "user_tz": 0, "elapsed": 207, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="f5cd6870-09ff-4b4e-ccf5-7dccac3bdacd" val_tweets[0],val_labels[0] # + id="bzBqnWQ-5ejw" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627392123770, "user_tz": 0, "elapsed": 158016, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="6d6bbe9b-c332-4933-9f60-2f685eb337df" h=model.fit( padded_train_seq, train_labels, validation_data=(val_seq,val_labels), epochs=20, callbacks=[tf.keras.callbacks.EarlyStopping(monitor='val_accuracy',patience=2)] ) # + [markdown] id="EdsJyMTLxIhX" # ## Task 9: Evaluating the Model # # 1. Visualizing training history # 2. Prepraring a test set # 3. A look at individual predictions on the test set # 4. A look at all predictions on the test set # + id="ENCfvXeLxIhX" colab={"base_uri": "https://localhost:8080/", "height": 392} executionInfo={"status": "ok", "timestamp": 1627392657961, "user_tz": 0, "elapsed": 405, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="9bbf3bb7-9998-44ac-fa78-eb757c4ea955" show_history(h) # + id="kWuzoz8uxIha" test_tweets,test_labels = get_tweet(test) test_seq = get_sequences(tokenizer,test_tweets) test_labels=names_to_ids(test_labels) # + colab={"base_uri": "https://localhost:8080/"} id="04E-BYQ_NEaq" executionInfo={"status": "ok", "timestamp": 1627393429156, "user_tz": 0, "elapsed": 802, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="cfbbe96b-2ba6-4377-a69c-b3348fd6fba9" _ = model.evaluate(test_seq,test_labels) # + id="7vRVJ_2SxIhc" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627393308466, "user_tz": 0, "elapsed": 111, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="42e340d1-8212-4a89-8b04-f8f123f8bd20" i= random.randint(0,len(test_labels)-1) print('Sentence',test_tweets[i]) print('Emotion',index_to_class[test_labels[i]]) p= model.predict(np.expand_dims(test_seq[i],axis=0))[0] pred_class=index_to_class[np.argmax(p).astype('uint8')] print('Predicted Emotion',pred_class) # + id="hHl5SVCFxIhh" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1627393908862, "user_tz": 0, "elapsed": 407, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="114567aa-7250-4b13-cfb4-47674f55435e" preds=model.predict_classes(test_seq) # + id="NC8YQ0OexIhj" colab={"base_uri": "https://localhost:8080/", "height": 472} executionInfo={"status": "ok", "timestamp": 1627393911257, "user_tz": 0, "elapsed": 302, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "13426954169014032881"}} outputId="8f31b474-588e-4689-a4a1-c891046be93a" show_confusion_matrix(test_labels,preds,list(classes))
_Tweet Emotion Recognition .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 statsmodels.formula.api as smf from matplotlib import pyplot as plt from matplotlib.lines import Line2D # %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd plt.style.use('seaborn') # - url = "https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/swiss.csv" df = pd.read_csv(url, index_col=0) df.head() #data wrangling: change column names to be readable and typable df.columns = ['fertility', 'agri', 'exam', 'edu', 'catholic', 'infant_mort'] #this is the model we are going to run formula = 'fertility ~ %s'%(" + ".join(df.columns.values[1:])) formula lin_reg = smf.ols(formula, data=df).fit() lin_reg.summary() lin_reg.params lin_reg.conf_int() err_series = lin_reg.params - lin_reg.conf_int()[0] err_series coef_df = pd.DataFrame({'coef': lin_reg.params.values[1:], 'err': err_series.values[1:], 'varname': err_series.index.values[1:] }) coef_df #basic plot fig, ax = plt.subplots(figsize=(8, 5)) coef_df.plot(x='varname', y='coef', kind='bar', ax=ax, color='none', yerr='err', legend=False) ax.set_ylabel('') ax.set_xlabel('') ax.scatter(x=pd.np.arange(coef_df.shape[0]), marker='s', s=120, y=coef_df['coef'], color='black') ax.axhline(y=0, linestyle='--', color='black', linewidth=4) ax.xaxis.set_ticks_position('none') _ = ax.set_xticklabels(['Agriculture', 'Exam', 'Edu.', 'Catholic', 'Infant Mort.'], rotation=0, fontsize=16) # + #level 2: adding groups fig, ax = plt.subplots(figsize=(8, 5)) coef_df.plot(x='varname', y='coef', kind='bar', ax=ax, color='none', yerr='err', legend=False) ax.set_ylabel('') ax.set_xlabel('') ax.scatter(x=pd.np.arange(coef_df.shape[0]), marker='s', s=120, y=coef_df['coef'], color='black') ax.axhline(y=0, linestyle='--', color='black', linewidth=4) ax.xaxis.set_ticks_position('none') _ = ax.set_xticklabels(['Agriculture', 'Exam', 'Edu.', 'Catholic', 'Infant Mort.'], rotation=0, fontsize=16) fs = 16 ax.annotate('Control', xy=(0.3, -0.2), xytext=(0.3, -0.3), xycoords='axes fraction', textcoords='axes fraction', fontsize=fs, ha='center', va='bottom', bbox=dict(boxstyle='square', fc='white', ec='black'), arrowprops=dict(arrowstyle='-[, widthB=6.5, lengthB=1.2', lw=2.0, color='black')) _ = ax.annotate('Study', xy=(0.8, -0.2), xytext=(0.8, -0.3), xycoords='axes fraction', textcoords='axes fraction', fontsize=fs, ha='center', va='bottom', bbox=dict(boxstyle='square', fc='white', ec='black'), arrowprops=dict(arrowstyle='-[, widthB=3.5, lengthB=1.2', lw=2.0, color='black')) # - #level 3: multiple models and model comparisons formula_1 = 'fertility ~ %s'%(" + ".join(df.columns.values[1:-1])) print(formula_1) mod_1 = smf.ols(formula_1, data=df).fit() mod_1.params formula_2 = 'fertility ~ %s'%(" + ".join(df.columns.values[1:-2].tolist() + ['infant_mort'])) print(formula_2) mod_2 = smf.ols(formula_2, data=df).fit() mod_2.params coef_df = pd.DataFrame() for i, mod in enumerate([mod_1, mod_2]): err_series = mod.params - mod.conf_int()[0] coef_df = coef_df.append(pd.DataFrame({'coef': mod.params.values[1:], 'err': err_series.values[1:], 'varname': err_series.index.values[1:], 'model': 'model %d'%(i+1) }) ) coef_df ## marker to use marker_list = 'so' width=0.25 ## 5 covariates in total base_x = pd.np.arange(5) - 0.2 base_x # + fig, ax = plt.subplots(figsize=(8, 5)) for i, mod in enumerate(coef_df.model.unique()): mod_df = coef_df[coef_df.model == mod] mod_df = mod_df.set_index('varname').reindex(coef_df['varname'].unique()) ## offset x posistions X = base_x + width*i ax.bar(X, mod_df['coef'], color='none',yerr=mod_df['err']) ## remove axis labels ax.set_ylabel('') ax.set_xlabel('') ax.scatter(x=X, marker=marker_list[i], s=120, y=mod_df['coef'], color='black') ax.axhline(y=0, linestyle='--', color='black', linewidth=4) ax.xaxis.set_ticks_position('none') _ = ax.set_xticklabels(['', 'Agriculture', 'Exam', 'Edu.', 'Catholic', 'Infant Mort.'], rotation=0, fontsize=16) fs = 16 ax.annotate('Control', xy=(0.3, -0.2), xytext=(0.3, -0.35), xycoords='axes fraction', textcoords='axes fraction', fontsize=fs, ha='center', va='bottom', bbox=dict(boxstyle='square', fc='white', ec='black'), arrowprops=dict(arrowstyle='-[, widthB=6.5, lengthB=1.2', lw=2.0, color='black')) ax.annotate('Study', xy=(0.8, -0.2), xytext=(0.8, -0.35), xycoords='axes fraction', textcoords='axes fraction', fontsize=fs, ha='center', va='bottom', bbox=dict(boxstyle='square', fc='white', ec='black'), arrowprops=dict(arrowstyle='-[, widthB=3.5, lengthB=1.2', lw=2.0, color='black')) ## finally, build customized legend legend_elements = [Line2D([0], [0], marker=m, label='Model %d'%i, color = 'k', markersize=10) for i, m in enumerate(marker_list) ] _ = ax.legend(handles=legend_elements, loc=2, prop={'size': 15}, labelspacing=1.2) # + #boxplots and fixing them # fake data: a = pd.DataFrame({ 'group' : np.repeat('A',500), 'value': np.random.normal(10, 5, 500) }) b = pd.DataFrame({ 'group' : np.repeat('B',500), 'value': np.random.normal(13, 1.2, 500) }) c = pd.DataFrame({ 'group' : np.repeat('B',500), 'value': np.random.normal(18, 1.2, 500) }) d = pd.DataFrame({ 'group' : np.repeat('C',20), 'value': np.random.normal(25, 4, 20) }) e = pd.DataFrame({ 'group' : np.repeat('D',100), 'value': np.random.uniform(12, size=100) }) df=a.append(b).append(c).append(d).append(e) # Usual boxplot sns.boxplot(x='group', y='value', data=df) # - #correction: adding jitter ax = sns.boxplot(x='group', y='value', data=df) ax = sns.stripplot(x='group', y='value', data=df, color="orange", jitter=0.2, size=2.5) plt.title("Boxplot with jitter", loc="left") #correction: building violin plots sns.violinplot( x='group', y='value', data=df) plt.title("Violin plot", loc="left") # + #avoiding clutter and overplotting # libraries and data import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd plt.style.use('seaborn') # Dataset: df=pd.DataFrame({'x': np.random.normal(10, 1.2, 20000), 'y': np.random.normal(10, 1.2, 20000), 'group': np.repeat('A',20000) }) tmp1=pd.DataFrame({'x': np.random.normal(14.5, 1.2, 20000), 'y': np.random.normal(14.5, 1.2, 20000), 'group': np.repeat('B',20000) }) tmp2=pd.DataFrame({'x': np.random.normal(9.5, 1.5, 20000), 'y': np.random.normal(15.5, 1.5, 20000), 'group': np.repeat('C',20000) }) df=df.append(tmp1).append(tmp2) # plot plt.plot( 'x', 'y', data=df, linestyle='', marker='o') plt.xlabel('Value of X') plt.ylabel('Value of Y') plt.title('Overplotting looks like that:', loc='left') # + #correction: change dot size # Plot with small marker size plt.plot( 'x', 'y', data=df, linestyle='', marker='o', markersize=0.7) plt.xlabel('Value of X') plt.ylabel('Value of Y') plt.title('Overplotting? Try to reduce the dot size', loc='left') # + #correction: change transparency # Plot with transparency plt.plot( 'x', 'y', data=df, linestyle='', marker='o', markersize=3, alpha=0.05, color="purple") # Titles plt.xlabel('Value of X') plt.ylabel('Value of Y') plt.title('Overplotting? Try to use transparency', loc='left') # + #correction:Adding density # 2D density plot: sns.kdeplot(df.x, df.y, cmap="Reds", shade=True) plt.title('Overplotting? Try 2D density graph', loc='left') # + #correction: random sampling # Sample 1000 random lines df_sample=df.sample(1000) # Make the plot with this subset plt.plot( 'x', 'y', data=df_sample, linestyle='', marker='o') # titles plt.xlabel('Value of X') plt.ylabel('Value of Y') plt.title('Overplotting? Sample your data', loc='left') # -
nov13-15-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 # --- # # van der Pol方程式(Hopf分岐) # $$ # \left\{ # \begin{aligned} # \dot{x} &= a \left( y + x - \frac{x^3}{3}\right),\\ # \dot{z} &= -x - by # \end{aligned} # \right. # $$ # van der Pol方程式のリミットサイクルに対するHopf分岐による説明 import numpy as np from scipy.integrate import solve_ivp import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline sns.set('poster', 'whitegrid', 'dark', rc={"lines.linewidth": 2, 'grid.linestyle': '--'}) def vdp(t, x, a, b): return [a*(x[1]+x[0]-x[0]**3/3), -x[0] - b*x[1]] b = 0.5 t0 = 0.0 # $b = 0.5$を固定し,$a$をいろいろ変える # $a = 0.45$ t1 = 150.0 N = 15000 tt = np.linspace(t0,t1,N) x0 = [0.0, 2.0] a = 0.45 s0 = solve_ivp(vdp, [t0, t1], x0, t_eval=tt,args=([a,b])) fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(111) ax.set_xlabel("$x$") ax.set_ylabel("$y$") ax.set_xlim(-2,2) ax.set_ylim(-2,2) ax.plot(s0.y[0], s0.y[1], '-', color='grey') # plt.savefig("hopf045.pdf", bbox_inches='tight') # $a = 0.5$ a = 0.5 s1 = solve_ivp(vdp, [t0, t1], x0, t_eval=tt,args=([a,b])) fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(111) ax.set_xlabel("$x$") ax.set_ylabel("$y$") ax.set_xlim(-2,2) ax.set_ylim(-2,2) ax.plot(s1.y[0], s1.y[1], '-', color='grey') # plt.savefig("hopf050.pdf", bbox_inches='tight') # $a = 0.55$ a = 0.55 s2 = solve_ivp(vdp, [t0, t1], x0, t_eval=tt,args=([a,b])) s22 = solve_ivp(vdp, [t0, t1], [0.0,0.1], t_eval=tt,args=([a,b])) fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(111) ax.set_xlabel("$x$") ax.set_ylabel("$y$") ax.set_xlim(-2,2) ax.set_ylim(-2,2) ax.plot(s2.y[0], s2.y[1], '-', color='darkgrey') ax.plot(s22.y[0][:5*N//8], s22.y[1][:5*N//8], '-', color='darkgrey') ax.plot(s2.y[0][-N//10:], s2.y[1][-N//10:], '-k') # plt.savefig("hopf055.pdf", bbox_inches='tight') # $a = 0.6$ a = 0.6 s3 = solve_ivp(vdp, [t0, t1], x0, t_eval=tt,args=([a,b])) s32 = solve_ivp(vdp, [t0, t1], [0.0,0.1], t_eval=tt,args=([a,b])) fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(111) ax.set_xlabel("$x$") ax.set_ylabel("$y$") ax.set_xlim(-2,2) ax.set_ylim(-2,2) ax.plot(s3.y[0], s3.y[1], '-', color='grey') ax.plot(s32.y[0][:5*N//8], s32.y[1][:5*N//8], '-', color='darkgrey') ax.plot(s3.y[0][-N//10:], s3.y[1][-N//10:], '-k') # plt.savefig("hopf060.pdf", bbox_inches='tight')
notebooks/oscillation/HopfBifurcation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: UDaCT # language: python # name: udact # --- # + import numpy as np import pandas as pd import matplotlib from matplotlib import pyplot as plt # - # <div class="alert alert-success" role="alert"> # <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> # <i class="fa fa-question-circle" style="font-size:22px;color:green"></i> <strong><u> Model: </u></strong> <br/> # <hr> # $$ weight1 * x_1 + weight2 * x_2 + bias = 0$$<br/> # <b><u>Such that:</u></b><br/> # * if ... > 0 => positive class (True) <br/> # * if ... < 0 => negative class (False)<br/> # </div> # <div class="alert alert-block alert-info"> # <b> Task:</b> # <hr> # # In this quiz, you'll set <br/> # # the weights: weight1, weight2 # the bias: bias # # to the values that calculate the <u><b>NOT</b></u> operation on the second input and ignores the first input. # # <div/> # DON'T CHANGE ANYTHING BELOW # Inputs and outputs test_inputs = [(0, 0), (0, 1), (1, 0), (1, 1)] correct_outputs = [True, False, True, False] # TODO: Set weight1, weight2, and bias weight1 = 0 weight2 = -1 bias = .5 def line(x, w1, w2, b): return list(map(lambda elem: (-b - elem * w1) / w2, x)) x1, x2 = zip(*test_inputs) x = np.arange(-0.1, 1.3, 0.1) y = line(x, weight1, weight2, bias) # + matplotlib.rc('axes',edgecolor='lightgray') plt.plot(x, y, "-", color="red", label="boundary") t1 = plt.Polygon(np.array([[x[0], y[0]], [x[0], 1.2], [x[-1], 1.2], [x[-1], y[0]]]), color="blue", alpha=0.2, hatch="/", label="negative class") t2 = plt.Polygon(np.array([[x[0], y[0]], [x[0], -.1], [x[-1], -.1], [x[-1], y[0]]]), color="red", alpha=0.2, hatch="\\", label="positive class") plt.gca().add_patch(t1) plt.gca().add_patch(t2) plt.scatter(x1, x2, color="darkgreen", alpha=1) plt.ylabel('y') plt.xlabel('x') plt.title("Perceptron for NO function", fontdict={"size":20}) plt.grid(alpha=0.3) plt.legend(loc='upper right', bbox_to_anchor=(1.4,1.)) plt.show() # - outputs = [] # Generate and check output for test_input, correct_output in zip(test_inputs, correct_outputs): linear_combination = weight1 * test_input[0] + weight2 * test_input[1] + bias output = int(linear_combination >= 0) is_correct_string = 'Yes' if output == correct_output else 'No' outputs.append([test_input[0], test_input[1], linear_combination, output, is_correct_string]) # Print output num_wrong = len([output[4] for output in outputs if output[4] == 'No']) output_frame = pd.DataFrame(outputs, columns=['Input 1', ' Input 2', ' Linear Combination', ' Activation Output', ' Is Correct']) if not num_wrong: print('Nice! You got it all correct.\n') else: print('You got {} wrong. Keep trying!\n'.format(num_wrong)) print(output_frame.to_string(index=False))
notebooks/NOT_perceptron.ipynb
# --- # jupyter: # jupytext: # split_at_heading: true # 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 # --- #hide # !pip install -Uqq fastbook import fastbook fastbook.setup_book() #hide from fastbook import * # # Training a State-of-the-Art Model # ## Imagenette from fastai.vision.all import * path = untar_data(URLs.IMAGENETTE) dblock = DataBlock(blocks=(ImageBlock(), CategoryBlock()), get_items=get_image_files, get_y=parent_label, item_tfms=Resize(460), batch_tfms=aug_transforms(size=224, min_scale=0.75)) dls = dblock.dataloaders(path, bs=64) model = xresnet50(n_out=dls.c) learn = Learner(dls, model, loss_func=CrossEntropyLossFlat(), metrics=accuracy) learn.fit_one_cycle(5, 3e-3) # ## Normalization x,y = dls.one_batch() x.mean(dim=[0,2,3]),x.std(dim=[0,2,3]) def get_dls(bs, size): dblock = DataBlock(blocks=(ImageBlock, CategoryBlock), get_items=get_image_files, get_y=parent_label, item_tfms=Resize(460), batch_tfms=[*aug_transforms(size=size, min_scale=0.75), Normalize.from_stats(*imagenet_stats)]) return dblock.dataloaders(path, bs=bs) dls = get_dls(64, 224) x,y = dls.one_batch() x.mean(dim=[0,2,3]),x.std(dim=[0,2,3]) model = xresnet50(n_out=dls.c) learn = Learner(dls, model, loss_func=CrossEntropyLossFlat(), metrics=accuracy) learn.fit_one_cycle(5, 3e-3) # ## Progressive Resizing dls = get_dls(128, 128) learn = Learner(dls, xresnet50(n_out=dls.c), loss_func=CrossEntropyLossFlat(), metrics=accuracy) learn.fit_one_cycle(4, 3e-3) learn.dls = get_dls(64, 224) learn.fine_tune(5, 1e-3) # ## Test Time Augmentation preds,targs = learn.tta() accuracy(preds, targs).item() # ## Mixup # ### Sidebar: Papers and Math # ### End sidebar # + church = PILImage.create(get_image_files_sorted(path/'train'/'n03028079')[0]) gas = PILImage.create(get_image_files_sorted(path/'train'/'n03425413')[0]) church = church.resize((256,256)) gas = gas.resize((256,256)) tchurch = tensor(church).float() / 255. tgas = tensor(gas).float() / 255. _,axs = plt.subplots(1, 3, figsize=(12,4)) show_image(tchurch, ax=axs[0]); show_image(tgas, ax=axs[1]); show_image((0.3*tchurch + 0.7*tgas), ax=axs[2]); # - # ## Label Smoothing # ### Sidebar: Label Smoothing, the Paper # ### End sidebar # ## Conclusion # ## Questionnaire # 1. What is the difference between ImageNet and Imagenette? When is it better to experiment on one versus the other? # 1. What is normalization? # 1. Why didn't we have to care about normalization when using a pretrained model? # 1. What is progressive resizing? # 1. Implement progressive resizing in your own project. Did it help? # 1. What is test time augmentation? How do you use it in fastai? # 1. Is using TTA at inference slower or faster than regular inference? Why? # 1. What is Mixup? How do you use it in fastai? # 1. Why does Mixup prevent the model from being too confident? # 1. Why does training with Mixup for five epochs end up worse than training without Mixup? # 1. What is the idea behind label smoothing? # 1. What problems in your data can label smoothing help with? # 1. When using label smoothing with five categories, what is the target associated with the index 1? # 1. What is the first step to take when you want to prototype quick experiments on a new dataset? # ### Further Research # # 1. Use the fastai documentation to build a function that crops an image to a square in each of the four corners, then implement a TTA method that averages the predictions on a center crop and those four crops. Did it help? Is it better than the TTA method of fastai? # 1. Find the Mixup paper on arXiv and read it. Pick one or two more recent articles introducing variants of Mixup and read them, then try to implement them on your problem. # 1. Find the script training Imagenette using Mixup and use it as an example to build a script for a long training on your own project. Execute it and see if it helps. # 1. Read the sidebar "Label Smoothing, the Paper", look at the relevant section of the original paper and see if you can follow it. Don't be afraid to ask for help!
fastbook/clean/07_sizing_and_tta.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 Overlay # 导入Overlay # + from pp4fpgas import CordicOverlay overlay = CordicOverlay() # - # # Register level driver # 直接读写寄存器来使用overlay中的hls ip theta = 0b010000000000 overlay.cordic_0.write(0x10, theta) overlay.cordic_0.read(0x20) # # Learn something about this overlay # 了解overlay相关的api,从中获取该overlay包含的信息 overlay.ip_dict overlay.gpio_dict overlay.clock_dict overlay.bitfile_name overlay.hierarchy_dict help(overlay) # # Write a driver for hls ip # 给hls ip写一个上层驱动 # + from pynq import DefaultIP class cordicDriver(DefaultIP): def __init__(self, description): super().__init__(description=description) bindto = ['xilinx.com:hls:cordic:1.0'] def calc(self, theta): self.write(0x10, theta) return self.read(0x20) # - cordic = CordicOverlay() cordic.cordic_0.calc(0b010000000000)
boards/Pynq-Z1/notebooks/01-CORDIC.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 # --- # + tags=[] import numpy as np from tqdm import tqdm # - # # Load Citeseer Dataset # + tags=[] from graphgallery.datasets import Planetoid data = Planetoid('citeseer', root="~/GraphData/datasets/", verbose=False) graph = data.graph splits = data.split_nodes() # - # # TensorFlow Backend from graphgallery import set_backend set_backend('tensorflow') # + from graphgallery.gallery import GCN accs = [] for seed in tqdm(range(10)): trainer = GCN(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=100) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # + from graphgallery.gallery import SGC accs = [] for seed in tqdm(range(10)): trainer = SGC(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=100) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # + from graphgallery.gallery import GAT accs = [] for seed in tqdm(range(10)): trainer = GAT(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=200) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # - # # PyTorch Backend from graphgallery import set_backend set_backend('pytorch') # + from graphgallery.gallery import GCN accs = [] for seed in tqdm(range(10)): trainer = GCN(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=200) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # + from graphgallery.gallery import SGC accs = [] for seed in tqdm(range(10)): trainer = SGC(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=100) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # + from graphgallery.gallery import GAT accs = [] for seed in tqdm(range(10)): trainer = GAT(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=200) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # - # # PyG Backend from graphgallery import set_backend set_backend('pyg') import graphgallery as gg gg.backend("DGL") # + from graphgallery.gallery import GCN accs = [] for seed in tqdm(range(10)): trainer = GCN(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=200) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # + from graphgallery.gallery import SGC accs = [] for seed in tqdm(range(10)): trainer = SGC(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=200) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # + from graphgallery.gallery import GAT accs = [] for seed in tqdm(range(10)): trainer = GAT(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=200) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # - # # DGL (PyTorch) Backend from graphgallery import set_backend set_backend('dgl') # + from graphgallery.gallery import GCN accs = [] for seed in tqdm(range(10)): trainer = GCN(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=200) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # + from graphgallery.gallery import SGC accs = [] for seed in tqdm(range(10)): trainer = SGC(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=100) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}") # + from graphgallery.gallery import GAT accs = [] for seed in tqdm(range(10)): trainer = GAT(graph, device="gpu", seed=42+seed).process(attr_transform="normalize_attr").build() his = trainer.train(splits.train_nodes, splits.val_nodes, verbose=0, epochs=200) results = trainer.test(splits.test_nodes, verbose=0) accs.append(results.accuracy) print(f"Final results: {np.mean(accs):.2%}±{np.std(accs):.2%}")
benchmark/Planetoid/Citeseer.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/Rishit-dagli/Deep-Learning-With-TensorFlow-Blog-series/blob/master/Part%203-Using%20Convolutional%20Neural%20Networks%20with%20TensorFlow/Excercise2_question.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="I5tcbh0IWTmQ" colab_type="text" # # You learned how to do classificaiton using Fashion MNIST, a data set containing items of clothing. There's another, similar dataset called MNIST which has items of handwriting - the digits 0 through 9. # Write an MNIST classifier that trains to 99% accuracy or above, and does it without a fixed number of epochs - i.e. you should stop training once you reach that level of accuracy. # # Some notes: # # 1. It should succeed in less than 10 epochs, so it is okay to change epochs = to 10, but nothing larger # 2. When it reaches 99% or greater it should print out the string "Reached 99% accuracy so cancelling training!" # # Use this code line to get MNIST handwriting data set: # # ``` # mnist = tf.keras.datasets.mnist # ``` # # # + id="aXwpXnljWIji" colab_type="code" colab={} # YOUR CODE SHOULD START HERE # YOUR CODE SHOULD END HERE import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() # YOUR CODE SHOULD START HERE # YOUR CODE SHOULD END HERE model = tf.keras.models.Sequential([ # YOUR CODE SHOULD START HERE # YOUR CODE SHOULD END HERE ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # YOUR CODE SHOULD START HERE # YOUR CODE SHOULD END HERE
Part 4-Extending what Convolutional Neural Nets can do/Excercise2_question.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 # --- # # Pre-computing various second-moment related quantities # # This saves computation for M&M by precomputing and re-using quantitaties shared between iterations. It mostly saves $O(R^3)$ computations. This vignette shows results agree with the original version. Cannot use unit test due to numerical discrepency between `chol` of amardillo and R -- this has been shown problematic for some computations. I'll have to improve `mashr` for it. muffled_chol = function(x, ...) withCallingHandlers(chol(x, ...), warning = function(w) { if (grepl("the matrix is either rank-deficient or indefinite", w$message)) invokeRestart("muffleWarning") } ) set.seed(1) library(mashr) simdata = simple_sims(500,5,1) data = mash_set_data(simdata$Bhat, simdata$Shat, alpha = 0) U.c = cov_canonical(data) grid = mashr:::autoselect_grid(data,sqrt(2)) Ulist = mashr:::normalize_Ulist(U.c) xUlist = expand_cov(Ulist,grid,TRUE) llik_mat0 = mashr:::calc_lik_rcpp(t(data$Bhat),t(data$Shat),data$V, matrix(0,0,0), simplify2array(xUlist),T,T)$data svs = data$Shat[1,] * t(data$V * data$Shat[1,]) sigma_rooti = list() for (i in 1:length(xUlist)) sigma_rooti[[i]] = t(backsolve(muffled_chol(svs + xUlist[[i]], pivot=T), diag(nrow(svs)))) llik_mat = mashr:::calc_lik_common_rcpp(t(data$Bhat), simplify2array(sigma_rooti), T)$data head(llik_mat0) head(llik_mat) rows <- which(apply(llik_mat,2,function (x) any(is.infinite(x)))) if (length(rows) > 0) warning(paste("Some mixture components result in non-finite likelihoods,", "either\n","due to numerical underflow/overflow,", "or due to invalid covariance matrices", paste(rows,collapse=", "), "\n")) loglik_null = llik_mat[,1] lfactors = apply(llik_mat,1,max) llik_mat = llik_mat - lfactors mixture_posterior_weights = mashr:::compute_posterior_weights(1/ncol(llik_mat), exp(llik_mat)) post0 = mashr:::calc_post_rcpp(t(data$Bhat), t(data$Shat), matrix(0,0,0), matrix(0,0,0), data$V, matrix(0,0,0), matrix(0,0,0), simplify2array(xUlist), t(mixture_posterior_weights), T, 4) Vinv = solve(svs) U0 = list() for (i in 1:length(xUlist)) U0[[i]] = xUlist[[i]] %*% solve(Vinv %*% xUlist[[i]] + diag(nrow(xUlist[[i]]))) post = mashr:::calc_post_precision_rcpp(t(data$Bhat), t(data$Shat), matrix(0,0,0), matrix(0,0,0), data$V, matrix(0,0,0), matrix(0,0,0), Vinv, simplify2array(U0), t(mixture_posterior_weights), 4) head(post$post_mean) head(post0$post_mean) head(post$post_cov) head(post0$post_cov) # Now test the relevant `mvsusieR` interface: simulate_multivariate = function(n=100,p=100,r=2) { set.seed(1) res = mvsusieR::mvsusie_sim1(n,p,r,4,center_scale=TRUE) res$L = 10 return(res) } attach(simulate_multivariate(r=2)) prior_var = V[1,1] residual_var = as.numeric(var(y)) data = mvsusieR:::DenseData$new(X,y) A = mvsusieR:::BayesianSimpleRegression$new(ncol(X), residual_var, prior_var) A$fit(data, save_summary_stats = T) null_weight = 0 mash_init = mvsusieR:::MashInitializer$new(list(V), 1, 1 - null_weight, null_weight) residual_covar = cov(y) mash_init$precompute_cov_matrices(data, residual_covar) B = mvsusieR:::MashRegression$new(ncol(X), residual_covar, mash_init) B$fit(data, save_summary_stats = T)
inst/prototypes/precomputed_quantities_mash.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/kyriell2/Numerical-Methods/blob/main/operations_and_Expressions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="Ew3JbLKIJ-AM" # ##Boolean Operators # + colab={"base_uri": "https://localhost:8080/"} id="kIHnJ_-kKAw7" outputId="8a0e46cd-90cc-46e3-bebf-702d1d28ca34" print(10>9) print(10<9) # + [markdown] id="JKHShmVONl69" # ##Bool Function # + colab={"base_uri": "https://localhost:8080/"} id="2ESDCCHlNopW" outputId="9e968294-70bb-4d4a-f05a-5773a8d6b602" print(bool("Hello")) print(bool(15)) print(bool(0)) print(bool(1)) print(bool(None)) print(bool([])) # + [markdown] id="oyukipiAOzZc" # ##Functions can return a Boolean # + colab={"base_uri": "https://localhost:8080/"} id="bkGIJjEqKnxt" outputId="0c18aca1-4e91-4064-89b4-87b4a227fef3" def myFunction(): return False print(myFunction()) # + colab={"base_uri": "https://localhost:8080/"} id="B2WzS2zxMmZQ" outputId="24bb12da-848c-4e27-e861-b941e80978dd" if myFunction(): print("yes") else: print("no") # + [markdown] id="2cNrwBivMxhe" # ##Application 1 # + colab={"base_uri": "https://localhost:8080/"} id="40IKw8gfM0CO" outputId="71f0d28a-bc7e-4ef9-84f1-e1f3ecab6e79" print (10<9) a=6 b=7 print(a==b) print(a!=a) # + [markdown] id="BT-NQ3RjOh87" # ##Python Operators # + colab={"base_uri": "https://localhost:8080/"} id="hBt93pFmOj3q" outputId="9a95e850-c930-4fde-9569-62de7c99d45d" print(10+9) print(10-9) print(10*9) print(10/9) print(10**9) # + [markdown] id="jVXgD7R4Pggp" # ##Python Bitwise Operators # + colab={"base_uri": "https://localhost:8080/"} id="lTAEUZDiPjY9" outputId="cdbdb0bc-4818-447d-cc98-e8ad911d8d7c" a = 60 b = 13 print(a&b) print(a|b) # + [markdown] id="ltmpaf4zQM1Z" # ##Python Assignment Operators # + colab={"base_uri": "https://localhost:8080/"} id="7OHLgdVOQO0P" outputId="4aa640b1-2593-4cbd-febd-d835e4cf66db" a+=3 print(a) # + [markdown] id="etH2DaHrREDW" # ##Logical operators # + colab={"base_uri": "https://localhost:8080/"} id="TnXXBahRRFmz" outputId="c5a63c8b-ebea-4257-a9af-da2a8f3c9e2f" a = True b = False print(a and b) print(not(a or b)) # + [markdown] id="6S6vKF68RoCL" # ##Identity Operators # + colab={"base_uri": "https://localhost:8080/"} id="CVS9ACjERqsk" outputId="73d4537c-4229-4202-910c-ca78f0795ee4" print(a is b) print(a is not b)
operations_and_Expressions.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/HenriqueCCdA/ElementosFinitosCurso/blob/main/notebooks/Elemento_finitos_Exercicios_ex1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="ccSP9ejpOgm5" import numpy as np from scipy.linalg import lu_factor, lu_solve import matplotlib.pyplot as plt import matplotlib as mpl # + [markdown] id="1X0wvV5nos5P" # # Paramentros de entrada # + id="ftorWfJfP85k" f = -2 dudx_0 = -2 u3 = 0.0 # + [markdown] id="yE9UpnI8YcFS" # ![Capture.PNG](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAcwAAADXCAYAAACXvWFqAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAACE2SURBVHhe7d17bB3VnQfwopZuVy1qVtWq/1AVLdIWqarKVrtbVapa+gctXYQUqHgEtigNLRRoA6wLlE2KaRpawoaGJg0kEOImwSEJkIQE3BBDDHm/Yzt+xY5fcezYseP3K3bs397vcCYZ31xfz7135szMud+PNIp97Iju3cn93t+cc37nU0JERERTYmASERG5wMAkIiJygYFJRETkAgOTiIjIBQYmERGRCwxMIiIiFxiYRERELjAwiYiIXGBgEhERucDAJCIicoGBSURE5AIDk4iIyAUGJhERkQsMTCIiIhcYmERERC4wMImIiFxgYBIREbnAwCQiInKBgUlEROQCA5OIiMgFBiYREZELDEwiIiIXGJhEREQuMDCJiMgzw0c2ybnf/Zt19W+ep0Yn6nr+h9YVNQxMIgNUdu6QxcXTrWtH08tqdKKV5T+3LiI/OQMT12jDMfWTSxiYRBQYZ2DiOjNwQv3kEgYm6WAHZs+yey7+GY+BSUSBsQNzQ/UTF/+Mx8AkHezAxONYOzQx5sTAJKLA2IGJx7F2aGLMiYFJOjgDE49jE1WZDEwiCowzMPE4NlGVycAkHZyBCb2vP2J9P/jhpbl1BiYRBcYZmPBu/Z+s7w+0rre+BwYm6RAfmIDvnQGZKDDtYI3/3TBhYMbZVnZO7nm13LqW7jitRid66PUT1kUUFvGBCfjeGZCJAtMO1vjfJUpXosDE186x+MDE30Fg2vAI1/l9WDAw4zgDE9fx0/3qJ5cwMClsEgUmvnaOxQcm/g4C04ZHuM7vidKRKDABAYlx++tkVST+bqLVtUFjYMaxA/O3b5+8+Gc8BiaFTaLABAQkxu2vk1WR+LuJVtcSpWKywMQcpj0+VWCiumSFGQF2YOJxrB2aGHNiYFLYTBaYmMO0x6cKTFSXrDApU5MFJtjbTJIFpr2yNlHDg6AxMOM4AxOPYxNVmQxMCpvJAhPsbSbJAtNeWZuo4QFRKpIFpv0zOzQTwbhzRW2YMDDjOAMT/vheg/X96/tbre+BgUlhkyww7Z/ZoZkIxp0raonSlSwwwV4Nm2iOEmE52d9zGj76jgztfV19pw8DM058YAK+dwbkZIFph2v8I1wivyULTLBXwyaao0RYTvb3iHRxE5ajLVXSt/Z/pHflL6yvdWNgxkkUmPjaOZYoMPFzVKEMTIoShiWFgb0gKP6y5zHHh3ploGChdL1ws1VZ4vsgGBuYzzzzjPXn6vdPyYaixPspE0kUmICAxLj9daIKExiYpFPFuQ/lrkd+IIfb3lYj7tkLguIvzmNSmIzUHZKel+6yqsqxrmY1KrJo0SLp6upS3+lhbGB+6lOf/J/W2Dooc2IhlrP0uFSdmvpTyWSBaVePGGdgUtDODtZZj1nfPjnXutcLGhbI+urfyKneYvUbRNHmrCoxZxlv2rRpDEyv2IFp27KnRW55ap+s2taoRhKbLDDB3mbCwKSgDF/ol53Nr8nfKu6XY2e3WN/b9/qJro8lr/znUtS0zBoniipUlQjK/o25kz5+ZWB66Nixy/fwtHUOy/zVVfLQomIpPtmtRidKFpj2z+zQTISBSX5p6jsub5x4zKoqe863qdGJ9/ro2HnZefo1WVE2U8rPfaBGiaLBrirxCPZ8xcTTduIleo/3m7GBmUzh4bNyR+5BWb6lXsbHx9XoJ5IFJtgrYRN1AAIGJnktvqp0o7m/XN6qeUq21s2XjqEGNUoUXvZcJQIzqEU9UzEyMFGm33DDDeq7xHoHRmXhumqZteCo7Cv3LuAYmOQlVJUIysJTiyd9zHr99derry537Ow78lLpHXKgdZ0aIQoXhCO2iiAsU9kqgvd4PpL1AF5EPN92Y1dJh9z77GF58c2TMjh8QY2mxu4IFH8latxO5IZdVeIRbG33fjWaWPx8fbzekbOyreEFWXviUanvOaRGiYKHxTzpbhXhHKZH8CIm+9Qdb2R0TJZuqpUZ8w5J0bF2NUoUDHuuEoHpZvHONddco75KrqZrj6yufFA+OLVEBkcTz+ET6YBKEttEMmlAgPd4BmaADld1yQMLj8lza6vlXO95NUqkB8IRW0UQltg24ofx8THZ07Jalh+/R453bFOjRHrYi3qCbkCQLmMrzEw+eawsaJTpc/ZLgaN/LJGf0IDAuVUkFfX19eor91oHqmVT7dOyuTZX2gZq1CiRfyZrQJCudO77TBkZmHgh3T6mmkxZXY/MXlwiuXmV0twxpEaJvOVsQJBuVTnVHGYypR0Fsqx0huxtWaNGiLzlrCoTNSBIF97jdYcmA3MK+R80yU2P75GNO1vUCFHm7EU96VaVTpkEJgyMdklh42JZU/mwnOzep0aJMuemAUG6GJgeweNY9Bn0Sm1zvzy5vCx2lcvJ2NdEmZisAUG67L7JmarrOSj5VbPl/YY/S98IF79R+uyq0k0DgnSxl2zIocpEtZlf2KRGiNyLryrDav+ZtfJy6Z1S3L5VjRC5h4BEVTm4Y1nkFvVMxdhHsnl5eeo7b51uH7TmNR9ZXCLl9WbdDOQfuwEBqspMHr8m4lWF6dQ+VC9b6v4Q+987R1r6K9Qo0eR0n1XJCtMj6DGYyj7MdGAF7a1z91sraokm46wqp2pAkK5M5zCTKevYLq+W3Su7mlfKhbERNUp0CapIbBHRvVUE7/G6+8kaGZhFRUVTtsbzAvZqYs/m/f931NrDSeRkz1Uma2vnBT8DE4ZG+6xDpvNioV/dtUuNEn1SVdpbRXRUlU4MTA/pfCHRHWjGvINWt6DRCxObuVP2QTgiJBGWCE2/6brXG3uPybrqHCloeF66h7lqPJvZi3rsqjIImHrjI9mIGhi+YPWjRV/a3aVsvp6tMmlAEBWH2t6UJSW3yZG2jWqEsonXDQiixMjA3LRpky8LIdzAySc4AQUnoeBEFMoOXjQgSJff8/WJdA6flnfr/iTrq5+IVdGlapRM5qwqvWxAkK7p06dzH6YXEJh4MYOCIzZx1ubtuQek8HDm++wovJyLeoKqKv2ew0ymsrNIVpbfJ0VNy2VkbFCNkmn8bECQLs5hegSLfmbOnKm+C07xyW55aFGxzF9dJW2dw2qUTOF1A4J0edXVKl0jY0Py8ekV8lr5rFiA+rNJnYKBcERI+tmAIF0oihiYBlq1rVFueWqfbNnDhRImiK8q6ROn+8vkzZrfyta6P8q5IW63irpMzqo0lZGBiZVTuldPTaXqVJ/kLD0uc14tl8ZWPrqKKmcDgiCrSifd8zhTOXp2s/y15CdyoHW9GqEo0d2AIF1B3PdGBia6/IThkWwiG4pOy405u60/KTrsqhLnSPrVgCBdQc5hTqZ7uFX+3rBQ1p54TBp6j6pRCjNUkUE0IEgX9tpj+k0nBmYAUGHOXVFhVZxVjXzUEXZ2Vel3A4J0hTEwbdVdu2VV5S/lw6alMjTao0YpbIJsQJAuBqZHMBGMlbJhhzlNzG1ijpPCB+FoNyAIW1XpFNQWKrfGxi/I7pa/yStlP5XjHe+rUQoDVJFBNyBIFwojbivJMlg9i1W0WE2LVbUUDtnQgEC3MwMn5O2aubK59vfSNlirRiko2dyAIF1GBibKdN2leqYKD5+VO3IPWvs3sY+TghFkA4J0hb3CjFfc/q68XHqX7G2JVkVjCmdVGYYGBOlihekRHPvy6KOPqu+iA52BXlhfY3UKQscg0id+q0iUqsowz2FOpm+kQ7Y3vihrKn8ltT0H1Cj5LYwNCNLFOUyPRDUwbbtKOqyetOhNOzh8QY2SX8LSgCBdUQxMG8Ly9apfx8LzL1aIkj8QjmFtQJAuBqZHsAczbHvTUjUyOmadfjJj3iHrNBTyXnxVGVW6u534Yd+ZfOsxLR7XkrdMbUAQxPu8kYFpEpyz+cDCY9a5mzh/k7wR9arSRG0DtdaCIPz/pKU/GlsbwiwqDQiixNhHspgQNsnKgka5de5+KdjfqkYoHXZVGcYGBOkK4rQSP2HrCbagYCsKtqRQalBFDu5YZmRV6YS99uwl6wHMXyI0TVNW1yOzF5dIbl6lNHcMqVFyK+wNCNIV5TnMyQyO9ljNDtD0AM0PyJ1s2iqC5uu699sbGZhYZm9ahemUX9gkNz2+RzbuZDN3NxCOUWhAkK6gTyvxE9rqra16zGqz132eT1cmgyoyqg0I0oXCiIFJrtQ298uTy8tiV7mcjH1NibEBgRnQyB0N3Y+0hb+Dl25sQKCPkYEZxtNK/IIqE9Umqk66JIoNCNIV9RXhbnUMNcrWumdlQ/WT1lFi2c6uKjuf/Z4xW0VSEcR9b2RgYjLY5Eey8TCfmZtXYc1vltdndzP3+K0i2VBVmjiHmUxF5w7rsGocWo3Dq7ORSQ0I0hXE+zwD0yBYQYuVtFhRm42ydatItgUmjIwNykenX5GV5fdJZWe02mBmAuFoWgOCdDEwPYKJYBM2c6cDezWfy6+29m5iD2c2iK8qs03Uesl6CR+S1lc/YT1+Pzdk9rSEqQ0I0hXE+3z2fTTNEugONGPeQatbELoGmYoNCAgOt22UJSW3yaG2N9WIOdiAIDyMDEyU6dmyECKZwfNjVj9a9KXdXWpWM3e7qjSpAUG6srnCdOoebpGChudlXXWONPZG/wlT/FYRVpUTscL0SBAbWsMMJ5/gBJSF66qtE1GiztQGBOnKxjnMZE507ZK88vtlR9PLMnShT41GC7eKTI1zmB5hYF4OZ2zirM3bcw9I4eFoPrpEOJrcgCBdDMzLjY2Pys7mlfJq2b1S1rFdjYZffFVJk2NgesSE00r8UnyyWx5aVCzzV1dJW+ewGg0/NiCYXLYucHOjpb9C3qqZI+/UzpP2oXC/J7CqTA1PKyFtVm1rlFue2idb955RI+GUTQ0IyD/F7VvlpdI7Zf+ZN9RIeNhVZbY2IIgSIwMTpTo/dU+t6lSf5Cw9LnNeLZfG1kE1Gg6oIg+0rmNV6YJpp5X4pW+kXbY3LpL8qtlS13NQjQaLDQjSh8VuuqfejAzMIE7ijrINRaflxpzd1p9hwK0iqeEcZmow/7268mFrPrx/pFON6oVwZAOCzARxKpWR/9Kw6IcVZmpQYc5dUWFVnFWngvmkiyoymxsQpMvk00r8tLdljSwrvVtK2t9TI3qwAYE3gjiVih9NaYIte1qsuU3McerEqpKC0DZQI5trc2VT7dPSOlCtRv3BBgTRZ2RgcoVsZrB6FqtosZoWq2r95KwquVUkPbzfM3e8Y5u8cvy/ZU/LahnHHiwPxW8VYVXpjSBOpTIyMLEIgo9kM4f9mnfkHrT2b3r8HmJhAwJvcA7TG4Oj3fLBqSWyuvJBqenao0Yzw60i/uEcpkcwp8NP3d5AZ6AX1tdYnYLQMcgLCEc2IPAOA9Nb9T2HZG3VI7Kt4QXpHTmrRlMTX1WS9zCHqbstpJH/0vCpI1sOkNYFvWjRkxa9aQeHL6jR1LEBgffYS9Yf2Na0tOT2lBeg2VtFMF/Jx6/+wU4I3bsh+NGUXMOpJzj9ZMa8Q9ZpKKlgAwKKoo6hBtlaN1/eqnlKmvvL1WhidlXJrSLmYoVJKcM5mzhv87m11db5m8mgisQndFaV/mGF6T88GVlRNtNaoDY6dvk9b89VIjBZVerBCtMj06ZNY2BqsLKgQW6du18K9reqkYlQSXKriP84h6kHPuwVNS2TvPJfSFXnR9YYwhGPXhGW3CqiF+cwPcLA1Ke8vldmLy6R3LxKae4YssbwxsIGBPowMPU61Vss66t/Iwe3PyDnFt7ErSIBYWB6hFtK9MsvbJKbHt8jb+z9mFWlZrzf9bIbEDQvv1XWfHSzHG57W/2EdEJRxNNKKJJQVW49sUwWHfiZzNu4RmqbOVdJZrEX9TgbEHQNN8t79c9ZFScqTzKbkYHJ0xv0im9AsHFni1Vtouok//F+999UDQgwp4m5TcxxcmGbHljcyV6yHuCcjh54Y5isAQHmM3PzKqz5Tcxzkn94v/vHWVWiaXoyWD2LuXuspsWqWvIXAhPdfnQy8l8aT2/wn9sGBFhBi5W0WFFL/uD97o90z6rEfk3s28T+TezjJH+guuSiHwq1dBoQYK/mc/nV1t5N7OEkCjO7qsy0AQE+TKJTEDoGkRmMDEz2kfUeqshMGxCgO9CMeQetbkHoGkTe4P3uHa8bEKAXLXrSojctetSSd7BKVvf2QeMCEy8g9mGSd5wNCDJta4c+tOhHi7606E9LmeMcZuYQjn42IMDpJzgFBaeh4FQUyhznMD3AwPQOqki/GhDg5JNZC45YJ6HgRBRKHwMzM1jM49wq4hecs4nzNnHuJs7fpMxgDnPmzJnqOz2MDEx88qDMYKuI3w0IcMYmztq8/ekD1tmblB7dCx9MgUoS20Rw6Wxr1zpQLZtqn5bNtbnSNlCjRilVaNixadMm9Z0e/GhKEzirSl1L44tPdstDi4pl/uoqaescVqNE/rAX9eioKpMpaX9PlpXeLXtb1qgRCjtWmHRRfAMC3VZta5RbntonW/a0qBFygxWme1M1INCtf6TT+ve2uvJhHqaeIlaYHsCKQe5LSw3CcbIGBLpVneqVnKXHZe6KCmlsHVSjlAznMKfmrCqnakAQhLqeg5JfNVu2Ny6SvpHUzprNVpzD9AA+dbBVmHtuGxDotqHotNyYs9v6k5JjYCaXbgOCIOw/84a8VHqnFLdvVSM0GQamR3h6w9TSaUCgGypMVJqoOKtO9alRisf7PTG7qsy0AYFu7UP18k7tPHmrZo609FeoUUpE973Pj6ZZBlVkpg0IdNu694w1t4k5TiI3EJCoKgd3LAt9VTmZso7t8mrZvbKzeaWMjXPrVRgY+UhW92bWqPCyAYFuWD2LVbRYTYtVtXQJpyAusc+q1L1VxC9DF/pkR9PLkld+v5zo2qVGCbDgh71kM1RUVCQ33HCD+o4AVaRfDQh0w37NO3IPWvs3sY+TYv+IOYdpVZHYIhL0VhG/NPYek3XVOVLQ8Lx0D3MVOSAwp0+frr7Tw8gKU/eLGGY6GhDohs5A6BA0a8FRq2NQtsv2VeGoJO2tIiZUlckcantTlpTcJofbNqqR7IXiiIt+yBPOqtLUs/nQixY9adGbdvA8m7lnG3tRj11VZotzQ03Wgr311U9YH4hJH+MCE40LcGWzoBsQ6IRTT3D6yYx5h6zTULJRNp5WErYGBEGo7CySleX3yUenX5GRsezbsxzEe71xgRnEc+2wsKvKMDQg0A3nbOK8TZy7ifM3s0k2zWE6q8owNiDQbWRsSD4+vUJeK58lFZ3R2TrjBc5heiBbAzOsDQh0W1nQILfO3S8F+1vViPmyJTCj1IBAt9P9ZbKh+knZWvesdAxlx/YrBqYHsOgHL2S2iEIDAt3K63tl9uISyc2rkOaOITVqLtN7ySIcEZJRa0AQhCNtm+SvJT+RA63r1Yi5gnivz55nOYZBFRm1BgS65Rc2yU2P75GNO7kMP6p0nVVpku7zrfL3hoWytuoxaeg9qkbJC6wwIyjKDQh0O9ncL08uL7Ou2tjXJjKxwjStAUEQqrt2y6rKX8qHTUtlcLRHjZoDi93QT1Yn4wIziIa8utiLekxoQKAbqkxUm6g6TWPSHCaqSJMbEOg2Nn5Bdrf8TV4p+6kc73hfjZohiCY1DMyIMLEBgW6Yz8S8JuY3y+rM+cRtSmBmUwMC3Vr6q6z3js21v5e2gVo1Gm0MTI/gsawpnFWlqQ0IdMMKWqykXVlgxmrCqN/vqCKzsQFBEIrb35WXS++SfWfy1Ui06b73jQxMU2RTAwLdsFcTezaxdxN7OCkYbECgX99Ih2xv/Iu8XvVrqe05oEbJDeMCc9GiRdongr1mV5XZ2IBAN3QHmjHvoNUtCF2DoiiKp5U4q0o2IAgGwnJN5a9i4fmiFaJRg0eyuk+mMjIwo3y8FwISVeWB1nWsKjUZHL5g9aNFX9pdJdF744jaHCYbEITL3pbXrce0eFwbJXgcq/vDopGBiStqsJCHDQiChZNPZi04Yp2EghNRoiIqp5UgHNmAIJzaBmutBUFv18yVMwMn1Gi4YVsJF/1kGVSRbGsXHjhjE2dt4szNwsNn1Shlig0IogFbT7AFBVtRsCWFJjIuMKN0WgkqSVSUrCrDp/hktzz8YonMX10lbZ3DajScwnxaCRsQRM/QaI/V7ABND9D8IKx4WokHMH8Z9key9qIeVpXht/r9U3LLU/tky57wttcL4xwmqsjBHctYVUYY2uqtPfGY1Wavezh8hxlwDtMDYQ9MNiCInqrGXslZelzmrqiQxtbwnTsYtsDkVhGzoJE7GrofPbtZjYQDA9MD6CMbxo3czqqSDQiiaUPRabkxZ7f1Z5iEpZcsqkg2IDDTuaFG2Vr3R3mz5rfWUWJhgMexuosj4wIzjNiAwByoMFFpouKsOtWnRolVZXao7NxhHVaNQ6txeHW2YYXpI7uqZAMC82zde8aa21y1Lfj2ekFWmHZV2fns97hVJEuMjA1KUdNyWVl+XyxAi9SofqwwPYDG62Ho9GPPVSIwWVWaCatnsYr2oUXF1qraoAQ1h8kGBNmtqa9U1lc/Ie/W/Uk6h/VPU2B1uO49yAxMjyEc0YAAYcmtItmh8HCbtW8T+zexj1M33YGJcGQDArIdadsoS0puk0Ntb6oRPRiYHkCZHtS+NDYgyF7oDIQOQbMWHLU6BumkcwqCDQgoke7hFiloeF7WVedIY6+++1H39JtxgRkEVJJsa0ewu/Sc1ZMWvWkHhs3plMIGBORGddcuyYsVDTuaXpahUfMWxRn5SFbXpw57UQ+rSnIavTBunX6CU1BwGorf/NyLFr9VhFUlTeXC2Ijsal4pr5bdK2Ud29Wo9/Akcfr06eo7PYwLTLyAWCnrNzYgoKngnM37Fx6T59ZWW+dv+sWvOUxuFaFMtPRXxN4f58iWuj9I+5D302SYfps2bZr6Tg/jAhOdfvwMTGdVyQYE5MZrBQ1y69z9UrDfn/ZiXi98iK8qiTJR3L5VXi69U/afWatGvIHAZKefEGMDAkpXeX2vzF5cIrl5lXK6PXzt9WysKskPfSPt8n7DnyW/arbU9RxUo9FjXGD6sULWrirZgIAylV/YJDc9vkc27vSumbsX97xdVbIBAfnpZPc+WVP5sBQ2LpaB0cxPGtG9I8K4wMSBokVF3nWfYAMC8trJ5n55cnmZddXGvs5UpnOYbEBAuu1tWSPLSmdIaUeBGkkd5zA9gGfaXqySRTiyAQH5CVUmqs38D5rUSHrSDUyEIxsQUFDaBmpkc22ubKp9WloHqtWoewxMD6C3IF7ITLABAenS3DEkuXkV1vxmWV2PGk1NOr1k2YCAwuJ4xzZZfvwe2dOyWsbHx9To1PA+z16yAWIDAgoKVtBiJe3KAn+bubMBAYXR4Gi3fHBqiayufFBquvao0Th4coh9l//0TyJf+tInX7PTTwZiL17et74l9V/8YkovqL2oh1UlBQl7NZ/Lr5YHFh6z9nC65abCjN8qwqqSwqi+55CsPfGobGt4QXpHzqrRmLfeErnySpHPfhZzEBevZz796U9+pok5gale0GuuuELqHS+o9SIneUHZgIDCBt2B7v7DIatb0MhokkdU6hO3NYeZ5AMit4pQ1BxoXScvld4RK2DeiZWfgyJXXXXpPd1xWfc+fobf0SD2XzOA4wW9JnZNCExcCV5QZ1XJBgQUNoPDF6x+tOhLu6ukQ406OD5xW28a9uX4gBhfVRJFScdQg2ytmy9vbb9Lmr/7lYnv6eqy7n1UnXPmqL/lr9h/zQA5ORcDE2HZpV7Mi1fcC8oGBBQVOPlk1oIjsnBdtXUiiiXuE/cx572OK/azkcrdVlBivpKPXynKyh/6jqz48Mey8zffkNF/+PSEe/3ivf+1r6nf9lfsv2SAr399wouY8Iq9oHZVyQYEFCXj4+PWWZs4c7Pw8NkJHxDjr/HPfVoGfvxV6fnd97lVhMzwhS/I8FVXStH/flPy/v5DOfFfV19+73/+8+qX/RX7Lxkg9oLaL9wNseuyCjN2NX33ajYgoEgrPtktDy8qkfl3vyhtV3354r19vfpz5KtfkJ77r5OBH14t49+4Tv0toohzvL+f+vY/y/r870vBC/8pXbH73b73GZipcLyg02KXMzDxyeTdRd+W/PU/kKuvmyZXXHEFL16RvlZ8Z5bc8utC2fLN6dY9jnmcvjv+xQrL0S//ozXWH7sS/V1evKJ2lcXuZfv93L4Oz/pXOfDAdbEv1RieMmoQ+y8ZwPFIFp84nIF57J5rrWv4P76hfpko4mIfEKu+fJ3k3L5E5kx/Xr7yuStlKPbJG49j7fte1yduIt8lmYJ4FH9ijQp+R4PYf80ASV5Q69L4ghL5zvEBccO/z5A13/nZxPsdl6ZP3ES+S7KtxLrwhJHbSlIQoheUyHf8gEjZBlulPvOZy+91jK1apX7Jf7H/oiFC8oIS+Y4fECkboSnHzTeLoOE62uPhaxed3LwU+9dlkBC8oERa8AMikXZmBSZRNuEHRCKtGJhEREQuMDCJiIhcYGASERG5wMAkIiJygYFJRETkAgOTiIjIBQYmERGRCwxMIiIiFxiYRERELjAwiYiIXGBgEhFRqOzatUtwOPSCBQvUyCUPPvig9bPa2lo1oo8RgRnWF5dIB97/ZKIf/ehHl927+BpjuK+DYEyFGcYXl0gX3v9kGvv+xb1ts+/zoBgTmGF8cYl04f1PJsJTE9zDeIpiP0l544031E/1M+pfU9heXCKdeP+TiXAfX3vttRevIBn38TNMLy6Rbrz/yTT40If7Ghc+CAbJuMAM04tLpBvvfzKN/eQEV6InJvbCNlyJFr55ybjAnOrFBczt8NM3mShMby5EmXIuXEs0J4+f24va7N/1k1GBOdWLCwhKvJEwMMk06by54E+isML9at/H9rz8ZB/08HO/39eNCky3Ly7eJBiYZJpU3lwA/wYYmBRWie5h+x533rf2WPy4H4wJTLcvLjAwyTSp3P+A3+e/AQoz3J/x9yjuZdzTeIISz/5ZovvdK8YEZiovLsb5ZkEmSfXNBb+L0CQKI3zww72baB7e/lmi+xcfEidbu+IFIwIz1ReXgUkmSfX+R4D6+aZCpAvuY+e9PFmQesWYCjMVDEzKVghLhCiRKRCS9uX3B8GsC0zni6vjBSYKC9zr8fc/w5PIvaysMImIiFLFwCQiInKBgUlEROQCA5OIiMgFBiYREZELDEwiIiIXGJhEREQuMDCJiIhcYGASERG5wMAkIiJygYFJRETkAgOTiIjIBQYmERGRCwxMIiIiFxiYRERELjAwiYiIXGBgEhERucDAJCIicoGBSURE5AIDk4iIyAUGJhERkQsMTCIiIhcYmERERC4wMImIiFxgYBIREbnAwCQiIpqSyP8DgP4UFY6TqxIAAAAASUVORK5CYII=) # + [markdown] id="BF4VJMFfOhWh" # ## No 1 # # \begin{equation} # k_{11} = \int_0^1 \frac{dN_1}{dx} \frac{dN_1}{dx} dx = \int_0^{1/2} \frac{dN_1}{dx} \frac{dN_1}{dx} dx = \int_0^{1/2} (-2) (-2) dx = (-2) (=2) \left(\frac{1}{2} - 0 \right) = 2 # \end{equation} # # \begin{equation} # k_{12} = \int_0^1 \frac{dN_1}{dx} \frac{dN_2}{dx} dx = \int_0^{1/2} \frac{dN_1}{dx} \frac{dN_2}{dx} dx = \int_0^{1/2} (-2) (2) dx = (-2) (2) \left(\frac{1}{2} - 0 \right) = -2 # \end{equation} # # \begin{equation} # k_{13} = \int_0^1 \frac{dN_1}{dx} \frac{dN_3}{dx} dx = 0 # \end{equation} # # \begin{equation} # f_{1} = \int_0^1 f N_1dx + \frac{du}{dx}(1) N_1(1) - \frac{du}{dx}(0) N_1(0) = \frac{f}{4} - \frac{du}{dx}(0) # \end{equation} # # + id="iGfSq2iyOjGG" k11 = 2.0 k12 = -2.0 k13 = 0.0 f1 = f/4 - dudx_0 # + [markdown] id="bBmhc04hOrHY" # ## No 2 # # \begin{equation} # k_{21} = \int_0^1 \frac{dN_2}{dx} \frac{dN_1}{dx} dx = 2 # \end{equation} # # \begin{equation} # k_{22} = \int_0^1 \frac{dN_2}{dx} \frac{dN_2}{dx} dx = \int_0^{1/2} \frac{dN_2}{dx} \frac{dN_2}{dx} dx + \int_{1/2}^{1} \frac{dN_2}{dx} \frac{dN_2}{dx} dx = \int_0^{1/2} (2) (2) dx + \int_{1/2}^{1} (-2) (-2) dx = 2 + 2 = 4 # \end{equation} # # \begin{equation} # k_{23} = \int_0^1 \frac{dN_2}{dx} \frac{dN_3}{dx} dx = \int_{1/2}^1 \frac{dN_2}{dx} \frac{dN_3}{dx} dx = \int_{1/2}^1 (2) (-2) dx = -2 # \end{equation} # # \begin{equation} # f_{2} = \int_0^1 f N_2dx + \frac{du}{dx}(1) N_2(1) - \frac{du}{dx}(0) N_2(0) = \frac{f}{2} # \end{equation} # # + id="Y7q3cIvpOojV" k21 = k12 k22 = 4.0 k23 = -2.0 f2 = f/2 # + [markdown] id="82ppp5c9hWqJ" # # Sistema de equações # # \begin{equation} # \begin{bmatrix} # k_{11} & k_{12}\\ # k_{21} & k_{22} # \end{bmatrix} # * # \begin{bmatrix} # u_1\\ # u_2 # \end{bmatrix} # = # \begin{bmatrix} # f_1 - k_{13} * u_3\\ # f_2 - k_{23} * u_3 # \end{bmatrix} # \end{equation} # # # + [markdown] id="3yTLE-K8Q7_P" # ## Matriz de Coeficiente Real # + colab={"base_uri": "https://localhost:8080/"} id="0wGsBXIVQ9UX" outputId="9b72c1df-76cf-4786-e1f8-110a210a6bf1" K = np.array([ [k11, k12], [k21, k22], ]) K # + [markdown] id="SlEP1AwLhDtH" # ## Vetor de forças # + colab={"base_uri": "https://localhost:8080/"} id="Elu1WcbJRESI" outputId="ad3ed0e5-4f78-4b62-b5c2-7d347df4e30b" F = np.array([ f1 - k13 * u3, f2 - k23 * u3 ]) F # + [markdown] id="XeoPly9OhJTK" # # + id="2ACiogu7SE4D" lu, piv = lu_factor(K) u1, u2 = lu_solve((lu, piv), F) # + colab={"base_uri": "https://localhost:8080/"} id="x9OaQ5zUT6kf" outputId="5917a0c8-0ac8-4f5c-d9c2-122748fc83a5" u_numerico_coef = [ u1, u2, u3] u_numerico_coef # + colab={"base_uri": "https://localhost:8080/"} id="cIXABM1BUg8_" outputId="5e257b79-775a-4cd6-cd42-8416b91929d8" x_malha = [0, 0.5, 1.0] x_malha # + [markdown] id="WCINPSoZgdBE" # # Solução Exata # # Solução # $$ # u(x) = x ^ 2 - 2 x + 1 # $$ # # Derivada da solução # # $$ # \frac{du}{dx} = 2 x - 2 # $$ # + id="qmge9f6qSWCE" def u_analitico(x): return x**2 - 2.0 * x + 1.0 def dudx_analitico(x): return 2.0 * x - 2.0 # + [markdown] id="PKcpQsm9cuEs" # # Solução númerica # # Aproximação # # $$u(x) = N_1(x) u_1 + N_2(x) u_2 + N_3(x) u_3$$ # # **Funções de interpolação:** # # * $N_1$: # # $$ # N_1(x) = \begin{cases} # &1 * -2 x &\text{ se } & 0 < x < 1/2 \\ # &0 &\text{ se } & 1/2 < x < 1 # \end{cases} # $$ # # * $N_2$: # # $$ # N_2(x) = \begin{cases} # &2 x &\text{ se } & 0 < x < 1/2 \\ # &2 - 2 x &\text{ se } & 1/2 < x < 1 # \end{cases} # $$ # # * $N_3$: # # $$ # N_3(x) = \begin{cases} # &0 &\text{ se } & 0 < x < 1/2 \\ # &2 x - 1 &\text{ se } & 1/2 < x < 1 # \end{cases} # $$ # # # + id="le646rTbWl45" def u_numerico(x, u_numerico_coef, x_malha): u1, u2, u3 = u_numerico_coef x1, x2, x3 = x_malha # 0 < x < 1/2 if x1 <= x < x2: N1 = 1.0 - 2.0 * x N2 = 2.0 * x N3 = 0.0 # 1/2 < x < 1 elif x2 <= x <= x3: N1 = 0.0 N2 = 2.0 * ( 1.0 - x) N3 = 2*x - 1.0 return N1*u1 + N2 * u2 + N3 *u3 # + [markdown] id="1eSsWTY7fmOy" # **Solução númerica:** # # $$ # \frac{du}{dx}(x) = \frac{dN_1}{dx}(x) u_1 + \frac{dN_2}{dx}(x) u_2 + \frac{dN_3}{dx}(x) u_3 # $$ # # **Funções de interpolação:** # # * $\frac{dN_1}{dx}$: # # $$ # \frac{dN_1}{dx} = \begin{cases} # &-2 &\text{ se } & 0 < x < 1/2 \\ # &0 &\text{ se } & 1/2 < x < 1 # \end{cases} # $$ # # * $N_2$: # # $$ # \frac{dN_2}{dx} = \begin{cases} # & 2 &\text{ se } & 0 < x < 1/2 \\ # &-2 &\text{ se } & 1/2 < x < 1 # \end{cases} # $$ # # * $N_3$: # # $$ # \frac{dN_3}{dx} = \begin{cases} # &0 &\text{ se } & 0 < x < 1/2 \\ # &2 &\text{ se } & 1/2 < x < 1 # \end{cases} # $$ # # + id="meHh3DeWcqiA" def dudx_numerico(x, u_numerico_coef, x_malha): u1, u2, u3 = u_numerico_coef x1, x2, x3 = x_malha # 0 < x < 1/2 if x1 <= x < x2: dN1dx = -2.0 dN2dx = 2.0 dN3dx = 0.0 # 1/2 < x < 1 elif x2 <= x <= x3: dN1dx = 0.0 dN2dx = -2.0 dN3dx = 2.0 return dN1dx * u1 + dN2dx * u2 + dN3dx *u3 # + [markdown] id="8caUiHJTgXkh" # # Plotando os resultados # + id="cVTWQeh5S4iE" x = np.linspace(0, 1, 50) # + id="6R66W8GDYPe2" u_exato = [ u_analitico(xi) for xi in x ] dudx_exato = [ dudx_analitico(xi) for xi in x ] # + id="-pp3L4X_YOyo" u_num = [ u_numerico(xi, u_numerico_coef, x_malha) for xi in x ] dudx_num = [ dudx_numerico(xi, u_numerico_coef, x_malha) for xi in x ] # + colab={"base_uri": "https://localhost:8080/", "height": 629} id="E-ZPIJxfTGgj" outputId="889aa1e7-b73d-4ff3-c2f4-e4f0dae5beee" mpl.rcParams['figure.figsize'] = (20, 10) # fig, (ax1, ax2) = plt.subplots(ncols = 2) # ax1.set_title('Solução', fontsize = 18) ax1.plot(x, u_exato, label = 'Analito') ax1.plot(x, u_num , label = 'Numerico') ax1.set_ylabel('u(x)', fontsize = 14) ax1.set_xlabel('x', fontsize = 14) # ax2.set_title('Derivada', fontsize = 18) ax2.plot(x, dudx_exato) ax2.plot(x, dudx_num) ax2.set_ylabel(r'$\frac{du}{dx}(x)$', fontsize = 14) ax2.set_xlabel('x', fontsize = 14) # ax1.grid(ls = '--') ax2.grid(ls = '--') # ax1.legend(fontsize=14) plt.show() # + id="2ivvldls7WCe"
notebooks/Elemento_finitos_Exercicios_ex1.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 # --- # # Simple Convnet - MNIST # # Slightly modified from mnist_cnn.py in the Keras examples folder: # # **https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py** WEIGHTS_FILEPATH = 'mnist_cnn.hdf5' MODEL_ARCH_FILEPATH = 'mnist_cnn.json' # + import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.callbacks import EarlyStopping, ModelCheckpoint # + nb_classes = 10 # input image dimensions img_rows, img_cols = 28, 28 # the data, shuffled and split between train and test sets (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 print('X_train shape:', X_train.shape) print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) # + # Sequential Model model = Sequential() model.add(Convolution2D(32, 3, 3, border_mode='valid', input_shape=input_shape, dim_ordering='tf')) model.add(Activation('relu')) model.add(Convolution2D(32, 3, 3, border_mode='valid', dim_ordering='tf')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2), border_mode='valid', dim_ordering='tf')) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # + # Model saving callback checkpointer = ModelCheckpoint(filepath=WEIGHTS_FILEPATH, monitor='val_acc', verbose=1, save_best_only=True) # Early stopping early_stopping = EarlyStopping(monitor='val_acc', verbose=1, patience=5) # Train batch_size = 128 nb_epoch = 100 model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=2, callbacks=[checkpointer, early_stopping], validation_data=(X_test, Y_test)) score = model.evaluate(X_test, Y_test, verbose=0) print('Test score:', score[0]) print('Test accuracy:', score[1]) # - with open(MODEL_ARCH_FILEPATH, 'w') as f: f.write(model.to_json())
demos/notebooks/mnist_cnn.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: computationalPhysics # language: python # name: conda-env-computationalPhysics-py # --- # <h1> Measuring Youngs Modulus of a Ball Spring Model Solid </h1> # <h2> <NAME> </h2> # <h2> Computational Physics Term Project </h2> # <hr> # <h3>Abstract</h3> # Introductory physics course teach a ball spring model of solids, using only this model it is possible to make numerical simulations demonstrationg traditionally more complex propoerties of solids which do not feature heavily in introductory course work. Here I present a simple method to measure youngs modulus of a 2-Dimensional solid modeled as point masses connected in a lattice of damped springs. This could be adapted to an introductory lab allowing students to investigate emergent properties of solids computationally. # <hr> # <h3>Boilerplate and Initial Conditions</h3> # We start by including the relevant modules. Note that I include the numba module. Numba allows for just in time compilation of python code, drastically speeding up certain steps of the simulation. However, Numba can also me difficult to install, if you are trying to run this notebook and are unable to install Numba simply remove teh import statement and remove all @njit decoraters above functions. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mplEasyAnimate import animation from tqdm import tqdm from scipy.special import comb from scipy.special import factorial from numba import njit, jit from scipy.stats import linregress # I will define a function to generate the initial conditions of the lattice. The latice will be comprised of $N_{v}\times N_{h}$ point masses in a rectangular grid, all seperated by the equilibrium length of the springs connecting them (See Below). # # <img src="PresentationFigures/BallSpring.png" alt="Drawing" style="width: 500px;"/> def make_lattice(Nv, Nh, sep): lattice = np.zeros(shape=(Nv, Nh, 4)) for nv in range(Nv): for nh in range(Nh): lattice[nh, nv] = np.array([nh*sep, nv*sep, 0, 0]) return lattice # The following functions are simply to aid in visulization latter. def plot_system(y, F=None): fig = plt.figure(figsize=(10, 7)) ax = fig.add_subplot(111) ax.plot(y[:, 1:-1, 0], y[:, 1:-1, 1], 'C0o') if F is not None: ax.quiver(y[-1, 1:-1, 0], y[-1, 1:-1, 1], F[0], F[1]) return fig, ax def animate_system(filename, ys, F=None, skip=1): anim = animation(filename, fps=30) for i, y in tqdm(enumerate(ys), total=ys.shape[0]): if i%skip == 0: fig, ax = plot_system(y, F=F) ax.set_xlim(np.min(ys[0, :, 0])-0.1, np.max(ys[-1, :, 0])+0.1) ax.set_ylim(np.min(ys[:, 0, 1])-0.1, np.max(ys[:, -1, 1])+0.1) anim.add_frame(fig) plt.close(fig) anim.close() # <h3>Model</h3> # We define a 9 part peicwise model to control the numerical integration of our system. Eight parts of this model are to account for boundary conditions with one final part dedicated to all remaining particles. The equations of motion are as follows # # $$ # \ddot{x} = -b\dot{x}-\frac{k}{m}\begin{cases} # 0 & i = j = 0 \\ # 0 & i = 0, j = N_{v} \\ # 0 & i = 0, 0<j<N_{v} \\ # \left[2s-x_{i-1,j}-x_{i, j+1}\right] & i = N_{h}, j = 0 \\ # \left[2s-x_{i-1,j}-x_{i, j-1}\right] & i = N_{h}, j = N_{v} \\ # \left[3s-x_{i-1,j}-x_{i, j-1}-x_{i, j+1}\right] & i = N_{h}, 0<j<N_{v} \\ # \left[3s-x_{i+1,j}-x_{i, j+1}-x_{i-1, j}\right] & 0<i<N_{h}, j=0 \\ # \left[3s-x_{i+1,j}-x_{i, j-1}-x_{i-1, j}\right] & 0<i<N_{h}, j=N_{v} \\ # \left[4s-x_{i+1,j}-x_{i, j-1}-x_{i-1, j}-x_{i, j+1}\right] & otherwise \\ # \end{cases} # $$ # One area of future improvment which should be considered is automating the calculation of boundary conditions so that they do not have to be manually input. # # One side of this model is pinned so that it may not move. I have achived this by calculating the force on those masses as always zero. Note also that the corners where $i=N_{h}$ have only two spring connected to them, so when those springs are offset from eqilibrium the force vector will be striktly inwards towrds the bulk of the solid. This is not a concern for the results of this simulation as the corners, top row, and bottom row of point masses are included to keep all other particles in equilibrium and are not themselves considered to be meaningful particles in the simulation. # # In order to impliment this model I will define three functions. One function to quickly find the vector, magnitude, and unit vector from a given particle to another. A second function to find the force vector acting on a single particle given some list of relative $i, j$ coorindates to connect springs from it to. Finally I define the model function itself where I calculate the acceleration on each particle. @njit def getVecs(r1, r2): sr = r2-r1 srmag = np.sqrt(sr[0]**2+sr[1]**2) return sr, srmag, sr/srmag @njit def getForceComponents(r, v, pList, IDx, IDy, k, b, sep, xoffsets, yoffsets, ts): FMag = np.zeros(shape=(2,)) for oID in range(len(xoffsets)): dx = xoffsets[oID] dy = yoffsets[oID] sr, srmag, srhat = getVecs(r, pList[IDx+dx, IDy+dy, :2]) if srmag > 0.1: FMag += -k*(sep-srmag)*srhat-b*v return FMag @njit def ym_nbody(I0, IDx, IDy, h, sep, pList, massList, ts, b, k, F): dydt = np.zeros(4) v = I0[2:] dydt[:2] = v r = I0[:2] m = massList[IDx, IDy] # corners if IDx == IDy == 0: FMag = getForceComponents(r, v, pList, IDx, IDy, k, b, sep, [1, 0], [0, 1], ts) FMag = np.array([0.0, 0.0]) elif IDx == pList.shape[0]-1 and IDy == pList.shape[1]-1: FMag = getForceComponents(r, v, pList, IDx, IDy, k, b, sep, [-1, 0], [0, -1], ts) + F elif IDx == 0 and IDy == pList.shape[1]-1: FMag = getForceComponents(r, v, pList, IDx, IDy, k, b, sep, [1, 0], [0, -1], ts) FMag = np.array([0.0, 0.0]) elif IDx == pList.shape[0]-1 and IDy == 0: FMag = getForceComponents(r, v, pList, IDx, IDy, k, b, sep, [-1, 0], [0, 1], ts) + F # edges elif IDy == 0 and IDx != 0 and IDx != pList.shape[0]-1: FMag = getForceComponents(r, v, pList, IDx, IDy, k, b, sep, [-1, 0, 1], [0, 1, 0], ts) elif IDy == pList.shape[1]-1 and IDx != 0 and IDx != pList.shape[0]-1: FMag = getForceComponents(r, v, pList, IDx, IDy, k, b, sep, [-1, 0, 1], [0, -1, 0], ts) elif IDx == 0 and IDy != 0 and IDy != pList.shape[1]-1: FMag = getForceComponents(r, v, pList, IDx, IDy, k, b, sep, [0, 1, 0], [-1, 0, 1], ts) FMag = np.array([0.0, 0.0]) elif IDx == pList.shape[0]-1 and IDy != 0 and IDy != pList.shape[1]-1: FMag = getForceComponents(r, v, pList, IDx, IDy, k, b, sep, [0, -1, 0], [-1, 0, 1], ts) + F # All other particles else: FMag = getForceComponents(r, v, pList, IDx, IDy, k, b, sep, [0, 1, 0, -1], [-1, 0, 1, 0], ts) dydt[2:] += FMag/m return dydt # <h3>Integration</h3> # We will integrate this model using a fourth order Runge Kutta Method. Given we are working with a small number of oscillators this method will proove to be sufficient. However, if one were interested in increasing the number of masses in the solid another, more stable, integration method should be considered. @njit def ym_rk4(y0, IDx, IDy, h, sep, pList, massList, ts, b, k, F): k1 = h*ym_nbody(y0, IDx, IDy, h, sep, pList, massList, ts, b, k, F) k2 = h*ym_nbody(y0+k1/2, IDx, IDy, h, sep, pList, massList, ts, b, k, F) k3 = h*ym_nbody(y0+k2/2, IDx, IDy, h, sep, pList, massList, ts, b, k, F) k4 = h*ym_nbody(y0+k3, IDx, IDy, h, sep, pList, massList, ts, b, k, F) return y0 + (k1/6)+(k2/3)+(k3/3)+(k4/6) # I define the following function to control the integration of the system. Note that this allows a force to be added into the system. This force will be included in the model for all particles $i=N_{h}$. The effect of this is that we have the ability to stretch the solid, an essential compoent in measuring youngs modulus. def ym_int_n_model(pList, mass, sep, h, tf=1, b=0.2, k=10, F=np.array([0,0]), pbar=True): ts = np.arange(0, tf, h) ys = np.zeros(shape=(len(ts)+1, pList.shape[0], pList.shape[1], pList.shape[2])) ys[0] = pList for i in tqdm(range(ts.shape[0]), disable=not pbar): for IDx in range(ys[i, :].shape[0]): for IDy in range(ys[i, :].shape[1]): ys[i+1, IDx, IDy] = ym_rk4(ys[i, IDx, IDy], IDx, IDy, h, sep, ys[i, :, :], massList, i, b, k, F) return np.arange(0, tf+h, h), ys # Youngs modulus is defined as # $$ # E = \frac{Stress}{Strain} # $$ # Where # $$ # Stress = \frac{A}{F} \;\;\;\;\;\;\;\;\;\;\;\;\;\;Strain = \frac{\Delta L}{L} # $$ # This is the general 3 dimensional defintion. As we are working in a 2 Dimensional system here the analogy to Area will be the length of the side the force is being applied over on the solid. I define the followign functions to find the stress, strain, and youngs modulus individually. def get_strain(ys): Li = np.mean(ys[0, -1, :, 0]-ys[0, 0, :, 0]) Lf = np.mean(ys[-1, -1, :, 0]-ys[-1, 0, :, 0]) dL = Lf-Li return dL/Li def get_stress(ys, F): A = ys[-1, -1, -1, 1]-ys[-1, -1, 0, 1] FMag = np.sqrt(F[0]**2+F[1]**2) return FMag/A def get_youngs_modulus(ys, F): return get_stress(ys, F)/get_strain(ys) # <h3>Results</h3> # I build a 10 by 10 lattice of partilces all seperated by a distance of 1 length unit. Each particle is given a mass of 1 mass unit. sep=1 n = 10 lattice = make_lattice(n, n, sep) massList = np.ones(shape=(n, n)) F = np.array([10, 0]) # We can use the helper functions from earlier to see the particles and the instantaious force on the last column of particles. fig, ax = plot_system(lattice, F) # We will integrate this for 15 time units with a time step size of 0.01 time units. Additionally I will heaviliy damp this system, giving the springs a dampening coefficient of 1. Finally I will set the spring stiffness to 50 Force units per length unit. ts, ys = ym_int_n_model(lattice, massList, sep, 0.01, tf=15, b=1, k=50, F=F) # We can animate this in order to see the solid expand, note that depenging on the speed of your long term storage media this line may take upwards of a minute to run. animate_system('Animations/PullAndRelease.mp4', ys, F, skip=10) # + from IPython.display import HTML def playVideo(path): return HTML(""" <video width="320" height="240" controls> <source src="{}" type="video/mp4"> </video> """.format(path)) # - playVideo('Animations/PullAndRelease.mp4') # Note here that the force remains constant yet the solid reatches an equilibrium stretch. This is because as the solid expands the spring force increases and eventually balances the stretch force. We can calculate youngs modulus using the functions that we already defined by simply telling the youngs modulus function about the recorded state of the system along with what the applied force was print("Youngs Modulus of this system is: {:0.2f}".format(get_youngs_modulus(ys, F))) # We may also be interested in determing a relationship between youngs modulus and the spring constant and dampening coefficient. I build up a 2 dimensional parameter space of spring constants and dampening coefficients, calculating youngs modulus at each point on the grid. Note that this cell may take signifigant time to run. # + nk = 10 nb = 10 K = np.linspace(1, 20, nk) B = np.linspace(0.05, 1, nb) e = np.zeros(shape=(nb, nk)) for ib, b in tqdm(enumerate(B), total=nb): for ik, k in tqdm(enumerate(K), total=nk, disable=True): ts, ys = ym_int_n_model(lattice, massList, sep, 0.01, tf=15, b=b, k=k, F=F, pbar=False) e[ib, ik] = get_youngs_modulus(ys, F) # - KK, BB = np.meshgrid(K, B) fig = plt.figure(figsize=(10, 7)) ax = fig.add_subplot(111, projection='3d') ax.plot_wireframe(KK, BB, e) ax.set_xlabel('Spring Constant', fontsize=17) ax.set_ylabel('Spring Dampening Constant', fontsize=17) ax.set_zlabel('Youngs Modulus', fontsize=17) # We see that the main factor contributing to youngs modulus; however, there is some structure if we slice for varying dampening constants, see below def line(x, m, b): return m*x+b # I will preform a standard linear regression for a slice along both the dampening constant and spring constant. When I preform this constant I will start 3 steps in to remove the inisial transience. This transicene is due to the simulations not running long enough for these solids to reach initial conditions. plt.figure(figsize=(10, 7)) plt.plot(B, e[:, 5]) slope, intercept, r_value, p_value, std_err = linregress(B[3:],e[3:, 5]) X = np.linspace(B[3], B[-1], 100) plt.plot(X, line(X, slope, intercept)) plt.xlabel('Spring Dampening Constant', fontsize=17) plt.ylabel('Youngs Modulus', fontsize=17) plt.title('Spring Constant = {:0.2f}'.format(K[5]), fontsize=20) plt.annotate(r"$r^{{2}}$={:0.3f}".format(r_value**2), xy=(0.4, 1.5), fontsize=17) plt.annotate(r"E={:0.2f}b+{:0.2f}".format(slope, intercept), xy=(0.6, 1.4), fontsize=17) plt.show() # If we instead slice at a constant dampening constant to show the structure inherint to the how the spring constant effects youngs modulus plt.figure(figsize=(10, 7)) plt.plot(K, e[5, :]) slope, intercept, r_value, p_value, std_err = linregress(K[3:],e[5, 3:]) X = np.linspace(K[3], K[-1], 100) plt.plot(X, line(X, slope, intercept)) plt.xlabel('Spring Constant', fontsize=17) plt.ylabel('Youngs Modulus', fontsize=17) plt.title('Spring Dampeing Constant = {:0.2f}'.format(B[5]), fontsize=20) plt.annotate(r"$r^{{2}}$={:0.3f}".format(r_value**2), xy=(5, 1.5), fontsize=17) plt.annotate(r"E={:0.2f}k+{:0.2f}".format(slope, intercept), xy=(11, 1.25), fontsize=17) plt.show() # <h3>Future Work & Conclusions</h3> # Here I have presented a simple method to measure youngs modulus computationally. This could be used to create as the basis of a lab for introductory physics courses. The results of these simulations clearly show a link between the spring constant and youngs modulus, but also between the dampening coefficient and youngs modulus. Future work could take a similar ball spring model as presented here and attempt to observe other properties of solids, such as the coefficient of restitution.
YoungsModulusOfABallSpringSolid/Boudreaux.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 # --- # # WRF # # * [UCAR-WRF](http://www2.mmm.ucar.edu/wrf/users/downloads.html) # * [Public Domain Notice](http://www2.mmm.ucar.edu/wrf/users/public.html) # * [tutorial](http://www2.mmm.ucar.edu/wrf/OnLineTutorial/index.htm) # * [registration](http://www2.mmm.ucar.edu/wrf/users/download/wrf-regist.php) # * [src](http://www2.mmm.ucar.edu/wrf/users/download/get_sources.html) # # + ###################### # from __future__ import print_function import os, sys; # lib = "/usr/local/apps/ecflow/current/lib/python2.7/site-packages/ecflow" lib = "/usr/local/apps/ecflow/current/lib/python3.5/site-packages/ecflow" lib = "/usr/local/lib/python3.5/site-packages/ecflow" sys.path.append(lib) import ecf; from ecf import (Client, Defs, Suite, Family, Task, Defstatus, Edit, Trigger) try: x = Edit(test="value") # Edit is present in recent ecf.py module except: class Edit(Variables): pass home = os.getenv("HOME") + "/ecflow_server" user = os.getenv("USER") WRF="WRFV3.9.1.1.TAR.gz" # HERE A PYTHON VARIABLE FROM="http://www2.mmm.ucar.edu/wrf/src/WRFV3.9.1.1.TAR.gz" # SUITE node = Suite("WRF").add( Defstatus("suspended"), Edit(ECF_HOME=home, ECF_INCLUDE=home + "/include", ECF_FILES=home + "/files", ECF_EXTN=".ecg", # current convention for generated task template extension ECF_JOB_CMD="%ECF_JOB% > %ECF_JOBOUT% 2>&1", # localhost run ECF_URL_CMD="firefox %URL%", WRF=WRF, # PYTHON VARIABLES IS TURNED INTO ECFLOW VARIABLE FROM=FROM, URL="http://lmdz.lmd.jussieu.fr/", ), Family("make").add( Family("get").add(Task("cmd").add( # Defstatus("complete") Edit(CMD="WRF=%WRF%; FROM=%FROM%;\n" + #ECFLOW VARIABLES TURNED INTO SCRIPT (SHELL) VARIABLE "[ ! -d WRFV3 ] && curl -o $WRF.tgz $FROM && tar -xzvf $WRF.tgz", ARGS=""))), Family("compile").add( Trigger(["get"]), Task("cmd").add( Edit(CMD="cd WRFV3 && ./configure && make")), ), ), Family("main").add(Task("cmd").add(Edit(CMD="echo", ARGS="YOUR PART")))) # TASK TEMPLATE with open(home + "/files/cmd.ecg", 'w') as task_template: print("""#!/bin/bash %include <head.h> %CMD:echo% %ARGS:% %include <tail.h>""", file=task_template) # DEFS defs = Defs() defs.add_suite(node) path = '/' + node.name() # CLIENT client = Client("localhost@%s" % os.getenv("ECF_PORT", 2500)) # PYTHON CLIENT client.replace(path, defs) # load/replace the top node (suite) client.begin_suite(node.name()) # BEGIN suite: UNKNOWN -> QUEUED client.resume(path) # RESUME suite: SUSPENDED -> create job and submit # - os.system("ecflow_ui &")
WRF.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 # --- # ### DataFrame Indexing and Loading # + import pandas as pd purchase_1=pd.Series({'Name':'chris', 'item_purschased':'Dog food', 'cost':22.50}) purchase_2=pd.Series({'Name':'Keyvn', 'item_purschased':'kitty litter', 'cost':2.50}) purchase_3=pd.Series({'Name':'Vinod', 'item_purschased':'bird seed', 'cost':5.0}) # - df=pd.DataFrame([purchase_1,purchase_2,purchase_3],index=['store1','store1','store2']) df costs=df['cost'] costs # ### applying Broadcasting to df costs+=2 costs df # this command will not work in window, it will only work in linux or MacOS # !cat olympics.csv df0=pd.read_csv('olympics.csv') df0.head() # ### Making 1st row as Column labels and 1st row as df label df0=pd.read_csv('olympics.csv', index_col=0, skiprows=1) df0.head() # ### settting the pandas name using the pandas' column name property df0.columns for col in df0.columns: if col[:2] == '01': print(col[:2]) df0.rename(columns={col:'Gold'+col[4:]}, inplace=True) if col[:2] == '02': df0.rename(columns={col:'Silver'+col[4:]}, inplace=True) print(col[:2],'Silver') if col[:2] == '03': df0.rename(columns={col:'Bronze'+col[4:]}, inplace=True) print(col[:2],'Bronze') if col[:2] == '№ ': df0.rename(columns={col:'Gold'+col[4:]}, inplace=True) df0.head()
pandas/Office_practice_2019_04_17_DF_loading_Indexing.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 # --- # # XOR Prediction Neural Network # #### A simple neural network which will learn the XOR logic gate. # # I will provide you with any links necessary so that you can read about the different aspects of this NN(Neural Network). # ## Neural Network Info # # #### All information regarding the neural network: # # - Input Layer Units = 2 (Can be modified) # - Hidden Layer Units = 2 (Can be modified) # - Output Layer Units = 1 (Since this is problem specific, it can't be modified) # # - No. of hidden layers = 1 # - Learning Algorithm = Backpropagation # # ![arsitektur_NN](Studi_kasus1.jpg) # # Feel free to mess around with it and try out different things. # + import numpy as np # For matrix math import matplotlib.pyplot as plt # For plotting import sys # For printing # - # ### Neural Network Implementation # Initially, I was going to approach this in an Object Oriented manner but I think that it would be much easier to read and implement, functionally. So, let's get started. # ### Training Data # # The XOR logic gate returns true when the number of inputs given is odd and false when they're even. Here is the simple training dataset. # + # The training data. X = np.array([ [0, 1], [1, 0], [1, 1], [0, 0] ]) # The labels for the training data. y = np.array([ [1], [1], [0], [0] ]) outNN = np.zeros(4) # - X y # ### Additional Parameters # These are just additional parameters which are required by the weights for their dimensions. num_i_units = 2 # Number of Input units num_h_units = 2 # Number of Hidden units num_o_units = 1 # Number of Output units # ### Neural Network Parameters # These are the parameters required directly by the NN. Comments should describe the variables. # + # The learning rate for Gradient Descent. learning_rate = 0.01 # The parameter to help with overfitting. reg_param = 0 # Maximum iterations for Gradient Descent. max_iter = 50 # Number of training examples m = 4 # - # ### Weights and Biases # These are the numbers the NN needs to learn to make accurate predictions. # # For the connections being made from the input layer to the hidden layer, the weights and biases are arranged in the following order: **each row contains the weights for each hidden unit**. Then, the shape of these set of weights is: *(number of hidden units X number of input units)* and the shape of the biases for this connection will be: *(number of hidden units X 1)*. # # So, the overall shape of the weights and biases are: # # **Weights1(Connection from input to hidden layers)**: num_h_units X num_i_units # **Biases1(Connection from input to hidden layers)**: num_h_units X 1 # # **Weights2(Connection from hidden to output layers)**: num_o_units X num_h_units # **Biases2(Connection from hidden to output layers)**: num_o_units X 1 # # ### Generating the Weights # # The weights here are going to be generated using a [Normal Distribution(Gaussian Distribution)](http://mathworld.wolfram.com/NormalDistribution.html). They will also be seeded so that the outcome always comes out the same. # + np.random.seed(1) W1 = np.random.normal(0, 1, (num_h_units, num_i_units)) # 2x2 W2 = np.random.normal(0, 1, (num_o_units, num_h_units)) # 1x2 B1 = np.random.random((num_h_units, 1)) # 2x1 B2 = np.random.random((num_o_units, 1)) # 1x1 # - W1 W2 B1 B2 # ### Sigmoid Function # [This](http://mathworld.wolfram.com/SigmoidFunction.html) function maps any input to a value between 0 and 1. # # ![sigmoid-curve.png](attachment:sigmoid-curve.png) # # In my implementation, I have added a boolean which if set to true, will return [Sigmoid Prime(the derivative of the sigmoid function)](http://www.ai.mit.edu/courses/6.892/lecture8-html/sld015.htm) of the input value. This will be used in backpropagation later on. def sigmoid(z, derv=False): if derv: return z * (1 - z) return 1 / (1 + np.exp(-z)) # ### Forward Propagation # [This](https://en.wikipedia.org/wiki/Feedforward_neural_network) is how predictions are made. Propagating the input through the NN to get the output. # # In my implementation, the forward function only accepts a feature vector as row vector which is then converted to a column vector. Also, the predict boolean, if set to true, only returns the output. Otherwise, it returns a tuple of the outputs of all the layers. def forward(x, predict=False): a1 = x.reshape(x.shape[0], 1) # Getting the training example as a column vector. z2= W1.dot(a1) + B1 # 2x2 * 2x1 + 2x1 = 2x1 a2 = sigmoid(z2) # 2x1 z3 = W2.dot(a2) + B2 # 1x2 * 2x1 + 1x1 = 1x1 a3 = sigmoid(z3) if predict: return a3 return (a1, a2, a3) # ### Gradients for the Weights and Biases # These variables will contain the gradients for the weights and biases which will be used by gradient descent to update the weights and biases. # # Also, creating the vector which will be storing the cost values for each gradient descent iteration to help visualize the cost as the weights and biases are updated. # + dW1 = 0 # Gradient for W1 dW2 = 0 # Gradient for W2 dB1 = 0 # Gradient for B1 dB2 = 0 # Gradient for B2 cost = np.zeros((max_iter, 1)) # Column vector to record the cost of the NN after each Gradient Descent iteration. # - # ## Training # This is the training function which contains the meat of NN. This contains forward propagation and [Backpropagation](http://neuralnetworksanddeeplearning.com/chap2.html). # # ### Backpropagation # The process of propagating the error in the output layer, backwards through the NN to calculate the error in each layer. Intuition: It's like forward propagation, but backwards. # # Steps(for this NN): # 1. Calculate the error in the output layer(dz2). # 2. Calculate the error in the weights connecting the hidden layer to the output layer using dz2 (dW2). # 3. Calculate the error in the hidden layer(dz1). # 4. Calculate the error in the weights connecting the input layer to the hidden layer using dz1 (dW1). # 5. The errors in the biases are just the errors in the respective layers. # # Afterwards, the gradients(errors) of the weights and biases are used to update the corresponding weights and biases by multiplying them with the negative of the learning rate and scaling it by divinding it by the number of training examples. # # While iterating over all the training examples, the cost is also being calculated simultaneously for each example. Then, a regurlization parameter is added, although for such a small dataset, regularization is unnecessary since to perform well, the NN will have to over fit to the training data. def train(_W1, _W2, _B1, _B2): # The arguments are to bypass UnboundLocalError error for i in range(max_iter): c = 0 dW1 = 0 dW2 = 0 dB1 = 0 dB2 = 0 for j in range(m): sys.stdout.write("\rIteration: {} and {}".format(i + 1, j + 1)) # Forward Prop. a0 = X[j].reshape(X[j].shape[0], 1) # 2x1 z1 = _W1.dot(a0) + _B1 # 2x2 * 2x1 + 2x1 = 2x1 a1 = sigmoid(z1) # 2x1 z2 = _W2.dot(a1) + _B2 # 1x2 * 2x1 + 1x1 = 1x1 a2 = sigmoid(z2) # 1x1 # Back prop. dz2 = a2 - y[j] # 1x1 dW2 += dz2 * a1.T # 1x1 .* 1x2 = 1x2 dz1 = np.multiply((_W2.T * dz2), sigmoid(a1, derv=True)) # (2x1 * 1x1) .* 2x1 = 2x1 dW1 += dz1.dot(a0.T) # 2x1 * 1x2 = 2x2 dB1 += dz1 # 2x1 dB2 += dz2 # 1x1 c = c + (-(y[j] * np.log(a2)) - ((1 - y[j]) * np.log(1 - a2))) sys.stdout.flush() # Updating the text. _W1 = _W1 - learning_rate * (dW1 / m) + ( (reg_param / m) * _W1) _W2 = _W2 - learning_rate * (dW2 / m) + ( (reg_param / m) * _W2) _B1 = _B1 - learning_rate * (dB1 / m) _B2 = _B2 - learning_rate * (dB2 / m) cost[i] = (c / m) + ( (reg_param / (2 * m)) * ( np.sum(np.power(_W1, 2)) + np.sum(np.power(_W2, 2)) ) ) return (_W1, _W2, _B1, _B2) # ## Running # Now, let's try out the NN. Here, I have called the train() function. You can make any changes you like and then run all the kernels again. I have also plotted the cost function to visual how the NN performed. # # The console printing might be off. # # The weights and biases are then shown. a0 = X[j].reshape(X[j].shape[0], 1) # 2x1 a0 W1, W2, B1, B2 = train(W1, W2, B1, B2) W1 W2 B1 B2 # ### Plotting # Now, let's plot a simple plot showing the cost function with respect to the number of iterations of gradient descent. # + # Assigning the axes to the different elements. plt.plot(range(max_iter), cost) # Labelling the x axis as the iterations axis. plt.xlabel("Iterations") # Labelling the y axis as the cost axis. plt.ylabel("Cost") # Showing the plot. plt.show() # - # # Observation # With the initial parameters, the cost function doesn't look that good. It is decreasing which is a good sign but it isn't flattening out. I have tried, multiple different values but this some seems like the best fit. # # Try out your own values, run the notebook again and see what you get. coba = np.array([ [0, 1], [1, 0], [1, 1], [0, 0] ]) coba # Forward Prop. for j in range(4): a0 = coba[j].reshape(coba[j].shape[0], 1) # 2x1 z1 = W1.dot(a0) + B1 # 2x2 * 2x1 + 2x1 = 2x1 a1 = sigmoid(z1) # 2x1 z2 = W2.dot(a1) + B2 # 1x2 * 2x1 + 1x1 = 1x1 outNN[j] = sigmoid(z2) # 1x1 outNN plt.plot(y, 'bo', linewidth=2, markersize=12) for j in range(4): plt.plot(j,outNN[j], 'r+', linewidth=2, markersize=12) for j in range(4): plt.plot(y, 'bo', j,outNN[j], 'r+', linewidth=2, markersize=12)
ANN_PID_Tuning/.ipynb_checkpoints/XOR-Net-Notebook - oprek-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 # --- # ![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) # # <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%curriculum-notebooks&branch=master&subPath=Mathematics/PiDay/pi-day.ipynb&depth=1" target="_parent"><img src="https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true" width="123" height="24" alt="Open in Callysto"/></a> # # Pi Day # <img src="images/pi.png" width="200"/> # # <center><font size="20" color="Purple">Happy Pi Day!</font></center> # ## Some Pi Facts # # Pi is represented mathematically as the symbol $\pi$ and is **the circumference divided by the diameter of a circle**. # # <img src="images/pi_calculation.png" width="400"> # # <center>[Source](https://www.mathsisfun.com/numbers/pi.html)</center> # # # The symbol for Pi ($\pi$) was introduced by **[<NAME>](https://www.historytoday.com/archive/william-jones-and-his-circle-man-who-invented-pi)** in 1706. Before being ascribed a modern name, Pi was known as "quantitas in quam cum multiflicetur diameter, proveniet circumferencia" — Latin for “the quantity which, when the diameter is multiplied by it, yields the circumference.” # # Pi is an irrational number - **its digits never end or repeat in any known way**. # # # It's believed that human civilizations were aware of Pi [as early as 2550 BC](https://www.pcworld.com/article/191389/a-brief-history-of-pi.html). # ## Why Do We Celebrate [Pi Day](https://www.exploratorium.edu/pi/pi-day-history)? # # <img src="images/PiDay.jpeg"> # # <center>[Source](https://www.exploratorium.edu/pi/pi-day-history)</center> # # March 14 is Community Pi (π) Day, the annual celebration of a never-ending number—and <NAME>’s birthday. How did Pi inspire a national holiday and an international celebration thousands of years after its discovery? It all started at San Francisco’s Exploratorium with former staff physicist, tinkerer, and media specialist <NAME> in 1988. # ## Interactive Pi Fun! # # Select the code cell below, then click the `▶Run` button in the toolbar to run this interactive Pi memory test. # # Don't worry about understanding the code, scroll down to see the resulting interactive game below. import ipywidgets as widgets from IPython.display import display, Markdown, Latex, Math, HTML, clear_output, Javascript digit_answers=[1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4,6,2,6,4,3,3,8,3,2,7,9,5,0,2,8,8,4,1,9,7,1] current_position=0 number_of_mistakes=5 number_of_mistakes_left=number_of_mistakes digit_widgets=[] for i in range(len(digit_answers)): digit_widgets.append(widgets.Text(value='',disabled=True,layout=widgets.Layout(width='3%'))) pi_real=widgets.HTMLMath(value="$$\pi=3.$$") next_number=widgets.HTML(value="Select the next digit:") answer_text=widgets.Select(options=['0','1','2','3','4','5','6','7','8','9'],value='0', description='',disabled=False,layout=widgets.Layout(width='10%')) warning=widgets.HTML(value="") mistakes=widgets.HTML(value="Mistakes left: <font color='red'>"+str(number_of_mistakes_left)+"</font>") reset_button=widgets.Button(description='Reset',disabled=False) def on_digit_selected(b): global current_position,number_of_mistakes_left if answer_text.value == str(digit_answers[current_position]): digit_widgets[current_position].value=answer_text.value current_position=current_position+1 warning.value="<font color='green'> Correct! </font>" else: warning.value="<font color='red'> Not quite... </font>" number_of_mistakes_left=number_of_mistakes_left-1 mistakes.value="Mistakes left: <font color='red'>"+str(number_of_mistakes_left)+"</font>" if number_of_mistakes_left==0 or current_position==len(digit_answers): b.disabled=True answer_text.disabled=True for i in range(len(digit_answers)): digit_widgets[i].value=str(digit_answers[i]) warning.value="<font color='red'> You scored "+str(current_position)+"! Run the code cell again to start over.</font>" answer_text.observe(on_digit_selected, names='value') display(Markdown("**How many digits of $\pi$ can you remember?**")) display(widgets.HBox([pi_real]+digit_widgets[:17])) display(widgets.HBox(digit_widgets[17:])) display(widgets.HBox([next_number,answer_text,warning])) display(widgets.HBox([mistakes])) # According to the [Guiness World Records](http://www.guinnessworldrecords.com/world-records/most-pi-places-memorised), # the most decimal places of Pi memorised is `70,000`! 😍😍😍 # >This was achieved by <NAME> at VIT University, in Vellore, India, on 21 March 2015. Rajveer wore a blindfold throughout the entire recall, which took nearly 10 hours. # # <img src="images/rajveer.png" width="500"> # # <center>[Source](http://www.guinnessworldrecords.com/world-records/most-pi-places-memorised)</center> # # #### [The Pilish Language](http://www.cadaeic.net/pilish.htm) # # <img style="float: right;" src="images/not_a_wake.png" width="150"/> # # Pilish is a language in which the lengths of successive words represent the digits of Pi (3.14159265358979...) # # One of the earliest example is the following sentence, believed to have been composed by the English physicist Sir <NAME>: # # >**How I need a drink, alcoholic in nature, after the heavy lectures involving quantum mechanics!** # # The most recent example is the [book by <NAME> "Not A Wake"](https://www.amazon.ca/dp/B0077QIOE4) (Vinculum Press, 2010): # # > **Now I fall, a tired suburbian in liquid under the trees, # > Drifting alongside forests simmering red in the twilight over Europe.** # # `▶Run` the following code cell to display an interactive Pilish writing checker. import re pi_digits=[3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4,6,2,6,4,3,3,8,3,2,7,9,5,0,2,8,8,4,1,9,7,1] text_area1=widgets.Textarea(placeholder='Type something(up to 32 words)',disabled=False,layout=widgets.Layout(height='100px')) text_area2=widgets.Textarea(disabled=True,layout=widgets.Layout(height='100px')) submit_button=widgets.Button(description='Submit',button_style='info',disabled=False) reset_button1=widgets.Button(description='Reset',disabled=False) warning1=widgets.HTML(value=" ") def on_button_reset1_clicked(b): text_area1.value="" text_area2.value="" warning1.value="" reset_button1.on_click(on_button_reset1_clicked) def on_button_submit_clicked(b): text=re.sub(r'[^\w\s]',' ',text_area1.value) text = re.sub("\d+", "", text) text_list=text.split() text_len=len(text_list) if text_len==0: text_area1.value="" warning1.value="There is no text, try again!" else: if text_len>32: text_len=32 text_list=text_list[:text_len] pi_subset=pi_digits[:text_len] text_list1=[] word_length=[] for word in text_list: lenw=len(word) word_length.append(lenw) text_list1.append(word+"("+ str(lenw)+")") if word_length==pi_subset: warning1.value=" <font color='green'> Well done! This is written in Pilish!</font>" else: warning1.value=" <font color='red'>Not quite. Your sequence is "+' '.join(str(word_length))+", it needs to be "+' '.join(str(pi_subset))+"</font>" text_area2.value=' '.join(text_list1) submit_button.on_click(on_button_submit_clicked) display(Markdown("**Can you write in Pilish?** Remember $\pi=3.1415926535897932384626433832795028841971$...")) display(Markdown("**Note**: numbers and special characters are excluded.")) vbox1=widgets.VBox([text_area1,widgets.HBox([submit_button,reset_button1])]) vbox2=widgets.VBox([text_area2,warning1]) display(widgets.HBox([vbox1,vbox2])) # #### Calculating Pi with Darts # # `▶Run` the following code cell to display a video about this. # + active="" # from IPython.display import YouTubeVideo # YouTubeVideo('M34TO71SKGk') # + language="html" # <iframe width="560" height="315" src="https://www.youtube.com/embed/M34TO71SKGk" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> # - # **Throwing Darts at a Target (Dart Board) Explainer**: # - The square that surrounds the dart board has sides of 1 unit in length and the circle (dart board) inside of the square has a diameter of 1 unit. # # - The number of darts that land in the circle divided by the number of darts in the entire square should be proportional to the area of the circle divided by the area of the square: # $$\frac{n \mspace{3mu} circle}{n \mspace{3mu} square}\propto\frac{A \mspace{3mu} circle}{A \mspace{3mu} square}$$ # # - The area of the square is 1 (length = 1), and area of the circle is $\pi\times r^{2}$, where $r$ (radius) is 0.5: # $$\frac{n \mspace{3mu} circle}{n \mspace{3mu} square}\propto\pi\times r^{2}=\pi\times 0.5^{2}=\frac{\pi}{4}$$ # # - So we can get Pi by multiplying both parts by 4: # # $$\pi\approx\frac{n \mspace{3mu} circle}{n \mspace{3mu} square}\times4$$ # # **Try it yourself!** # # `▶Run` the code cell to plot random darts and calculate an approximation of π. You can change the value of `number_of_darts` to see what effect that has. # + number_of_darts = 1000 import matplotlib.pyplot as plt # %matplotlib inline import random circle_centerx=circle_centery=circle_radius=0.5 x_inside=[] y_inside=[] x_outside=[] y_outside=[] for i in range(number_of_darts): x=random.random() y=random.random() if (x-circle_centerx)**2+(y-circle_centery)**2<circle_radius**2: x_inside.append(x) y_inside.append(y) else: x_outside.append(x) y_outside.append(y) circle2 = plt.Circle((circle_centerx, circle_centery), circle_radius,color='b',fill=False) fig, ax = plt.subplots(figsize=(10,10)) ax.plot(x_inside,y_inside, 'o', color='y',alpha=0.4) ax.plot(x_outside,y_outside, 'o', color='r',alpha=0.4) ax.add_artist(circle2) plt.ylim(0, 1) plt.xlim(0, 1) plt.show() print("Number of darts inside the circle: "+str(len(x_inside))) print("Total number of darts: "+str(number_of_darts)) print("Estimated π = ("+str(len(x_inside))+"/"+str(number_of_darts)+")×4 = "+str(len(x_inside)*4/number_of_darts)) # - # #### [Calculating Pi ](http://www.mathscareers.org.uk/article/calculating-pi/) # # There are exact formulas for calculating Pi but in order to so requires you to do something an **infinite** number of times. # # One of the most well known ways to calculate Pi is to use the **Gregory-Leibniz Series**: # # $$\pi=\frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\frac{4}{9}-...$$ # # The problem with this series is that you need to add up a lot of terms in order to get an accurate approximation of Pi. (More than 300 terms need to be added in order to produce Pi accurate to two decimal places!) # # Another series which converges more quickly is the **Nilakantha Series** which was developed around 1500 AD (This means that you need to work out fewer terms for your answer to become closer to Pi): # # $$\pi=3+\frac{4}{2\times3\times4}-\frac{4}{4\times5\times6}+\frac{4}{6\times7\times8}-\frac{4}{8\times9\times10}+...$$ # # We can compare these two ways of calculating Pi by plotting each series. # # `▶Run` the code cell to generate the plots. series_l_x=[0] series_l_y=[4] series_n_x=[0] series_n_y=[3] ans = 3 j = 2 ans1 = 4 j1 = 3 for step in range(1,50): series_l_x.append(step) series_n_x.append(step) if step % 2 == 1: ans += 4.0 / (j * (j + 1) * (j + 2)) ans1 -= 4.0 / j1 else: ans -= 4.0 / (j * (j + 1) * (j + 2)) ans1 += 4.0 / j1 ans=round(ans,15) ans1=round(ans1,15) series_n_y.append(ans) series_l_y.append(ans1) j += 2 j1 += 2 fig = plt.figure(figsize=(17,7)) plt.scatter(series_n_x,series_n_y) plt.plot(series_n_x,series_n_y,label='Nilakantha Series') plt.scatter(series_l_x,series_l_y, color="r") plt.plot(series_l_x,series_l_y,color="r", label="Gregory-Leibniz Series") plt.title("Calculating Pi - Infinite Series") plt.ylabel('Estimated Pi') plt.xlabel('Number of Elements') plt.grid() plt.legend() plt.show() # We can see that the Gregory-Leibniz Series shows more variablility than the Nilakantha Series, particularly for smaller numbers of elements. However they do start to converge as the number of elements increases. # # #### [History of Calculating Pi ](https://www.piday.org/pi-facts/) # # - In around 250 BC, [Archimedes](http://www.ams.org/publicoutreach/math-history/hap-6-pi.pdf) presented what is thought to be the first rigourous calculation of Pi, using fractions, where $3.1408 < π < 3.14285$. # # - In 1600, [<NAME>](http://www.mathscareers.org.uk/article/celebrating-pi-day-ludolph-van-ceulen/) produced a **35 digit** approximation of Pi and took 25 years of calculations which were done by hand. Ludolph’s achievement was so great that when he died, his upper and lower bounds for Pi were inscribed on his tombstone. # # - By 1665, <NAME> calculated Pi to **16 decimal places**. # # - It was in the early 1700s that <NAME> calculated **127 decimal places** of Pi reaching a new record. # # - In the second half of the twentieth century, the number of digits of Pi increased from about 2000 to **500,000**. # # - In 2017 a Swiss scientist [<NAME>](https://pi2e.ch) computed more than **22 trillion digits** of Pi, which stood as the record until... # # - The record for calculating Pi was set by [<NAME>](https://blog.google/products/google-cloud/most-calculated-digits-pi/) in 2019, who computed Pi to 31,415,926,535,897 digits in 121 days using cloud computing infrastructure! # # #### More Pi History # - [A Brief History of Pi](https://www.pcworld.com/article/191389/a-brief-history-of-pi.html) # ![](https://raw.githubusercontent.com/callysto/callysto-sample-notebooks/master/notebooks/images/Callysto_Notebook-Banners_Bottom_06.06.18.jpg) # [![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
_build/html/_sources/curriculum-notebooks/Mathematics/PiDay/pi-day.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernel_info: # name: python3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib inline from matplotlib import style style.use('fivethirtyeight') import matplotlib.pyplot as plt from sqlalchemy import create_engine, inspect, func import numpy as np import pandas as pd import datetime # # Reflect Tables into SQLAlchemy ORM # Python SQL toolkit and Object Relational Mapper import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func engine = create_engine("sqlite:///Resources/hawaii.sqlite") # + # reflect an existing database into a new model Base = automap_base() Base.prepare(engine, reflect=True) # reflect the tables # # ????? # - # We can view all of the classes that automap found Base.classes.keys() # Save references to each table Station = Base.classes.station Measurement = Base.classes.measurement # Create our session (link) from Python to the DB session = Session(engine) # # Exploratory Climate Analysis # + # Design a query to retrieve the last 12 months of precipitation data and plot the results # Calculate the date 1 year ago from the last data point in the database last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() earliest_date = datetime.datetime.strptime(last_date.date, '%Y-%m-%d') earliest_date = earliest_date - datetime.timedelta(days=365) # Perform a query to retrieve the data and precipitation scores precip = pd.DataFrame(session.query(Measurement.date, Measurement.prcp).filter(Measurement.date >= earliest_date)).dropna() #.filter(Measurement.prcp > 0)) # Save the query results as a Pandas DataFrame and set the index to the date column precip = precip.set_index('date') precip = precip.groupby('date').max() # Sort the dataframe by date precip = precip.sort_index(ascending=True) #print(precip) # + # Use Pandas Plotting with Matplotlib to plot the data precip.plot(kind="bar",legend = True, width = 4.5,figsize=(15,7)) plt.xlabel("Date") plt.ylabel("Inches") plt.xticks([]) plt.savefig('precip.png') plt.show() # Print Summary Statistics print(precip['prcp'].mean()) print(precip['prcp'].median()) print(precip['prcp'].mode()) # - # Design a query to show how many stations are available in this dataset? session.query(Station.station).count() # + # Join data into single dataframe station_measure_df = pd.DataFrame(session.query(Measurement.station, Measurement.date,Measurement.prcp,Measurement.tobs, Station.name,Station.latitude,Station.longitude,Station.elevation) .filter(Measurement.station == Station.station)).dropna() # What are the most active stations? (i.e. what stations have the most rows)? # List the stations and the counts in descending order. station_measure_count = station_measure_df.groupby("station", as_index=False).count() station_measure_count = station_measure_count.sort_values('name', ascending=False) station_measure_count.rename(columns = {'name':'count'}, inplace = True) station_measure_count[['station','count']] # - # Using the station id from the previous query, calculate the lowest temperature recorded, # highest temperature recorded, and average temperature of the most active station? print(station_measure_df[station_measure_df["station"]=="USC00519281"].tobs.min()) print(station_measure_df[station_measure_df["station"]=="USC00519281"].tobs.max()) print(station_measure_df[station_measure_df["station"]=="USC00519281"].tobs.mean()) # + # Choose the station with the highest number of temperature observations. # Query the last 12 months of temperature observation data for this station and plot the results as a histogram # Perform a query to retrieve the data and tobs scores temp_last_date = session.query(Measurement.date).filter(Measurement.station == "USC00519281").order_by(Measurement.date.desc()).first() temp_earliest_date = datetime.datetime.strptime(temp_last_date.date, '%Y-%m-%d') temp_earliest_date = temp_earliest_date - datetime.timedelta(days=365) temp = pd.DataFrame(session.query(Measurement.tobs).filter(Measurement.station == "USC00519281").filter(Measurement.date >= temp_earliest_date)) # + # Create Histogram temp.plot(kind="hist",legend = True, width = 4.5,figsize=(15,7)) plt.xlabel("Temperature") plt.ylabel("Frequency") # Save Histrogram plt.savefig('temp.png') #plt.show() # - # ## Bonus Challenge Assignment # + # This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d' # and return the minimum, average, and maximum temperatures for that range of dates def calc_temps(start_date, end_date): """TMIN, TAVG, and TMAX for a list of dates. Args: start_date (string): A date string in the format %Y-%m-%d end_date (string): A date string in the format %Y-%m-%d Returns: TMIN, TAVE, and TMAX """ return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() # function usage example print(calc_temps('2012-02-28', '2012-03-05')) # - # Use your previous function `calc_temps` to calculate the tmin, tavg, and tmax # for your trip using the previous year's data for those same dates. # Plot the results from your previous query as a bar chart. # Use "Trip Avg Temp" as your Title # Use the average temperature for the y value # Use the peak-to-peak (tmax-tmin) value as the y error bar (yerr) # + # Calculate the total amount of rainfall per weather station for your trip dates using the previous year's matching dates. # Sort this in descending order by precipitation amount and list the station, name, latitude, longitude, and elevation # + # Create a query that will calculate the daily normals # (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day) def daily_normals(date): """Daily Normals. Args: date (str): A date string in the format '%m-%d' Returns: A list of tuples containing the daily normals, tmin, tavg, and tmax """ sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)] return session.query(*sel).filter(func.strftime("%m-%d", Measurement.date) == date).all() daily_normals("01-01") # + # calculate the daily normals for your trip # push each tuple of calculations into a list called `normals` # Set the start and end date of the trip # Use the start and end date to create a range of dates # Stip off the year and save a list of %m-%d strings # Loop through the list of %m-%d strings and calculate the normals for each date # - # Load the previous query results into a Pandas DataFrame and add the `trip_dates` range as the `date` index # Plot the daily normals as an area plot with `stacked=False`
climate_starter.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Cartographic Visualization # # _“The making of maps is one of humanity's longest established intellectual endeavors and also one of its most complex, with scientific theory, graphical representation, geographical facts, and practical considerations blended together in an unending variety of ways.”_ &mdash; [<NAME>](https://books.google.com/books?id=cVy1Ms43fFYC) # # Cartography &ndash; the study and practice of map-making &ndash; has a rich history spanning centuries of discovery and design. Cartographic visualization leverages mapping techniques to convey data containing spatial information, such as locations, routes, or trajectories on the surface of the Earth. # # <div style="float: right; margin-left: 1em; margin-top: 1em;"><img width="300px" src="https://gist.githubusercontent.com/jheer/c90d582ef5322582cf4960ec7689f6f6/raw/8dc92382a837ccc34c076f4ce7dd864e7893324a/latlon.png" /></div> # # Approximating the Earth as a sphere, we can denote positions using a spherical coordinate system of _latitude_ (angle in degrees north or south of the _equator_) and _longitude_ (angle in degrees specifying east-west position). In this system, a _parallel_ is a circle of constant latitude and a _meridian_ is a circle of constant longitude. The [_prime meridian_](https://en.wikipedia.org/wiki/Prime_meridian) lies at 0° longitude and by convention is defined to pass through the Royal Observatory in Greenwich, England. # # To "flatten" a three-dimensional sphere on to a two-dimensional plane, we must apply a [projection](https://en.wikipedia.org/wiki/Map_projection) that maps (`longitude`, `latitude`) pairs to (`x`, `y`) coordinates. Similar to [scales](https://github.com/uwdata/visualization-curriculum/blob/master/altair_scales_axes_legends.ipynb), projections map from a data domain (spatial position) to a visual range (pixel position). However, the scale mappings we've seen thus far accept a one-dimensional domain, whereas map projections are inherently two-dimensional. # # In this notebook, we will introduce the basics of creating maps and visualizing spatial data with Altair, including: # # - Data formats for representing geographic features, # - Geo-visualization techniques such as point, symbol, and choropleth maps, and # - A review of common cartographic projections. # # _This notebook is part of the [data visualization curriculum](https://github.com/uwdata/visualization-curriculum)._ import pandas as pd import altair as alt from vega_datasets import data # ## Geographic Data: GeoJSON and TopoJSON # Up to this point, we have worked with JSON and CSV formatted datasets that correspond to data tables made up of rows (records) and columns (fields). In order to represent geographic regions (countries, states, _etc._) and trajectories (flight paths, subway lines, _etc._), we need to expand our repertoire with additional formats designed to support rich geometries. # # [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON) models geographic features within a specialized JSON format. A GeoJSON `feature` can include geometric data &ndash; such as `longitude`, `latitude` coordinates that make up a country boundary &ndash; as well as additional data attributes. # # Here is a GeoJSON `feature` object for the boundary of the U.S. state of Colorado: # ~~~ json # { # "type": "Feature", # "id": 8, # "properties": {"name": "Colorado"}, # "geometry": { # "type": "Polygon", # "coordinates": [ # [[-106.32056285448942,40.998675790862656],[-106.19134826714341,40.99813863734313],[-105.27607827344248,40.99813863734313],[-104.9422739227986,40.99813863734313],[-104.05212898774828,41.00136155846029],[-103.57475287338661,41.00189871197981],[-103.38093099236758,41.00189871197981],[-102.65589358559272,41.00189871197981],[-102.62000064466328,41.00189871197981],[-102.052892177978,41.00189871197981],[-102.052892177978,40.74889940428302],[-102.052892177978,40.69733266640851],[-102.052892177978,40.44003613055551],[-102.052892177978,40.3492571857556],[-102.052892177978,40.00333031918079],[-102.04930288388505,39.57414465707943],[-102.04930288388505,39.56823596836465],[-102.0457135897921,39.1331416175485],[-102.0457135897921,39.0466599009048],[-102.0457135897921,38.69751011321283],[-102.0457135897921,38.61478847120581],[-102.0457135897921,38.268861604631],[-102.0457135897921,38.262415762396685],[-102.04212429569915,37.738153927339205],[-102.04212429569915,37.64415206142214],[-102.04212429569915,37.38900413964724],[-102.04212429569915,36.99365914927603],[-103.00046581851544,37.00010499151034],[-103.08660887674611,37.00010499151034],[-104.00905745863294,36.99580776335414],[-105.15404227428235,36.995270609834606],[-105.2222388620483,36.995270609834606],[-105.7175614468747,36.99580776335414],[-106.00829426840322,36.995270609834606],[-106.47490250048605,36.99365914927603],[-107.4224761410235,37.00010499151034],[-107.48349414060355,37.00010499151034],[-108.38081766383978,36.99903068447129],[-109.04483707103458,36.99903068447129],[-109.04483707103458,37.484617466122884],[-109.04124777694163,37.88049961001363],[-109.04124777694163,38.15283644441336],[-109.05919424740635,38.49983761802722],[-109.05201565922046,39.36680339854235],[-109.05201565922046,39.49786885730673],[-109.05201565922046,39.66062637372313],[-109.05201565922046,40.22248895514744],[-109.05201565922046,40.653823231326896],[-109.05201565922046,41.000287251421234],[-107.91779872584989,41.00189871197981],[-107.3183866123281,41.00297301901887],[-106.85895696843116,41.00189871197981],[-106.32056285448942,40.998675790862656]] # ] # } # } # ~~~ # The `feature` includes a `properties` object, which can include any number of data fields, plus a `geometry` object, which in this case contains a single polygon that consists of `[longitude, latitude]` coordinates for the state boundary. The coordinates continue off to the right for a while should you care to scroll... # # To learn more about the nitty-gritty details of GeoJSON, see the [official GeoJSON specification](http://geojson.org/) or read [Tom MacWright's helpful primer](https://macwright.org/2015/03/23/geojson-second-bite). # One drawback of GeoJSON as a storage format is that it can be redundant, resulting in larger file sizes. Consider: Colorado shares boundaries with six other states (seven if you include the corner touching Arizona). Instead of using separate, overlapping coordinate lists for each of those states, a more compact approach is to encode shared borders only once, representing the _topology_ of geographic regions. Fortunately, this is precisely what the [TopoJSON](https://github.com/topojson/topojson/blob/master/README.md) format does! # Let's load a TopoJSON file of world countries (at 110 meter resolution): world = data.world_110m.url world world_topo = data.world_110m() world_topo.keys() world_topo['type'] world_topo['objects'].keys() # _Inspect the `world_topo` TopoJSON dictionary object above to see its contents._ # # In the data above, the `objects` property indicates the named elements we can extract from the data: geometries for all `countries`, or a single polygon representing all `land` on Earth. Either of these can be unpacked to GeoJSON data we can then visualize. # # As TopoJSON is a specialized format, we need to instruct Altair to parse the TopoJSON format, indicating which named faeture object we wish to extract from the topology. The following code indicates that we want to extract GeoJSON features from the `world` dataset for the `countries` object: # # ~~~ js # alt.topo_feature(world, 'countries') # ~~~ # # This `alt.topo_feature` method call expands to the following Vega-Lite JSON: # # ~~~ json # { # "values": world, # "format": {"type": "topojson", "feature": "countries"} # } # ~~~ # # Now that we can load geographic data, we're ready to start making maps! # ## Geoshape Marks # To visualize geographic data, Altair provides the `geoshape` mark type. To create a basic map, we can create a `geoshape` mark and pass it our TopoJSON data, which is then unpacked into GeoJSON features, one for each country of the world: alt.Chart(alt.topo_feature(world, 'countries')).mark_geoshape() # In the example above, Altair applies a default blue color and uses a default map projection (`mercator`). We can customize the colors and boundary stroke widths using standard mark properties. Using the `project` method we can also add our own map projection: alt.Chart(alt.topo_feature(world, 'countries')).mark_geoshape( fill='#2a1d0c', stroke='#706545', strokeWidth=0.5 ).project( type='mercator' ) # By default Altair automatically adjusts the projection so that all the data fits within the width and height of the chart. We can also specify projection parameters, such as `scale` (zoom level) and `translate` (panning), to customize the projection settings. Here we adjust the `scale` and `translate` parameters to focus on Europe: alt.Chart(alt.topo_feature(world, 'countries')).mark_geoshape( fill='#2a1d0c', stroke='#706545', strokeWidth=0.5 ).project( type='mercator', scale=400, translate=[100, 550] ) # _Note how the 110m resolution of the data becomes apparent at this scale. To see more detailed coast lines and boundaries, we need an input file with more fine-grained geometries. Adjust the `scale` and `translate` parameters to focus the map on other regions!_ # So far our map shows countries only. Using the `layer` operator, we can combine multiple map elements. Altair includes _data generators_ we can use to create data for additional map layers: # # - The sphere generator (`{'sphere': True}`) provides a GeoJSON representation of the full sphere of the Earth. We can create an additional `geoshape` mark that fills in the shape of the Earth as a background layer. # - The graticule generator (`{'graticule': ...}`) creates a GeoJSON feature representing a _graticule_: a grid formed by lines of latitude and longitude. The default graticule has meridians and parallels every 10° between ±80° latitude. For the polar regions, there are meridians every 90°. These settings can be customized using the `stepMinor` and `stepMajor` properties. # # Let's layer sphere, graticule, and country marks into a reusable map specification: map = alt.layer( # use the sphere of the Earth as the base layer alt.Chart({'sphere': True}).mark_geoshape( fill='#e6f3ff' ), # add a graticule for geographic reference lines alt.Chart({'graticule': True}).mark_geoshape( stroke='#ffffff', strokeWidth=1 ), # and then the countries of the world alt.Chart(alt.topo_feature(world, 'countries')).mark_geoshape( fill='#2a1d0c', stroke='#706545', strokeWidth=0.5 ) ).properties( width=600, height=400 ) # We can extend the map with a desired projection and draw the result. Here we apply a [Natural Earth projection](https://en.wikipedia.org/wiki/Natural_Earth_projection). The _sphere_ layer provides the light blue background; the _graticule_ layer provides the white geographic reference lines. map.project( type='naturalEarth1', scale=110, translate=[300, 200] ).configure_view(stroke=None) # ## Point Maps # # In addition to the _geometric_ data provided by GeoJSON or TopoJSON files, many tabular datasets include geographic information in the form of fields for `longitude` and `latitude` coordinates, or references to geographic regions such as country names, state names, postal codes, _etc._, which can be mapped to coordinates using a [geocoding service](https://en.wikipedia.org/wiki/Geocoding). In some cases, location data is rich enough that we can see meaningful patterns by projecting the data points alone &mdash; no base map required! # # Let's look at a dataset of 5-digit zip codes in the United States, including `longitude`, `latitude` coordinates for each post office in addition to a `zip_code` field. zipcodes = data.zipcodes.url zipcodes # We can visualize each post office location using a small (1-pixel) `square` mark. However, to set the positions we do _not_ use `x` and `y` channels. _Why is that?_ # # While cartographic projections map (`longitude`, `latitude`) coordinates to (`x`, `y`) coordinates, they can do so in arbitrary ways. There is no guarantee, for example, that `longitude` → `x` and `latitude` → `y`! Instead, Altair includes special `longitude` and `latitude` encoding channels to handle geographic coordinates. These channels indicate which data fields should be mapped to `longitude` and `latitude` coordinates, and then applies a projection to map those coordinates to (`x`, `y`) positions. alt.Chart(zipcodes).mark_square( size=1, opacity=1 ).encode( longitude='longitude:Q', # apply the field named 'longitude' to the longitude channel latitude='latitude:Q' # apply the field named 'latitude' to the latitude channel ).project( type='albersUsa' ).properties( width=900, height=500 ).configure_view( stroke=None ) # _Plotting zip codes only, we can see the outline of the United States and discern meaningful patterns in the density of post offices, without a base map or additional reference elements!_ # # We use the `albersUsa` projection, which takes some liberties with the actual geometry of the Earth, with scaled versions of Alaska and Hawaii in the bottom-left corner. As we did not specify projection `scale` or `translate` parameters, Altair sets them automatically to fit the visualized data. # # We can now go on to ask more questions of our dataset. For example, is there any rhyme or reason to the allocation of zip codes? To assess this question we can add a color encoding based on the first digit of the zip code. We first add a `calculate` transform to extract the first digit, and encode the result using the color channel: alt.Chart(zipcodes).transform_calculate( digit='datum.zip_code[0]' ).mark_square( size=2, opacity=1 ).encode( longitude='longitude:Q', latitude='latitude:Q', color='digit:N' ).project( type='albersUsa' ).properties( width=900, height=500 ).configure_view( stroke=None ) # _To zoom in on a specific digit, add a filter transform to limit the data shown! Try adding an [interactive selection](https://github.com/uwdata/visualization-curriculum/blob/master/altair_interaction.ipynb) to filter to a single digit and dynamically update the map. And be sure to use strings (\`'1'\`) instead of numbers (\`1\`) when filtering digit values!_ # # (This example is inspired by <NAME>'s classic [zipdecode](https://benfry.com/zipdecode/) visualization!) # # We might further wonder what the _sequence_ of zip codes might indicate. One way to explore this question is to connect each consecutive zip code using a `line` mark, as done in <NAME>'s [ZipScribble](https://eagereyes.org/zipscribble-maps/united-states) visualization: alt.Chart(zipcodes).transform_filter( '-150 < datum.longitude && 22 < datum.latitude && datum.latitude < 55' ).transform_calculate( digit='datum.zip_code[0]' ).mark_line( strokeWidth=0.5 ).encode( longitude='longitude:Q', latitude='latitude:Q', color='digit:N', order='zip_code:O' ).project( type='albersUsa' ).properties( width=900, height=500 ).configure_view( stroke=None ) # _We can now see how zip codes further cluster into smaller areas, indicating a hierarchical allocation of codes by location, but with some notable variability within local clusters._ # # If you were paying careful attention to our earlier maps, you may have noticed that there are zip codes being plotted in the upper-left corner! These correspond to locations such as Puerto Rico or American Samoa, which contain U.S. zip codes but are mapped to `null` coordinates (`0`, `0`) by the `albersUsa` projection. In addition, Alaska and Hawaii can complicate our view of the connecting line segments. In response, the code above includes an additional filter that removes points outside our chosen `longitude` and `latitude` spans. # # _Remove the filter above to see what happens!_ # ## Symbol Maps # Now let's combine a base map and plotted data as separate layers. We'll examine the U.S. commercial flight network, considering both airports and flight routes. To do so, we'll need three datasets. # For our base map, we'll use a TopoJSON file for the United States at 10m resolution, containing features for `states` or `counties`: usa = data.us_10m.url usa # For the airports, we will use a dataset with fields for the `longitude` and `latitude` coordinates of each airport as well as the `iata` airport code &mdash; for example, `'SEA'` for [Seattle-Tacoma International Airport](https://en.wikipedia.org/wiki/Seattle%E2%80%93Tacoma_International_Airport). airports = data.airports.url airports # Finally, we will use a dataset of flight routes, which contains `origin` and `destination` fields with the IATA codes for the corresponding airports: flights = data.flights_airport.url flights # Let's start by creating a base map using the `albersUsa` projection, and add a layer that plots `circle` marks for each airport: alt.layer( alt.Chart(alt.topo_feature(usa, 'states')).mark_geoshape( fill='#ddd', stroke='#fff', strokeWidth=1 ), alt.Chart(airports).mark_circle(size=9).encode( latitude='latitude:Q', longitude='longitude:Q', tooltip='iata:N' ) ).project( type='albersUsa' ).properties( width=900, height=500 ).configure_view( stroke=None ) # _That's a lot of airports! Obviously, not all of them are major hubs._ # # Similar to our zip codes dataset, our airport data includes points that lie outside the continental United States. So we again see points in the upper-left corner. We might want to filter these points, but to do so we first need to know more about them. # # _Update the map projection above to `albers` &ndash; side-stepping the idiosyncratic behavior of `albersUsa` &ndash; so that the actual locations of these additional points is revealed!_ # # Now, instead of showing all airports in an undifferentiated fashion, let's identify major hubs by considering the total number of routes that originate at each airport. We'll use the `routes` dataset as our primary data source: it contains a list of flight routes that we can aggregate to count the number of routes for each `origin` airport. # # However, the `routes` dataset does not include the _locations_ of the airports! To augment the `routes` data with locations, we need a new data transformation: `lookup`. The `lookup` transform takes a field value in a primary dataset and uses it as a _key_ to look up related information in another table. In this case, we want to match the `origin` airport code in our `routes` dataset against the `iata` field of the `airports` dataset, then extract the corresponding `latitude` and `longitude` fields. alt.layer( alt.Chart(alt.topo_feature(usa, 'states')).mark_geoshape( fill='#ddd', stroke='#fff', strokeWidth=1 ), alt.Chart(flights).mark_circle().transform_aggregate( groupby=['origin'], routes='count()' ).transform_lookup( lookup='origin', from_=alt.LookupData(data=airports, key='iata', fields=['state', 'latitude', 'longitude']) ).transform_filter( 'datum.state !== "PR" && datum.state !== "VI"' ).encode( latitude='latitude:Q', longitude='longitude:Q', tooltip=['origin:N', 'routes:Q'], size=alt.Size('routes:Q', scale=alt.Scale(range=[0, 1000]), legend=None), order=alt.Order('routes:Q', sort='descending') ) ).project( type='albersUsa' ).properties( width=900, height=500 ).configure_view( stroke=None ) # _Which U.S. airports have the highest number of outgoing routes?_ # # Now that we can see the airports, which may wish to interact with them to better understand the structure of the air traffic network. We can add a `rule` mark layer to represent paths from `origin` airports to `destination` airports, which requires two `lookup` transforms to retreive coordinates for each end point. In addition, we can use a `single` selection to filter these routes, such that only the routes originating at the currently selected airport are shown. # # _Starting from the static map above, can you build an interactive version? Feel free to skip the code below to engage with the interactive map first, and think through how you might build it on your own!_ # + # interactive selection for origin airport # select nearest airport to mouse cursor origin = alt.selection_single( on='mouseover', nearest=True, fields=['origin'], empty='none' ) # shared data reference for lookup transforms foreign = alt.LookupData(data=airports, key='iata', fields=['latitude', 'longitude']) alt.layer( # base map of the United States alt.Chart(alt.topo_feature(usa, 'states')).mark_geoshape( fill='#ddd', stroke='#fff', strokeWidth=1 ), # route lines from selected origin airport to destination airports alt.Chart(flights).mark_rule( color='#000', opacity=0.35 ).transform_filter( origin # filter to selected origin only ).transform_lookup( lookup='origin', from_=foreign # origin lat/lon ).transform_lookup( lookup='destination', from_=foreign, as_=['lat2', 'lon2'] # dest lat/lon ).encode( latitude='latitude:Q', longitude='longitude:Q', latitude2='lat2', longitude2='lon2', ), # size airports by number of outgoing routes # 1. aggregate flights-airport data set # 2. lookup location data from airports data set # 3. remove Puerto Rico (PR) and Virgin Islands (VI) alt.Chart(flights).mark_circle().transform_aggregate( groupby=['origin'], routes='count()' ).transform_lookup( lookup='origin', from_=alt.LookupData(data=airports, key='iata', fields=['state', 'latitude', 'longitude']) ).transform_filter( 'datum.state !== "PR" && datum.state !== "VI"' ).add_selection( origin ).encode( latitude='latitude:Q', longitude='longitude:Q', tooltip=['origin:N', 'routes:Q'], size=alt.Size('routes:Q', scale=alt.Scale(range=[0, 1000]), legend=None), order=alt.Order('routes:Q', sort='descending') # place smaller circles on top ) ).project( type='albersUsa' ).properties( width=900, height=500 ).configure_view( stroke=None ) # - # _Mouseover the map to probe the flight network!_ # ## Choropleth Maps # A [choropleth map](https://en.wikipedia.org/wiki/Choropleth_map) uses shaded or textured regions to visualize data values. Sized symbol maps are often more accurate to read, as people tend to be better at estimating proportional differences between the area of circles than between color shades. Nevertheless, choropleth maps are popular in practice and particularly useful when too many symbols become perceptually overwhelming. # # For example, while the United States only has 50 states, it has thousands of counties within those states. Let's build a choropleth map of the unemployment rate per county, back in the recession year of 2008. In some cases, input GeoJSON or TopoJSON files might include statistical data that we can directly visualize. In this case, however, we have two files: our TopoJSON file that includes county boundary features (`usa`), and a separate text file that contains unemployment statistics: unemp = data.unemployment.url unemp # To integrate our data sources, we will again need to use the `lookup` transform, augmenting our TopoJSON-based `geoshape` data with unemployment rates. We can then create a map that includes a `color` encoding for the looked-up `rate` field. alt.Chart(alt.topo_feature(usa, 'counties')).mark_geoshape( stroke='#aaa', strokeWidth=0.25 ).transform_lookup( lookup='id', from_=alt.LookupData(data=unemp, key='id', fields=['rate']) ).encode( alt.Color('rate:Q', scale=alt.Scale(domain=[0, 0.3], clamp=True), legend=alt.Legend(format='%')), alt.Tooltip('rate:Q', format='.0%') ).project( type='albersUsa' ).properties( width=900, height=500 ).configure_view( stroke=None ) # *Examine the unemployment rates by county. Higher values in Michigan may relate to the automotive industry. Counties in the [Great Plains](https://en.wikipedia.org/wiki/Great_Plains) and Mountain states exhibit both low **and** high rates. Is this variation meaningful, or is it possibly an [artifact of lower sample sizes](https://medium.com/@uwdata/surprise-maps-showing-the-unexpected-e92b67398865)? To explore further, try changing the upper scale domain (e.g., to `0.2`) to adjust the color mapping.* # # A central concern for choropleth maps is the choice of colors. Above, we use Altair's default `'yellowgreenblue'` scheme for heatmaps. Below we compare other schemes, including a _single-hue sequential_ scheme (`teals`) that varies in luminance only, a _multi-hue sequential_ scheme (`viridis`) that ramps in both luminance and hue, and a _diverging_ scheme (`blueorange`) that uses a white mid-point: # + # utility function to generate a map specification for a provided color scheme def map_(scheme): return alt.Chart().mark_geoshape().project(type='albersUsa').encode( alt.Color('rate:Q', scale=alt.Scale(scheme=scheme), legend=None) ).properties(width=305, height=200) alt.hconcat( map_('tealblues'), map_('viridis'), map_('blueorange'), data=alt.topo_feature(usa, 'counties') ).transform_lookup( lookup='id', from_=alt.LookupData(data=unemp, key='id', fields=['rate']) ).configure_view( stroke=None ).resolve_scale( color='independent' ) # - # _Which color schemes do you find to be more effective? Why might that be? Modify the maps above to use other available schemes, as described in the [Vega Color Schemes documentation](https://vega.github.io/vega/docs/schemes/)._ # ## Cartographic Projections # Now that we have some experience creating maps, let's take a closer look at cartographic projections. As explained by [Wikipedia](https://en.wikipedia.org/wiki/Map_projection), # # > _All map projections necessarily distort the surface in some fashion. Depending on the purpose of the map, some distortions are acceptable and others are not; therefore, different map projections exist in order to preserve some properties of the sphere-like body at the expense of other properties._ # # Some of the properties we might wish to consider include: # # - _Area_: Does the projection distort region sizes? # - _Bearing_: Does a straight line correspond to a constant direction of travel? # - _Distance_: Do lines of equal length correspond to equal distances on the globe? # - _Shape_: Does the projection preserve spatial relations (angles) between points? # # Selecting an appropriate projection thus depends on the use case for the map. For example, if we are assessing land use and the extent of land matters, we might choose an area-preserving projection. If we want to visualize shockwaves emanating from an earthquake, we might focus the map on the quake's epicenter and preserve distances outward from that point. Or, if we wish to aid navigation, the preservation of bearing and shape may be more important. # # We can also characterize projections in terms of the _projection surface_. Cylindrical projections, for example, project surface points of the sphere onto a surrounding cylinder; the "unrolled" cylinder then provides our map. As we further describe below, we might alternatively project onto the surface of a cone (conic projections) or directly onto a flat plane (azimuthal projections). # # *Let's first build up our intuition by interacting with a variety of projections! **[Open the online Vega-Lite Cartographic Projections notebook](https://observablehq.com/@vega/vega-lite-cartographic-projections).** Use the controls on that page to select a projection and explore projection parameters, such as the `scale` (zooming) and x/y translation (panning). The rotation ([yaw, pitch, roll](https://en.wikipedia.org/wiki/Aircraft_principal_axes)) controls determine the orientation of the globe relative to the surface being projected upon.* # ### A Tour of Specific Projection Types # [**Cylindrical projections**]() map the sphere onto a surrounding cylinder, then unroll the cylinder. If the major axis of the cylinder is oriented north-south, meridians are mapped to straight lines. [Pseudo-cylindrical](https://en.wikipedia.org/wiki/Map_projection#Pseudocylindrical) projections represent a central meridian as a straight line, with other meridians "bending" away from the center. minimap = map.properties(width=225, height=225) alt.hconcat( minimap.project(type='equirectangular').properties(title='equirectangular'), minimap.project(type='mercator').properties(title='mercator'), minimap.project(type='transverseMercator').properties(title='transverseMercator'), minimap.project(type='naturalEarth1').properties(title='naturalEarth1') ).properties(spacing=10).configure_view(stroke=None) # - [Equirectangular](https://en.wikipedia.org/wiki/Equirectangular_projection) (`equirectangular`): Scale `lat`, `lon` coordinate values directly. # - [Mercator](https://en.wikipedia.org/wiki/Mercator_projection) (`mercator`): Project onto a cylinder, using `lon` directly, but subjecting `lat` to a non-linear transformation. Straight lines preserve constant compass bearings ([rhumb lines](https://en.wikipedia.org/wiki/Rhumb_line)), making this projection well-suited to navigation. However, areas in the far north or south can be greatly distorted. # - [Transverse Mercator](https://en.wikipedia.org/wiki/Transverse_Mercator_projection) (`transverseMercator`): A mercator projection, but with the bounding cylinder rotated to a transverse axis. Whereas the standard Mercator projection has highest accuracy along the equator, the Transverse Mercator projection is most accurate along the central meridian. # - [Natural Earth](https://en.wikipedia.org/wiki/Natural_Earth_projection) (`naturalEarth1`): A pseudo-cylindrical projection designed for showing the whole Earth in one view. # <br/><br/> # [**Conic projections**](https://en.wikipedia.org/wiki/Map_projection#Conic) map the sphere onto a cone, and then unroll the cone on to the plane. Conic projections are configured by two _standard parallels_, which determine where the cone intersects the globe. minimap = map.properties(width=180, height=130) alt.hconcat( minimap.project(type='conicEqualArea').properties(title='conicEqualArea'), minimap.project(type='conicEquidistant').properties(title='conicEquidistant'), minimap.project(type='conicConformal', scale=35, translate=[90,65]).properties(title='conicConformal'), minimap.project(type='albers').properties(title='albers'), minimap.project(type='albersUsa').properties(title='albersUsa') ).properties(spacing=10).configure_view(stroke=None) # - [Conic Equal Area](https://en.wikipedia.org/wiki/Albers_projection) (`conicEqualArea`): Area-preserving conic projection. Shape and distance are not preserved, but roughly accurate within standard parallels. # - [Conic Equidistant](https://en.wikipedia.org/wiki/Equidistant_conic_projection) (`conicEquidistant`): Conic projection that preserves distance along the meridians and standard parallels. # - [Conic Conformal](https://en.wikipedia.org/wiki/Lambert_conformal_conic_projection) (`conicConformal`): Conic projection that preserves shape (local angles), but not area or distance. # - [Albers](https://en.wikipedia.org/wiki/Albers_projection) (`albers`): A variant of the conic equal area projection with standard parallels optimized for creating maps of the United States. # - [Albers USA](https://en.wikipedia.org/wiki/Albers_projection) (`albersUsa`): A hybrid projection for the 50 states of the United States of America. This projection stitches together three Albers projections with different parameters for the continental U.S., Alaska, and Hawaii. # <br/><br/> # [**Azimuthal projections**](https://en.wikipedia.org/wiki/Map_projection#Azimuthal_%28projections_onto_a_plane%29) map the sphere directly onto a plane. minimap = map.properties(width=180, height=180) alt.hconcat( minimap.project(type='azimuthalEqualArea').properties(title='azimuthalEqualArea'), minimap.project(type='azimuthalEquidistant').properties(title='azimuthalEquidistant'), minimap.project(type='orthographic').properties(title='orthographic'), minimap.project(type='stereographic').properties(title='stereographic'), minimap.project(type='gnomonic').properties(title='gnomonic') ).properties(spacing=10).configure_view(stroke=None) # - [Azimuthal Equal Area](https://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection) (`azimuthalEqualArea`): Accurately projects area in all parts of the globe, but does not preserve shape (local angles). # - [Azimuthal Equidistant](https://en.wikipedia.org/wiki/Azimuthal_equidistant_projection) (`azimuthalEquidistant`): Preserves proportional distance from the projection center to all other points on the globe. # - [Orthographic](https://en.wikipedia.org/wiki/Orthographic_projection_in_cartography) (`orthographic`): Projects a visible hemisphere onto a distant plane. Approximately matches a view of the Earth from outer space. # - [Stereographic](https://en.wikipedia.org/wiki/Stereographic_projection) (`stereographic`): Preserves shape, but not area or distance. # - [Gnomonic](https://en.wikipedia.org/wiki/Gnomonic_projection) (`gnomonic`): Projects the surface of the sphere directly onto a tangent plane. [Great circles](https://en.wikipedia.org/wiki/Great_circle) around the Earth are projected to straight lines, showing the shortest path between points. # <br/><br/> # ## Coda: Wrangling Geographic Data # The examples above all draw from the vega-datasets collection, including geometric (TopoJSON) and tabular (airports, unemployment rates) data. A common challenge to getting starting with geographic visualization is collecting the necessary data for your task. A number of data providers abound, including services such as the [United States Geological Survey](https://www.usgs.gov/products/data-and-tools/data-and-tools-topics) and [U.S. Census Bureau](https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html). # # In many cases you may have existing data with a geographic component, but require additional measures or geometry. To help you get started, here is one workflow: # # 1. Visit [Natural Earth Data](http://www.naturalearthdata.com/downloads/) and browse to select data for regions and resolutions of interest. Download the corresponding zip file(s). # 2. Go to [MapShaper](https://mapshaper.org/) and drop your downloaded zip file onto the page. Revise the data as desired, and then "Export" generated TopoJSON or GeoJSON files. # 3. Load the exported data from MapShaper for use with Altair! # # Of course, many other tools &ndash; both open-source and proprietary &ndash; exist for working with geographic data. For more about geo-data wrangling and map creation, see Mike Bostock's tutorial series on [Command-Line Cartography](https://medium.com/@mbostock/command-line-cartography-part-1-897aa8f8ca2c). # ## Summary # # At this point, we've only dipped our toes into the waters of map-making. _(You didn't expect a single notebook to impart centuries of learning, did you?)_ For example, we left untouched topics such as [_cartograms_](https://en.wikipedia.org/wiki/Cartogram) and conveying [_topography_](https://en.wikipedia.org/wiki/Topography) &mdash; as in Imhof's illuminating book [_Cartographic Relief Presentation_](https://books.google.com/books?id=cVy1Ms43fFYC). Nevertheless, you should now be well-equipped to create a rich array of geo-visualizations. For more, MacEachren's book [_How Maps Work: Representation, Visualization, and Design_](https://books.google.com/books?id=xhAvN3B0CkUC) provides a valuable overview of map-making from the perspective of data visualization.
altair_cartographic.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 sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV, train_test_split, cross_val_score from sklearn.metrics import accuracy_score, recall_score, roc_auc_score, f1_score from sklearn.feature_extraction.text import TfidfVectorizer from konlpy.tag import Okt; t=Okt() import warnings warnings.filterwarnings(action='ignore') train = pd.read_csv('./new_train.csv', index_col=0) dev = pd.read_csv('../../data/dev.hate.csv') test = pd.read_csv('../../data/test.hate.no_label.csv') train.head() train.head() train = pd.concat([train, dev], axis=0) train.head() train.info() # 트레인 데이터 레이블대로 분류 none_df = train[train['label'] == 'none']['comments'] offensive_df = train[train['label'] == 'offensive']['comments'] hate_df = train[train['label'] == 'hate']['comments'] print(len(none_df), len(offensive_df), len(hate_df), "\n", "sum: {}".format(sum([len(none_df), len(offensive_df), len(hate_df)]))) # + # TfIdf 벡터라이즈 from sklearn.feature_extraction.text import TfidfVectorizer tfidf_vectorizer = TfidfVectorizer() # 훈련 데이터 전체 벡터라이즈 fit tfidf_vectorizer.fit(train['comments']) # 각각 레이블 벡터라이즈 transform none_matrix = tfidf_vectorizer.transform(none_df) offensive_matrix = tfidf_vectorizer.transform(offensive_df) hate_matrix = tfidf_vectorizer.transform(hate_df) none_matrix.shape, offensive_matrix.shape, hate_matrix.shape # + # 각각의 평균 벡터값(위치) 산출 none_vec = [] offensive_vec = [] hate_vec = [] for i in range(none_matrix.shape[1]): none_vec.append(none_matrix[:,i].mean()) for i in range(offensive_matrix.shape[1]): offensive_vec.append(offensive_matrix[:,i].mean()) for i in range(hate_matrix.shape[1]): hate_vec.append(hate_matrix[:,i].mean()) # 벡터라이즈 잘 되었는지 길이 확인 len(none_vec), len(offensive_vec), len(hate_vec) # + # 어레이 형태로 변환 none_vec = np.array(none_vec) offensive_vec = np.array(offensive_vec) hate_vec = np.array(hate_vec) # 2차원 어레이로 변환 none_vec = none_vec.reshape(1, -1) offensive_vec = offensive_vec.reshape(1, -1) hate_vec = hate_vec.reshape(1, -1) # 테스트 코멘트 벡터라이즈 적용 test_matrix = tfidf_vectorizer.transform(test['comments']) test_matrix.shape # + # 코멘트 <-> 각 레이블 간의 유사도 측정 후 가장 유사한 레이블 산출 from sklearn.metrics.pairwise import cosine_similarity preds = [] for i in range(test_matrix.shape[0]): distances = {cosine_similarity(test_matrix[i,:], none_vec)[0][0] : "none", cosine_similarity(test_matrix[i,:], offensive_vec)[0][0] : "offensive", cosine_similarity(test_matrix[i,:], hate_vec)[0][0] : "hate"} preds.append( distances[max(distances.keys())] ) preds # - test['label'] = preds test.head() def kaggle_format(df): df['label'][df['label'] == 'none'] = 0 df['label'][df['label'] == 'offensive'] = 1 df['label'][df['label'] == 'hate'] = 2 return df kaggle_format(test) test.head() test.info() test.to_csv('./0116_cos_jc.csv', index=False) pd.read_csv('./0116_cos_jc.csv') # dd
code/Jaecheol/JC_ScoreTrial-cos.ipynb
# ## Overview # # This notebook will show you how to create and query a table or DataFrame that you uploaded to DBFS. [DBFS](https://docs.databricks.com/user-guide/dbfs-databricks-file-system.html) is a Databricks File System that allows you to store data for querying inside of Databricks. This notebook assumes that you have a file already inside of DBFS that you would like to read from. # # This notebook is written in **Python** so the default cell type is Python. However, you can use different languages by using the `%LANGUAGE` syntax. Python, Scala, SQL, and R are all supported. # + # File location and type file_location = "/FileStore/tables/all_vars_for_zeroinf_analysis.csv" file_type = "csv" # CSV options infer_schema = "true" first_row_is_header = "true" delimiter = "," # The applied options are for CSV files. For other file types, these will be ignored. all_vars_for_zeroinf_analysis = spark.read.format(file_type) \ .option("inferSchema", infer_schema) \ .option("header", first_row_is_header) \ .option("sep", delimiter) \ .load(file_location) ##display(all_vars_for_zeroinf_analysis) # File location and type file_location_all_vars_for_analysis = "/FileStore/tables/all_vars_for_analysis.csv" file_type = "csv" # CSV options infer_schema = "true" first_row_is_header = "true" delimiter = "," # The applied options are for CSV files. For other file types, these will be ignored. all_vars_for_analysis = spark.read.format(file_type) \ .option("inferSchema", infer_schema) \ .option("header", first_row_is_header) \ .option("sep", delimiter) \ .load(file_location_all_vars_for_analysis) # - print(all_vars_for_analysis.count()) print (all_vars_for_analysis.printSchema()) display(all_vars_for_zeroinf_analysis.groupBy('state') .count() .orderBy('count', ascending=False))
Codes/Gathering_Data/all_vars_for_zeroinf_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.6 (tensorflow) # language: python # name: tensorflow # --- # <a href="https://colab.research.google.com/github/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_03_4_early_stop.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # # T81-558: Applications of Deep Neural Networks # **Module 3: Introduction to TensorFlow** # * Instructor: [<NAME>](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx) # * For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). # # Module 3 Material # # * Part 3.1: Deep Learning and Neural Network Introduction [[Video]](https://www.youtube.com/watch?v=zYnI4iWRmpc&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_03_1_neural_net.ipynb) # * Part 3.2: Introduction to Tensorflow and Keras [[Video]](https://www.youtube.com/watch?v=PsE73jk55cE&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_03_2_keras.ipynb) # * Part 3.3: Saving and Loading a Keras Neural Network [[Video]](https://www.youtube.com/watch?v=-9QfbGM1qGw&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_03_3_save_load.ipynb) # * **Part 3.4: Early Stopping in Keras to Prevent Overfitting** [[Video]](https://www.youtube.com/watch?v=m1LNunuI2fk&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_03_4_early_stop.ipynb) # * Part 3.5: Extracting Weights and Manual Calculation [[Video]](https://www.youtube.com/watch?v=7PWgx16kH8s&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_03_5_weights.ipynb) # # Google CoLab Instructions # # The following code ensures that Google CoLab is running the correct version of TensorFlow. try: # %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False # # Part 3.4: Early Stopping in Keras to Prevent Overfitting # **Overfitting** occurs when a neural network is trained to the point that it begins to memorize rather than generalize, as demonstrated in Figure 3.OVER. # # **Figure 3.OVER: Training vs Validation Error for Overfitting** # ![Training vs Validation Error for Overfitting](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/class_3_training_val.png "Training vs Validation Error for Overfitting") # # It is important to segment the original dataset into several datasets: # # * **Training Set** # * **Validation Set** # * **Holdout Set** # # There are several different ways that these sets can be constructed. The following programs demonstrate some of these. # # The first method is a training and validation set. The training data are used to train the neural network until the validation set no longer improves. This attempts to stop at a near optimal training point. This method will only give accurate "out of sample" predictions for the validation set, this is usually 20% or so of the data. The predictions for the training data will be overly optimistic, as these were the data that the neural network was trained on. Figure 3.VAL demonstrates how a dataset is divided. # # **Figure 3.VAL: Training with a Validation Set** # ![Training with a Validation Set](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/class_1_train_val.png "Training with a Validation Set") # ### Early Stopping with Classification # + import pandas as pd import io import requests import numpy as np from sklearn import metrics from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation from tensorflow.keras.callbacks import EarlyStopping df = pd.read_csv( "https://data.heatonresearch.com/data/t81-558/iris.csv", na_values=['NA', '?']) # Convert to numpy - Classification x = df[['sepal_l', 'sepal_w', 'petal_l', 'petal_w']].values dummies = pd.get_dummies(df['species']) # Classification species = dummies.columns y = dummies.values # Split into validation and training sets x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.25, random_state=42) # Build neural network model = Sequential() model.add(Dense(50, input_dim=x.shape[1], activation='relu')) # Hidden 1 model.add(Dense(25, activation='relu')) # Hidden 2 model.add(Dense(y.shape[1],activation='softmax')) # Output model.compile(loss='categorical_crossentropy', optimizer='adam') monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=5, verbose=1, mode='auto', restore_best_weights=True) model.fit(x_train,y_train,validation_data=(x_test,y_test), callbacks=[monitor],verbose=2,epochs=1000) # - # There are a number of parameters that are specified to the **EarlyStopping** object. # # * **min_delta** This value should be kept small. It simply means the minimum change in error to be registered as an improvement. Setting it even smaller will not likely have a great deal of impact. # * **patience** How long should the training wait for the validation error to improve? # * **verbose** How much progress information do you want? # * **mode** In general, always set this to "auto". This allows you to specify if the error should be minimized or maximized. Consider accuracy, where higher numbers are desired vs log-loss/RMSE where lower numbers are desired. # * **restore_best_weights** This should always be set to true. This restores the weights to the values they were at when the validation set is the highest. Unless you are manually tracking the weights yourself (we do not use this technique in this course), you should have Keras perform this step for you. # # As you can see from above, the entire number of requested epochs were not used. The neural network training stopped once the validation set no longer improved. # + from sklearn.metrics import accuracy_score pred = model.predict(x_test) predict_classes = np.argmax(pred,axis=1) expected_classes = np.argmax(y_test,axis=1) correct = accuracy_score(expected_classes,predict_classes) print(f"Accuracy: {correct}") # - # ### Early Stopping with Regression # # The following code demonstrates how we can apply early stopping to a regression problem. The technique is similar to the early stopping for classification code that we just saw. # + from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation import pandas as pd import io import os import requests import numpy as np from sklearn import metrics df = pd.read_csv( "https://data.heatonresearch.com/data/t81-558/auto-mpg.csv", na_values=['NA', '?']) cars = df['name'] # Handle missing value df['horsepower'] = df['horsepower'].fillna(df['horsepower'].median()) # Pandas to Numpy x = df[['cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin']].values y = df['mpg'].values # regression # Split into validation and training sets x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.25, random_state=42) # Build the neural network model = Sequential() model.add(Dense(25, input_dim=x.shape[1], activation='relu')) # Hidden 1 model.add(Dense(10, activation='relu')) # Hidden 2 model.add(Dense(1)) # Output model.compile(loss='mean_squared_error', optimizer='adam') monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=5, verbose=1, mode='auto', restore_best_weights=True) model.fit(x_train,y_train,validation_data=(x_test,y_test), callbacks=[monitor], verbose=2,epochs=1000) # - # Finally, we evaluate the error. # Measure RMSE error. RMSE is common for regression. pred = model.predict(x_test) score = np.sqrt(metrics.mean_squared_error(pred,y_test)) print(f"Final score (RMSE): {score}")
t81_558_class_03_4_early_stop.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 # --- movie = open('movies.txt',encoding="utf8", errors='ignore') context= movie.readlines() print(len(context)) movie.close() print(len(context)/9) # + productId=[] userId=[] score =[] review=[] summary = [] for i in range(len(context)): if len(context) >1: temp= context[i].split(':')[0] if temp == "product/productId" : productId.append(context[i].split(':')[1][1:len(context[i].split(':')[1])-1]) elif temp == "review/userId": userId.append(context[i].split(':')[1][0:len(context[i].split(':')[1])-1]) elif temp == "review/score" : score.append((context[i].split(':')[1][1:4])) elif temp == "review/text": review.append(context[i][13:len(context[i])-1]) elif temp == "review/summary": summary.append(context[i].split(':')[1][0:len(context[i].split(':')[1])-1]) score = [float(i) for i in score] # print(context[i]) #temp = context[i].split(':') #data[context[i].split(':')[0]]= context[i].split(':')[1:] # - print(len(review)) print(len(productId)) print(len(userId)) print(len(score)) print(len(summary)) # + import pandas as pd d = {'productId': productId, 'userId': userId, 'score': score,'summary':summary , 'review':review} df = pd.DataFrame(data=d) #df.iloc[:,2]=int(df.iloc[:,2]) # - top_ten_movies=df.groupby('productId')['productId'].count().nlargest(100) print(top_ten_movies) top_ten_movies.plot.bar(x='productId',rot=0) Five_movies=['B000H7I6CU','B004SIPA0A','B004WMKSH2', 'B001I1NGHY', 'B002LBKDYE'] new_df= df[df.productId.isin(Five_movies)] new_df.shape new_df=pd.DataFrame(data=new_df) new_df.head() dictionary_movie = {'B000H7I6CU':'Cars','B004SIPA0A':'Sin City','B004WMKSH2':'Harry Potter 7', 'B001I1NGHY':'Iron Man', 'B002LBKDYE':'Food, Inc'} new_df['movie_title'] = new_df['productId'].map(dictionary_movie) new_df.to_csv("five_movies.csv") temp=new_df.groupby('movie_title')['movie_title'].count() temp.plot.bar(x='movie_title',rot=0) temp=new_df.groupby('movie_title')['score'].mean() temp.plot.bar(x='movie_title',rot=0) # + temp=new_df[new_df['movie_title']=='Harry Potter 7'].groupby('score')['score'].count() temp.plot.bar(x='score',rot=0, title='Harry Potter and the Deathly Hallows: Part 1') # - print(temp) df.groupby('productId').productId new_df.to_csv("iron_man.csv") new_df df.to_csv("output.csv") temp=df.groupby('userId')['score'].count() temp.plot.bar(x='userId',rot=0) temp=df.groupby('productId')['score'].mean() print(temp) temp.plot.bar(x='productId',rot=0) temp=df.groupby('productId')['score'].count() temp.plot.bar(x='productId',rot=0) filepath = "temp.txt" with open(filepath) as fp: line = fp.readline() cnt = 1 while line: print("Line {}: {}".format(cnt, line.strip())) line = fp.readline() cnt += 1 with open("temp.txt") as f: content = f.readline() print(content) f = open("movies.txt", "r") content = f.read() print(content) splitcontent = content.splitlines() print(len(splitcontent)) f = open('movies.txt') for line in f: print(line) f.close() # + import numpy as np wordset = np.genfromtxt(fname='temp.txt') # - i data = pd.read_csv('movies.txt', sep="", header=None) #data.columns = ["a", "b", "c", "etc."] df=pd.read_table('movies.txt',header=None) movie=pd.read_fwf('movies.txt') with open('movies.json', 'w') as json_file: json.dump('movies.txt', json_file) # + import gzip import simplejson from tqdm import tqdm from utils import get_line_number def parse(filename, total): f = gzip.open(filename, 'r') entry = {} for l in tqdm(f, total=total): l = l.strip() colonPos = l.find(':') if colonPos == -1: yield entry entry = {} continue eName = l[:colonPos] rest = l[colonPos+2:] entry[eName] = unicode(rest, errors='ignore') yield entry if __name__ == '__main__': file_path = "data/movies.txt.gz" line_num = get_line_number(file_path) for e in parse(file_path, total=line_num): print(simplejson.dumps(e)) # - import json with open("movies.txt", "rb") as fin: content = json.load(fin) with open("stringJson.txt", "wb") as fout: json.dump(content, fout, indent=1)
Final_Project.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 print(tf.__version__) with tf.name_scope('scalar_set_one') as scope: const1 = tf.constant(1,name='one') const2 = tf.constant(2,name='two') addconst = tf.add(const1,const2,name='addtwoConstnt') print(const1) sess = tf.Session() sess.run(tf.global_variables_initializer()) tf_tensorboard_writer = tf.summary.FileWriter('./graphs', sess.graph) tf_tensorboard_writer.close() sess.close() a = tf.get_variable(name='scalar_set_one',shape=()) tf.all_variables() # + with tf.variable_scope("foo",reuse=True): bar1 = tf.get_variable("bar", (2,3)) # create print(bar1) with tf.variable_scope("foo", reuse=True): bar2 = tf.get_variable("bar") # reuse print(bar2) # with tf.variable_scope("", reuse=True): # root variable scope # bar3 = tf.get_variable("foo/bar") # reuse (equivalent to the above) # (bar1 is bar2) and (bar2 is bar3) # - # + with tf.name_scope("my_scope"): v1 = tf.get_variable("var1", [1], dtype=tf.float32) v2 = tf.Variable(1, name="var2", dtype=tf.float32) a = tf.add(v1, v2) print(v1.name) # var1:0 print(v2.name) # my_scope/var2:0 print(a.name) # my_scope/Add:0 # + with tf.variable_scope("my_scope"): v1 = tf.get_variable("var1", [1], dtype=tf.float32) v2 = tf.Variable(1, name="var2", dtype=tf.float32) a = tf.add(v1, v2) print(v1.name) # my_scope/var1:0 print(v2.name) # my_scope/var2:0 print(a.name) # my_scope/Add:0 # - # + with tf.name_scope("foo"): with tf.variable_scope("var_scope"): v = tf.get_variable("var", [1]) with tf.name_scope("bar"): with tf.variable_scope("var_scope", reuse=True): v1 = tf.get_variable("var", [1]) assert v1 == v print(v.name) # var_scope/var:0 print(v1.name) # var_scope/var:0 # -
Lectures/Lecture-08/scope.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 time import time from tensorflow.python.keras.callbacks import ModelCheckpoint, TensorBoard from tensorflow.python.keras.layers import Input, LSTM, Dense, Activation, Dropout from tensorflow.python.keras.models import Model, load_model from tensorflow.python.keras.optimizers import Nadam from tensorflow.python.keras.utils import to_categorical import numpy as np timestamp = int(time()) # - # ## Dados # Carregamos todo o texto (porque dá) e passamos para minúsculas text = open('data/casmurro.txt', encoding='utf-8').read() text = text.lower() # Detectamos os caracteres e mapeamos os índices chars = sorted(set(text)) char_to_int = {c: i for i, c in enumerate(chars)} # Geramos os exemplos "sequencia -> proxima letra" length = 32 x, y = [], [] word = text[:length] for letter in text[length:]: x.append([char_to_int[w] for w in word]) y.append(char_to_int[letter]) word = word[1:] + letter x = np.reshape(x, (-1, length, 1)) / len(chars) y = to_categorical(y, len(chars)) # Embaralhando o dataset i = np.random.permutation(x.shape[0]) x, y = x[i], y[i] # Separando treino e teste i = int(.9 * len(x)) x_train, x_test = x[:i], x[i:] y_train, y_test = y[:i], y[i:] # ## Modelo # Camada de entrada (compatível com a forma de x) out = entry = Input(shape=x_train.shape[1:]) # Camada de memória out = LSTM(32)(out) # Camada de saída com um neurônio para cada caractere e aplicação do softmax para obtermos uma distribuição de probabilidade out = Dropout(0.5)(out) out = Dense(y_train.shape[1])(out) out = Activation('softmax')(out) # Definição do modelo em si net = Model(entry, out) # Imprimimos a descrição do modelo net.summary() # ## Treinamento # Definição do custo e da otimização net.compile( loss='categorical_crossentropy', optimizer=Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-08, schedule_decay=0.004), metrics=['accuracy']) # Treinamento em si net.fit( x_train, y_train, batch_size=512, initial_epoch=10, epochs=20, validation_data=(x_test, y_test), callbacks=[ ModelCheckpoint('save/text.{epoch:02d}.h5'), TensorBoard(log_dir='logs/text_{}'.format(timestamp), histogram_freq=1)]) # ## Geração de texto # Ponto de partida net = load_model('save/text.01.h5') text = '''Era uma vez'''.lower() text = '''( function( global, factory ) { '''.lower() # Geração em si # + for _ in range(1000): word = text[-length:] x = [char_to_int[w] for w in word] x = np.reshape(x, (-1, length, 1)) / len(chars) y = net.predict(x, verbose=0)[0] char = np.random.choice(chars, p=y) # char = chars[np.argmax(y)] text += char print(text)
text.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 src="images/cat.png" width="200 px" align="right"><img src="images/qiskit.png" width="140 px" align="right"> # # Introduction to Quantum Computing with QISKit - a pratical guide # #### How to use www.qiskit.org :: An open source quantum computing framework for the development of quantum experiments and applications. # # ### Download the [slides](Slides4Lecture.pdf) that go with this course! # --- # ### Contributors: # <NAME>, <NAME>, <NAME>, and <NAME> from Department of Computer Science, University of Porto, Portugal. # # ### *Abstract* # # *Quantum computing is computing using quantum-mechanical phenomena, unlike binary digital electronic computers based on transistors. This notebook, provides an introduction to the fundamental notions of quantum mechanics and computer science techniques of the field of quantum computation and quantum information. We detail concepts of quantum mechanics on a computational basis and showcase examples using QISKit.* # # *Note: this notebook was run on 11/15/2018 at 23:15 p.m. (WET)* # ## Concepts # - What is a qubit # - What is bra-ket notation # - What is a superposition # - What is a entanglement # - What is a bloch sphere # - Measurement # - Classical vs quantum # - How do quantum algorithms work # - Quantum gates # # ### What is a qubit? # In quantum computing, a qbit or qubit or quantum bit is a unit of quantum information. In a quantum computer the basic memory units are qubits, analogously to the bits on a classical computer. A classical bit can take two distinct values, 0 or 1 at a given time. In contrast, a qubit state can be a combination of 0 and 1, called superposition where the qubit is in both basic states (0 and 1) at the same time. A qubit is a quantum system in which the Boolean states 0 and 1 are represented by a pair of normalised and mutually orthogonal quantum states. The two states form a computational basis and any other (pure) state of the qubit can be written as a linear combination, # $$|\psi\rangle = \alpha|0\rangle + \beta |1\rangle$$ # # where $\alpha$ and $\beta$ are probability amplitudes and can be complex numbers. In a measurement the probability of the bit being in $|0\rangle$ is $|\alpha|^2$ and $|1\rangle$ is $|\beta|^2$, # $$ # |\psi\rangle = # \begin{pmatrix} # \alpha \\ # \beta # \end{pmatrix}. # $$ # # Two real numbers can describe a single qubit quantum state, since global phase is undetectable and conservation probability $|\alpha|^2+ |\beta|^2 = 1$. # # ### What is bra-ket notation? # In quantum mechanics, bra-ket notation is a standard notation for representing quantum states. In order to calculate the scalar product of vectors, the notation uses angle brackets $\langle$ $\rangle$, and a vertical bar |. The scalar product is then $\langle\phi|\psi\rangle$ where the right part is the "psi ket" (a column vector) and the left part is the bra - the Hermitian transpose of the ket (a row vector). Bra-ket notation was introduced in 1939 by <NAME> and is also known as the Dirac notation. # # ### What is a superposition? # Superposition allows the qubit to be in both states at the same time, and it can be defined as a weighted combination between the basic states 0 and 1. Superposition occurs when any two (or more) quantum states are added, becoming superposed, resulting in a new quantum state - i.e. in 0 and 1 simultaneously, a linear combination of the two classical states. # # ### What is a entanglement? # An important difference between a qubit and a classical bit is that multiple qubits can exhibit quantum entanglement. It occurs when pairs or more than two particles are generated or interact in a way that the quantum state of each particle can't be described independently of the state of the other(s). # # ### What is a bloch sphere? # We can describe the states of the qubit by $|\psi\rangle = \cos(\theta/2)|0\rangle + \sin(\theta/2)e^{i\phi}|1\rangle$ # where $0\leq \phi < 2\pi$, and $0\leq \theta \leq \pi$. Qubit states ($\mathbb{C}^2$) corresponde to the points on the surface of a unit sphere ($\mathbb{R}^3$). # # <img src="images/bloch_sphere.png" width="200 px" align="left"> # ### Measurement # The system is deterministic until measurement. Afterwards, measurement provide only one state of the superposed states. The only one state become the new state and interferes with computational procedures. This state, is determined with some probability <= 1, implying uncertainty in the result states and cannot be copied ("cloned"). Also, environmental interference may cause a measurement-like state collapse (decoherence). # # ### Classical vs quantum # - Classical Logic Circuits, are governed by classical physics, where signal states are simple bit vectors, e.g. 11000101, operations are based in Boolean algebra, we can copy and measure signals freely, and we have the universal gate types, e.g. NAND, (AND, OR, NOT), (AND, NOT), etc. # - Quantum Logic Circuits, are governed by quantum mechanics, where signal states are vectors interpreted as a superposition of binary "qubit" vectors, operations are defined by linear algebra in the Hilbert space, represented by unitary matrices with complex elements, there are restrictions on copying and measuring signals, and we have many unitary operations and gates. # # ### How do quantum algorithms work? # Quantum algorithms work by applying quantum operations, called quantum logical gates, on qubits. Similar to instructions in a classical program. A quantum algorithm using gates is then a quantum circuit. # # ### Quantum gates # Quantum gates/operations are represented as matrices which act on a qubit represented by a $2\times 2$ unitary matrix $U$, in case of single qubit gates. The operation is by multiplying the matrix representing the gate with the vector that represents the quantum state. # # $$|\psi'\rangle = U|\psi\rangle$$ # # Here are the 1-qubit gates: # $$\sigma_x=\left(\begin{array}{cc}0\quad1\\1\quad0\end{array}\right)$$ # # $$\sigma_y=\left(\begin{array}{cc}0\quad-i\\i\quad0\end{array}\right)$$ # # $$\sigma_h=\left(\begin{array}{cc}1\quad0\\0\quad-1\end{array}\right)$$ # # $$H=\left(\begin{array}{cc}\frac{1}{\sqrt{2}}\quad\frac{1}{\sqrt{2}}\\\frac{1}{\sqrt{2}}\quad-\frac{1}{\sqrt{2}}\end{array}\right)$$ # # The 2-qubit gates are $4\times 4$, and 3-qubit gates $8\times 8$ matrices. An overview of the single and multiple qubit gates is described below, along with the matrix and circuit representation of each gate. # # ## Preliminaries # - IBM Q Experience device information # - What is QISKit # - Install QISKit using PIP Install Command # - Single-Qubit Gates # - Two-Qubit Gates # - Three-Qubit Gates # - Hello Quantum World program # - Quantum (not)Smiley program # # ### IBM Q Experience device information # IBM Q devices are named after IBM office locations around the globe. # - Client: IBM Q 20 Tokyo (20 qubits) # - Public devices: IBM Q 14 Melbourne (14 qubits), IBM Q 5 Tenerife (5 qubits) and IBM Q 5 Yorktown (5 qubits) # - Simulators: IBM Q QASM 32 Q Simulator (32 qubits) # # - display_name: IBM Q 5 Yorktown | backend_name: ibmqx2 | description: the connectivity is provided by two coplanar waveguide (CPW) resonators with resonances around 6.6 GHz (coupling Q2, Q3 and Q4) and 7.0 GHz (coupling Q0, Q1 and Q2). Each qubit has a dedicated CPW for control and readout (labeled as R). Chip layout and connections: # # <img src="images/yorktown.png" width="300 px" align="left"> # <img src="images/yorktown-connections.png" width="200 px" align="left"> # - display_name: IBM Q 16 Melbourne | backend_name: ibmq_16_melbourne | description: the connectivity on the device is provided by total 22 coplanar waveguide (CPW) "bus" resonators, each of which connects two qubits. Three different resonant frequencies are used for the bus resonators: 6.25 GHz, 6.45 GHz, and 6.65 GHz. Chip layout and connections: # # <img src="images/melbourne.png" width="300 px" align="left"> # <img src="images/melbourne-connections.png" width="600 px" align="left"> # To take full advantage of the connections of each different type of chip, research is being done in order to find the best coupling map using techniques and algorithms such as the Quantum Tabu Search to obtain a quantum combinatorial optimisation, suggesting that an entanglement-metaheurisc can display optimal solutions. # # <img src="images/tabuSearch.png" width="450 px" align="left"> # The algorithm main steps can be briefly described by, a) generating the neighbors, b) evaluating each neighbor and c) getting the neighbor with maximum evaluation. The algorithm stops at any iteration where there are no feasible moves into the local neighborhood of the current solution. # # ### What is QISKit? # QISKit is a software development kit (SDK) comprising of Python-based software libraries used to create quantum computing programs, compile, and execute them on one of the real quantum processors backends and simulators available in the IBM cloud. # # <img src="images/qiskit.org.png" width="600 px" align="left"> # #### What is Terra? # Qiskit Terra provides the foundational roots for our software stack. Within Terra is a set of tools for composing quantum programs at the level of circuits and pulses, optimizing them for the constraints of a particular physical quantum processor, and managing the batched execution of experiments on remote-access backends. # # <img src="images/terra.png" width="600 px" align="left"> # #### What is Aqua? # Qiskit Aqua contains a library of cross-domain quantum algorithms upon which applications for near-term quantum computing can be built. Aqua is designed to be extensible, and employs a pluggable framework where quantum algorithms can easily be added. It currently allows the user to experiment on chemistry, AI, optimization and finance applications for near-term quantum computers. # # <img src="images/aqua.png" width="600 px" align="left"> # ### Install Python PIP # Execute the following command to install QISKit: pip install qiskit # Useful packages for the next gates experiments import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit import execute from qiskit.tools.visualization import circuit_drawer from qiskit import Aer backend = Aer.get_backend('unitary_simulator') # ### Single-Qubit Gates # # - u gates # - Identity gate # - Pauli gates # - Cliffords gates # - $C3$ gates # - Standard rotation gates # # # Pauli X : bit-flip gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.x(q) im = circuit_drawer(qc) im.save("GateX.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateX.png" width="200 px" align="left"> # Pauli Y : bit and phase-flip gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.y(q) im = circuit_drawer(qc) im.save("GateY.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateY.png" width="200 px" align="left"> # Pauli Z : phase-flip gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.z(q) im = circuit_drawer(qc) im.save("GateZ.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateZ.png" width="200 px" align="left"> # Clifford Hadamard gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) im = circuit_drawer(qc) im.save("GateH.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateH.png" width="200 px" align="left"> # Clifford S gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.s(q) im = circuit_drawer(qc) im.save("GateS.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateS.png" width="200 px" align="left"> # Clifford T gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.t(q) im = circuit_drawer(qc) im.save("GateT.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateT.png" width="200 px" align="left"> # ### Two-Qubit Gates # # - controlled Pauli gates # - controlled Hadamard gate # - controlled rotation gates # - controlled phase gate # - controlled u3 gate # - swap gate # # # Pauli Controlled-X (or, controlled-NOT) gate q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q) im = circuit_drawer(qc) im.save("GateCX.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateCX.png" width="200 px" align="left"> # Pauli Controlled Z (or, controlled Phase) gate q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cz(q) im = circuit_drawer(qc) im.save("GateCZ.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateCZ.png" width="200 px" align="left"> # SWAP gate q = QuantumRegister(2) qc = QuantumCircuit(q) qc.swap(q) im = circuit_drawer(qc) im.save("GateSWAP.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateSWAP.png" width="200 px" align="left"> # ### Three-Qubit Gates # # - Toffoli gate # - Fredkin gate # # # Toffoli gate (ccx gate) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q) im = circuit_drawer(qc) im.save("GateCCX.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # <img src="images/GateCCX.png" width="200 px" align="left"> # ### Hello Quantum World program # Create and save a "Hello Quantum World" with the following code in a file such as quantumWorld.py: from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram, circuit_drawer # Create a Quantum Register called "qr" with 2 qubits. qr = QuantumRegister(2) # Create a Classical Register called "cr" with 2 bits. cr = ClassicalRegister(2) # Create a Quantum Circuit called "qc" with qr and cr. qc = QuantumCircuit(qr, cr) # Add the H gate in the Qubit 1, putting this qubit in superposition. qc.h(qr[1]) # Add the CX gate on control qubit 1 and target qubit 0, putting the qubits in a Bell state i.e entanglement. qc.cx(qr[1], qr[0]) # Add a Measure gate to see the state. qc.measure(qr, cr) # Compile and execute the quantum program in the local simulator. job_sim = execute(qc, "qasm_simulator") stats_sim = job_sim.result().get_counts() # Plot and print results. plot_histogram(stats_sim) print(stats_sim) im = circuit_drawer(qc) im.save("circuit.png", "PNG") # <img src="images/qwhist.png" width="500 px" align="left"> # {'00': 512, '11': 512} # <img src="images/qwcircuit.png" width="300 px" align="left"> # ### Quantum (not)Smiley program # Create and save a file such as quantumSmiley.py: from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram import matplotlib.pyplot as plt # 3 bitStrings, one for each symbol : )( #":" 00111010 "(" 00101000 ")" 00101001 # Create a Quantum Register called "qr" with 16 qubits. qr = QuantumRegister(16) # Create a Classical Register called "cr" with 16 bits. cr = ClassicalRegister(16) # Create a Quantum Circuit called "qc" with qr and cr. qc = QuantumCircuit(qr, cr) # Add the H gate in the 0 Qubit, putting the qubit in superposition. qc.h(qr[0]) qc.x(qr[3]) qc.x(qr[5]) qc.x(qr[9]) qc.x(qr[11]) qc.x(qr[12]) qc.x(qr[13]) for j in range(16): qc.measure(qr[j], cr[j]) # Compile and execute the quantum program in the local simulator. shots_sim = 128 job_sim = execute(qc, "qasm_simulator", shots=shots_sim) stats_sim = job_sim.result().get_counts() # Plot and print results. plot_histogram(stats_sim) print(stats_sim) def plotSmiley (stats, shots): for bitString in stats: char = chr(int(bitString[0:8],2)) # 8 bits (left), convert to an ASCII character. char += chr(int(bitString[8:16],2)) # 8 bits (right), add it to the previous character. prob = stats[bitString]/shots # Fraction of shots the result occurred plt.annotate(char, (0.5,0.5), va="center", ha="center", color = (0,0,0,prob), size = 300) # Create plot. plt.axis("off") plt.show() plotSmiley(stats_sim, shots_sim) # <img src="images/Figure_2.png" width="500 px" align="left"> # {'0011101000101000': 64, '0011101000101001': 64} # <img src="images/Figure_3.png" width="500 px" align="left"> # ## Arithmetics # - Assignment # - Sum (Binary) # - Sum (Ripple-carry adder) # - Sum (Quantum Fourier Transform) # - Average # # ### Assignment # The registers are made of qubits, therefore we cannot directly assign values from the bit strings to a quantum register. As such, when we create a new quantum register, all of its qubits start in the $|0\rangle$ state. By using the quantum X gate, we can flip the qubits that give us the $|1\rangle$ state. # Create a file such as assignment.py: from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute # E.g. number 21 in binary. number = "10101" # Initializing the registers. # Create a Quantum Register called "qr" with length number qubits. qr = QuantumRegister(len(str(number))) # Create a Classical Register called "cr" with length number bits. cr = ClassicalRegister(len(str(number))) # Create a Quantum Circuit called "qc" with qr and cr. qc = QuantumCircuit(qr, cr) # Setting up the registers using the value inputted. for i in range(len(str(number))): if number[i] == "1": qc.x(qr[len(str(number)) - (i+1)]) #Flip the qubit from 0 to 1. #Measure qubits and store results in classical register cr. for i in range(len(str(number))): qc.measure(qr[i], cr[i]) # Compile and execute the quantum program in the local simulator. job_sim = execute(qc, "qasm_simulator") stats_sim = job_sim.result().get_counts() # Print number. print(stats_sim) # {'10101': 1024} #21 # ### Sum (Binary) # Create a file such as sumBinary.py: # Boolean binary string adder. def rjust_lenght(s1, s2, fill='0'): l1, l2 = len(s1), len(s2) if l1 > l2: s2 = s2.rjust(l1, fill) elif l2 > l1: s1 = s1.rjust(l2, fill) return (s1, s2) def get_input(): bits_a = input('input your first binary string ') bits_b = input('input your second binary string ') return rjust_lenght(bits_a, bits_b) def xor(bit_a, bit_b): A1 = bit_a and (not bit_b) A2 = (not bit_a) and bit_b return int(A1 or A2) def half_adder(bit_a, bit_b): return (xor(bit_a, bit_b), bit_a and bit_b) def full_adder(bit_a, bit_b, carry=0): sum1, carry1 = half_adder(bit_a, bit_b) sum2, carry2 = half_adder(sum1, carry) return (sum2, carry1 or carry2) def binary_string_adder(bits_a, bits_b): carry = 0 result = '' for i in range(len(bits_a)-1 , -1, -1): summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry) result += str(summ) result += str(carry) return result[::-1] def main(): bits_a, bits_b = get_input() print('1st string of bits is : {}, ({})'.format(bits_a, int(bits_a, 2))) print('2nd string of bits is : {}, ({})'.format(bits_b, int(bits_b, 2))) result = binary_string_adder(bits_a, bits_b) print('summarized is : {}, ({})'.format(result, int(result, 2))) if __name__ == '__main__': main() # input your first binary string 101<br> # input your second binary string 1011<br> # 1st string of bits is : 0101, (5)<br> # 2nd string of bits is : 1011, (11)<br> # summarized is : 10000, (16) # ### Sum (Ripple-carry adder) # This implementation prepares a = 1, b = 15 and computes the sum into b with an output carry cout[0] by using a quantum ripple-carry adder approach. # Create a file such as sum.py: from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import circuit_drawer # Initializing the registers. # Create a Quantum Registers. cin = QuantumRegister(1) a = QuantumRegister(4) b = QuantumRegister(4) cout = QuantumRegister(1) # Create a Classical Registers. ans = ClassicalRegister(5) # Create a Quantum Circuit called "qc". qc = QuantumCircuit(cin, a, b, cout, ans) # Set input states. x = "0001" #1 y = "1111" #15 # Setting up the registers using the value inputted. for i in range(len(str(x))): if x[i] == "1": qc.x(a[len(str(x)) - (i+1)]) #Flip the qubit from 0 to 1. for i in range(len(str(y))): if y[i] == "1": qc.x(b[len(str(y)) - (i+1)]) #Flip the qubit from 0 to 1. def majority(circ, a, b, c): circ.cx(c,b) circ.cx(c,a) circ.ccx(a,b,c) def unmaj(circ, a, b, c): circ.ccx(a,b,c) circ.cx(c,a) circ.cx(a,b) # Add a to b, storing result in b majority(qc,cin[0],b[0],a[0]) majority(qc,a[0],b[1],a[1]) majority(qc,a[1],b[2],a[2]) majority(qc,a[2],b[3],a[3]) qc.cx(a[3],cout[0]) unmaj(qc,a[2],b[3],a[3]) unmaj(qc,a[1],b[2],a[2]) unmaj(qc,a[0],b[1],a[1]) unmaj(qc,cin[0],b[0],a[0]) # Measure qubits and store results. for i in range(0, 4): qc.measure(b[i], ans[i]) qc.measure(cout[0], ans[4]) # Compile and execute the quantum program in the local simulator. num_shots = 2 # Number of times to repeat measurement. job = execute(qc, "qasm_simulator", shots=num_shots) job_stats = job.result().get_counts() # Print result number and circuit. print(job_stats) im = circuit_drawer(qc) im.save("circuitSum.png", "PNG") # {'10000': 2} #16 # <img src="images/circuitSum.png" width="800 px" align="left"> # ### Sum (Quantum Fourier Transform) # Method to calculate sum on a quantum computer using the quantum Fourier Transform by applying repeated controlled-U gates. # Create a file such as sumQFT.py: from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import circuit_drawer import numpy as np n1 = '10011' # E.g. number 19 n2 = '0011101' # E.g. number 29 if len(str(n1)) > len(str(n2)): n = len(str(n1)) else: n = len(str(n2)) # Initializing the registers. # Create a Quantum Registers called "qr1" and "qr2". qr1 = QuantumRegister(n+1) qr2 = QuantumRegister(n+1) # The classical register. cr = ClassicalRegister(n+1) # Create a Quantum Circuit called "qc". qc = QuantumCircuit(qr1, qr2, cr) length1 = len(n1) length2 = len(n2) # Set same length. if length2 > length1: n1,n2 = n2, n1 length2, length1 = length1, length2 n2 = ("0")*(length1-length2) + n2 # Set registers qr1 and qr2 to hold the two numbers. for i in range(len(str(n1))): if n1[i] == "1": qc.x(qr1[len(str(n1)) - (i+1)]) for i in range(len(str(n2))): if n2[i] == "1": qc.x(qr2[len(str(n2)) - (i+1)]) def qft(circ, q1, q2, n): # n-qubit QFT on q in circ. for i in range(0, n+1): qc.cu1(np.math.pi/float(2**(i)), q2[n-i], q1[n]) def invqft(circ, q, n): # Performs the inverse quantum Fourier transform. for i in range(0, n): qc.cu1(-np.math.pi/float(2**(n-i)), q[i], q[n]) qc.h(q[n]) def input_state(circ, q, n): # n-qubit input state for QFT. qc.h(q[n]) for i in range(0, n): qc.cu1(np.math.pi/float(2**(i+1)), q[n-(i+1)], q[n]) for i in range(0, n+1): input_state(qc, qr1, n-i) qc.barrier() for i in range(0, n+1): qft(qc, qr1, qr2, n-i) qc.barrier() for i in range(0, n+1): invqft(qc, qr1, i) qc.barrier() for i in range(0, n+1): qc.cx(qr1[i],qr2[i]) for i in range(0, n+1): qc.measure(qr1[i], cr[i]) # Compile and execute the quantum program in the local simulator. num_shots = 2 # Number of times to repeat measurement. job = execute(qc, "qasm_simulator", shots=num_shots) job_stats = job.result().get_counts() print(job_stats) im = circuit_drawer(qc) im.save("circuitAdderQFT.png", "PNG") # {'00110000': 2} #48 # ### Average # Show that the average value of the observable $$X_1Z_2$$ for a two-qubit system measured in the state $$(|00\rangle+|11\rangle)/\sqrt{2}$$ is zero. # In a two-qubit system we represent the kets as vectors, the Pauli matrices and perform the tensor products, and conduct the multiplication. # # $$|0\rangle\equiv\left(\begin{array}{c}1\\0\end{array}\right)\qquad|1\rangle\equiv\left(\begin{array}{c}0\\1\end{array}\right)$$We calculate the tensor product, such as $|01\rangle$,$$|01\rangle=|0\rangle\otimes|1\rangle\equiv\left(\begin{array}{c}1\times\left(\begin{array}{c} 0 \\ 1 \end{array}\right)\\ 0\times \left(\begin{array}{c} 0 \\ 1 \end{array}\right) \end{array}\right)=\left(\begin{array}{c} 0 \\ 1 \\ 0 \\ 0 \end{array}\right)$$Where $\langle 01|$ is the Hermitian conjugate of,$$\langle 01|=\left(\begin{array}{cccc} 0 & 1 & 0 & 0 \end{array}\right)$$Then similar reasoning for the operators. For example,$$X_1X_2=\sigma_1\otimes\sigma_1=\left(\begin{array}{cc} 0\times \left(\begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right) & 1\times \left(\begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right) \\ 1\times \left(\begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right) & 0\times \left(\begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right) \end{array}\right)=\left(\begin{array}{cccc} 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 1 & 0 & 0 & 0 \end{array}\right).$$Finally, we simply multiply it out:$$\langle 01|X_1X_2|01\rangle=\left(\begin{array}{cccc} 0 & 1 & 0 & 0 \end{array}\right)\left(\begin{array}{cccc} 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 1 & 0 & 0 & 0 \end{array}\right)\left(\begin{array}{c} 0 \\ 1 \\ 0 \\ 0 \end{array}\right)=0.$$ from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import circuit_drawer # Initializing the registers. # Create a Quantum Registers. cin = QuantumRegister(1) a = QuantumRegister(2) b = QuantumRegister(2) cout = QuantumRegister(1) # Create a Classical Registers. ans = ClassicalRegister(3) # Create a Quantum Circuit called "qc". qc = QuantumCircuit(cin, a, b, cout, ans) # Set input states. x = "00" #0 y = "11" #3 # Setting up the registers using the value inputted. for i in range(len(str(x))): if x[i] == "1": qc.x(a[len(str(x)) - (i+1)]) #Flip the qubit from 0 to 1. for i in range(len(str(y))): if y[i] == "1": qc.x(b[len(str(y)) - (i+1)]) #Flip the qubit from 0 to 1. # Add a to b, storing result in b majority(qc,cin[0],b[0],a[0]) majority(qc,a[0],b[1],a[1]) qc.cx(a[1],cout[0]) unmaj(qc,a[0],b[1],a[1]) unmaj(qc,cin[0],b[0],a[0]) qc.cx(b[1],b[0]) qc.x(b[1]) # Measure qubits and store results. for i in range(0, 1): qc.measure(b[i], ans[i]) qc.measure(cout[0], ans[1]) # Compile and execute the quantum program in the local simulator. num_shots = 2 # Number of times to repeat measurement. job = execute(qc, "qasm_simulator", shots=num_shots) job_stats = job.result().get_counts() # Print result number and circuit. print(job_stats) im = circuit_drawer(qc) im.save("circuitAverage.png", "PNG") # {'000': 2} #0 # <img src="images/circuitAverage.png" width="600 px" align="left"> # ## Quantum Algorithms # - Shor's # - Grover's # # ### Shor's # Any integer number has a unique decomposition into a product of prime numbers. # In 1995 <NAME> proposed a polynomial-time quantum algorithm for the factoring problem. # # -> Runs partially on quantum computer. Fourier Transform and Period-finding algorithm.<br> # -> Pre- and post-processing on a classical computer: greatest common divisor (quadratic in number of digits of a, b), test of primality (polynomial), prime power test (O(log n)) and continued fraction expansion (polynomial)<br> # # Worst Case in Quantum : polynomial in log(N)<br> # Worst Case in Classical: polynomial in N<br> # # - Period Finding # Given integers N and a, find the smallest positive integer r such that a^r-1 is a multiple of N, # where r is the period of a modulo N (smallest positive integer r such that a^r=1 mod N) # # Example: N=15 and a=7 # We want to find the smallest positive integer r such that a^r = 1 mod N # <=> 7^r = 1 mod 15 # # r=2: 7^2 = 4 mod 15 # r=3: 7^3 = 4 * 7 mod 15 = 13 mod 15 # r=4: 7^4 = 13 * 7 mod 15 = 1 mod 15 # -> r=4 is the period of a modulo N # # - From factoring to period finding<br> # Assume that N has only two distinct prime factors: N = p1 * p2.<br> # 1) pick an integer a between [2,N-1] and compute greatest common divisor gcd(N,a) using Euclid's Algorithm.<br> # 2) If gcd(N,a)=p1 or p2 we are done.<br> # 3) Else repeat the above steps with different random choices of a until r is even. # If r is even and is the smallest integer such that a^r-1 is a multiple of N:<br> # a^r-1=(a^(r/2)-1)*(a^(r/2)+1).<br> # where neither (a^(r/2)-1) nor (a^(r/2)+1) is a multiple of N, but their product is.<br> # We can find p1 and p2 by computing gcd(N, (a^(r/2)-1)) and gcd(N, (a^(r/2)+1)).<br> # If (a^(r/2)+1) is multiple of N we try with a different a.<br><br> # At the heart of Shor's Algorithm, Quantum Fourier Transform (QFT), a linear transformation on quantum bits, and the quantum analogue of the discrete Fourier transform.<br> # Formally, the QFT is expected to be useful in determining the period r of a function i.e. when f(x)=f(x+r) for all x.<br> # The input register for QFT contains n-qubit basis state $|x\rangle$ which is rewritten as the tensor product of the individual qubits in its binary expansion.<br> # In fact, each of those single-qubit operations can be implemented efficiently using a Hadamard gate and controlled phase gates.<br> # The first term requires one Hadamard gate and (n-1) controlled phase gates, the next one requires a Hadamard gate and (n-2) controlled phase gate, and each following term requires one fewer controlled phase gate. # # <img src="images/1QFT.png" width="600 px" align="left"> # <img src="images/2QFT.png" width="600 px" align="left"> # <img src="images/3QFT.png" width="600 px" align="left"> # - Shor's Algorithm<br> # Shor's algorithm exploits interference to measure periodicity of arithmetic objects.<br> # Suppose we a,N are co-primes, gcd(a,N)=1.<br> # Our goal is to compute the smallest positive integer r such that a^r=1 mod N.<br><br> # Steps:<br> # 1. Determine if n is even, prime or a prime power. If so, exit.<br> # 2. Pick a random integer x < n and calculate gcd(x, n). If this is not 1, then we have obtained a factor of n.<br> # 3. Quantum algorithm:<br> # Pick q as the smallest power of 2 with n^2 $\leq$ q < 2 * n^2.<br> # Find period r of x^a mod n.<br> # Measurement gives us a variable c which has the property c $\approx$ d where d $\in$ |N.<br> # 4. Determine d, r via continued fraction expansion algorithm. d, r only determined if gcd(d, r) = 1 (reduced fraction).<br> # 5. If r is odd, go back to 2.<br> # If x^(r/2) $\equiv$ −1 mod n go back to 2.<br> # Otherwise the factors p, q = gcd(x^(r/2) $\pm$ 1, n). # # ### Grover's<br> # - Quantum algorithms<br> # The current state of quantum algorithms can be divided in two main types of algorithms. On one side we have the algorithms based on "Shor's quantum Fourier transform", on which were built some of the most popular known algorithms with a exponencial speedup over their classical counterparts.<br> # For example the classic Fast Fourier transform on a runs on O(nlog n) time and the Quantum Fourier transform runs on O(log^2 n).<br> # On the other side we have Groover's, which is mainly used on quantum search. This method gives a quadratic speedup to some of the best classical algorithms.<br> # Since it is used to search a database if the classical algorithm runs on the worst case O(N), on a groover's search algorithm it can e improved to run on O(sqrt(N))<br> # - Quantum Complexity<br> # Regarding computational complexity theory, when it comes to quantum computing we have two big correlations that we can compare to the classical computing complexities know as P and NP. One of them is BQP which stands for bounded-error quantum polynomial time which as the name implies belongs to the class of decision problems that can be solved by a quantum computer in polynomial time. We then have QMA, which stands for Quantum Merlin Arthur, and this one is, in an informal way, the set of decision problems for which when the answer is YES, there is a polynomial-size quantum proof (a quantum state) which convinces a polynomial-time quantum verifier of the fact with high probability. Moreover, when the answer is NO, every polynomial-size quantum state is rejected by the verifier with high probability. Both of these can be compared to P and NP because QMA is to BQP as NP is to P.<br> # - Groover's Algorithm<br> # This algorithm is mainly used to search databases, as told before the time it runs improves quadratically compared to the classical counterparts.<br> # What does that mean? Given an array of N elements, and on that array we want to locate a specific and unique element. Given this typical example we can relate to a normal problem we would face on a classical computer, but it would take on average N/2 or in the worst case O(N). This is not how it will work on a quantum computer, because using groover algorithm it is possible to reduce the time to O(sqrt(N)). How does it work?<br> # - The Oracle<br> # Firstly we have to encode a list in terms of a function f, this function returns f(x)=0 for all unwanted positions and f(u)=1 for the element we want to locate.<br> # The we define the Oracle to act on the state |x$\rangle$, this done by the following function: U f|x$\rangle$ =(-1)^f(x) |x$\rangle$.<br> # This works because the state of the qbit only changes when we find f(u)=1 resulting in U f|u$\rangle$ = -|w$\rangle$ while the rest remains the same.<br> # - Amplitude amplification<br> # So far so good but it is still very similar to a normal algorithm, and we cannot guess because it would still take O(N) and if we were to guess, the measure would destroy the super position. Amplitude representation in the image below.<br> # So how to initialize the algorithm?<br> # 1. Start a uniform superposition |s$\rangle$ by doing the following |s$\rangle$=H$\otimes$n|0$\rangle$n.<br> # 2. We then have to apply the oracle function to Uf|$\psi$t$\rangle$=|$\psi$t'$\rangle$. This results on the amplitude of the element we are searching for turning negative.<br> # 3. We now apply an additional reflection Us about the state |s$\rangle$.<br> # We have then to repeat this process O($\sqrt{N}$).<br> # In this code we have a grover implementation.<br> # This code represents a deterministic solution for a SAT problem with 3 clauses and 3 literals that has exactly one true output, the formula has to be on conjunctive normal form(CNF) in order for it to work.<br> # This works the following way, imagine all the results the expression could give are in an array, since the expression only has one output that is true, being that the one we want to find, it is possible to apply the algorithm to this problem.<br> # # <img src="images/charts.png" width="400 px" align="left"> # ### SAT program # Create and save a program with the following code in a file such as sat.py: import matplotlib.pyplot as plt import numpy as np from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram, circuit_drawer n = 3 sat_formula = [[1,2,-3],[-1,-2,-3],[1,-2,3]] f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(sat_formula)+1) ans = ClassicalRegister(n) qc = QuantumCircuit(f_in, f_out, aux, ans) # Initializes all of the qbits. def input_state(circuit, f_in, f_out, n): for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # The back box U function (Oracle). def black_box_u_f(circuit, f_in, f_out, aux, n, sat_formula): num_claus = len(sat_formula) for(k,claus) in enumerate(sat_formula): for literal in claus: if literal > 0: circuit.cx(f_in[literal-1],aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1],aux[k]) circuit.ccx(f_in[0],f_in[1],aux[num_claus]) circuit.ccx(f_in[2],aux[num_claus],aux[k]) circuit.ccx(f_in[0],f_in[1],aux[num_claus]) for literal in claus: if literal < 0: circuit.x(f_in[-literal-1]) if(num_claus == 1): circuit.cx(aux[0], f_out[0]) elif(num_claus == 2): circuit.ccx(aux[0],aux[1],f_out[0]) elif(num_claus == 3): circuit.ccx(aux[0], aux[1], aux[num_claus]) circuit.ccx(aux[2], aux[num_claus], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_claus]) else: raise ValueError('Apenas 3 clausulas pf :)') for(k,claus) in enumerate(sat_formula): for literal in claus: if literal > 0: circuit.cx(f_in[literal-1],aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1],aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_claus]) circuit.ccx(f_in[2], aux[num_claus], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_claus]) for literal in claus: if literal < 0: circuit.x(f_in[-literal-1]) # iInverts the qbit that was affected by the Oracle function. def inversion_about_average(circuit,f_in,n): for j in range(n): circuit.h(f_in[j]) for j in range(n): circuit.x(f_in[j]) n_controlled_z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) for j in range(n): circuit.h(f_in[j]) def n_controlled_z(circuit,controls,target): if(len(controls) > 2): raise ValueError('erro de control') elif(len(controls) == 1): circuit.h(target) circuit.cx(controls[0],target) circuit.h(target) elif(len(controls) == 2): circuit.h(target) circuit.ccx(controls[0],controls[1],target) circuit.h(target) input_state(qc,f_in,f_out,n) black_box_u_f(qc,f_in,f_out,aux,n,sat_formula) inversion_about_average(qc,f_in,n) black_box_u_f(qc,f_in,f_out,aux,n,sat_formula) inversion_about_average(qc,f_in,n) for j in range(n): qc.measure(f_out[0],ans[j]) # Compile and execute the quantum program in the local simulator. job_sim = execute(qc, "qasm_simulator") stats_sim = job_sim.result().get_counts() # Plot and print results. print(stats_sim) plot_histogram(stats_sim) im = circuit_drawer(qc) im.save("circuitGrover.pdf", "PDF") # <img src="images/grover.png" width="400 px" align="left"> # <img src="images/circuitGrover.png" width="1200 px" align="left"> # ### Final notes # - Check 'from qiskit import available_backends', useful to know which real backends are available. # - Check 'from qiskit.tools.qi.qi import state_fidelity', tool to verify if two states are same or not. # - Check 'from qiskit.tools.visualization import...', tools for exceptional visualization charts! # - Happy Quantum Coding! And, any help, check the IBM Q Graphical composer :) Compose quantum circuits using drag and drop interface. Save circuits online or as QASM text, and import later. Run circuits on real hardware and simulator. # <img src="images/qasmeditor.png" width="800 px" align="left"> # <img src="images/Help.png" width="700 px" align="left"> # ### Acknowledgments # We acknowledge use of the IBM Q for this work. The views expressed are those of the authors and do not reflect the official policy or position of IBM or the IBM Q team. # *** # ### *References* # # [1] <NAME>, and <NAME> (2010). Quantum Computation and Quantum Information: 10th Anniversary Edition. Cambridge: Cambridge University Press. doi:10.1017/CBO9780511976667.<br> # [2] IBM Research and the IBM QX team (2017). User guide. IBM Q Experience Documentation https://quantumexperience.ng.bluemix.net/qx/tutorial<br> # [3] <NAME>, <NAME>, <NAME>, and <NAME>. A new quantum ripple-carry addition circuit. arXiv:quant-ph/0410184, 2004.<br> # [4] <NAME>, <NAME>, <NAME>, and <NAME>. Open quantum assembly language. arXiv:1707.03429, 2017.<br> # [5] 5-qubit backend: IBM Q team, "IBM Q 5 Yorktown backend specification V1.1.0," (2018). Retrieved from https://ibm.biz/qiskit-yorktown.<br> # [6] 14-qubit backend: IBM Q team, "IBM Q 14 Melbourne backend specification V1.x.x," (2018). Retrieved from https://ibm.biz/qiskit-melbourne.<br> # [7] <NAME>, <NAME>, and <NAME> (2018). Driven tabu search: a quantum inherent optimisation. arXiv preprint arXiv:1808.08429.<br> # [8] <NAME> and <NAME> (2014). Quantum arithmetic with the Quantum Fourier Transform. arXiv preprint arXiv:1411.5949.<br>[9] <NAME>, <NAME>, and <NAME> (2007). An Introduction to Quantum Computing. Oxford Univ. Press.<br>
community/awards/teach_me_quantum_2018/basic_intro2qc/QuantumComputingIntroduction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: nft_analytics # language: python # name: nft_analytics # --- import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit import pandas as pd import os DATA_FOLDER = os.path.join("data", "BTCUSD") df = pd.read_csv(os.path.join(DATA_FOLDER, "BCHAIN-MKPRU.csv")) df = df.iloc[::-1] df = df[df["Value"] > 0] df["Date"] = pd.to_datetime(df["Date"], infer_datetime_format=True) df def func(x, a, b): return a + b * np.log(x) # + xdata = np.arange(1, len(df["Value"]) + 1) ydata = np.log(df["Value"]) popt, pcov = curve_fit(func, xdata, ydata, p0=[-15, 3]) # + # %matplotlib widget fig, ax = plt.subplots() ax.plot(df["Date"], df["Value"], "-") for i in range(-1, 3): ax.plot(df["Date"], np.exp(func(xdata, *popt)+i)) ax.fill_between(df["Date"], np.exp(func(xdata, *popt) + i - 1), np.exp(func(xdata, *popt) + i), alpha=0.1) ax.set_yscale("log") ax.set_ylim([0.02, 6e5])
notebooks/BitcoinAnalytics.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 # --- # In this part of the tutorial, we run two ontology based methods to produce vector representations of biological entities: Onto2Vec and OPA2Vec. # ## Onto2vec # Onto2vec produces vectory representations based on the logical axioms of an ontology and the known associations between ontology classes and biological entities. In the case study below, we use Onto2vec to produce vector representations of proteins based on their GO annotations and the GO logical axioms. org_id ='4932' #or 9606 for human data # !python onto2vec/runOnto2Vec.py -ontology data/go.owl -associations data/train/{org_id}.OPA_associations.txt -outfile data/{org_id}.onto2vec_vecs -entities data/train/{org_id}.protein_list.txt # ## OPA2Vec # In addition to the ontology axioms and their entity associations, OPA2Vec also uses the ontology metadata and literature to represent biological entities. The code below runs OPA2Vec on GO and protein-GO associations to produce protein vector representations # !python opa2vec/runOPA2Vec.py -ontology data/go.owl -associations data/train/{org_id}.OPA_associations.txt -outfile data/{org_id}.opa2vec_vecs -entities data/train/{org_id}.protein_list.txt # ## Generate features # Map proteins to corresponding vectors org_id = '9606' #org_id = '4932' onto2vec_map = {} opa2vec_map = {} with open (f'data/{org_id}.onto2vec_vecs','r') as f: for line in f: protein, vector=line.strip().split(" ",maxsplit=1) onto2vec_map [protein]=vector with open (f'data/{org_id}.opa2vec_vecs','r') as f: for line in f: protein, vector=line.strip().split(" ",maxsplit=1) opa2vec_map [protein]=vector # Generate pair features for the training/validation/testing datasets import random data_type = ['train', 'valid', 'test'] for i in data_type: pair_data = [] feature_vecs =[] label_map ={} with open (f'data/{i}/{org_id}.protein.links.v11.0.txt','r') as f1: for line in f1: prot1, prot2 = line.strip().split() pair_data.append((prot1,prot2)) label_map[(prot1, prot2)] = 1 with open (f'data/{i}/{org_id}.negative_interactions.txt','r') as f2: for line in f2: prot1, prot2 = line.strip().split() pair_data.append((prot1, prot2)) label_map[(prot1, prot2)] = 0 random.shuffle(pair_data) with open (f'data/{i}/{org_id}.onto2vec_features','w') as f3: with open (f'data/{i}/{org_id}.opa2vec_features', 'w') as f4: with open (f'data/{i}/{org_id}.labels','w') as f5: with open (f'data/{i}/{org_id}.pairs','w') as f6: for prot1, prot2 in pair_data: if (prot1 in onto2vec_map and prot1 in opa2vec_map and prot2 in onto2vec_map and prot2 in opa2vec_map): f6.write (f'{prot1} {prot2}\n') f5.write (f'{label_map[(prot1,prot2)]}\n') f4.write (f'{opa2vec_map[prot1]} {opa2vec_map[prot2]}\n') f3.write (f'{onto2vec_map[prot1]} {onto2vec_map[prot2]}\n') # ## Cosine similarity # Calculating cosine similarity to explore neighbors of each protein and finding most similar protein vectors. The interaction prediction is then performed based on similarity value based on the assumption that proteins with highly similar feature vectors are more like to interact # + import os import sys import numpy from sklearn.metrics import pairwise_distances from scipy.spatial.distance import cosine from itertools import islice for prot1, prot2 in pair_data: v1_onto = onto2vec_map[prot1] v2_onto = onto2vec_map [prot2] v1_opa = opa2vec_map [prot1] v2_opa = opa2vec_map [prot2] if (prot1 in onto2vec_map and prot1 in opa2vec_map and prot2 in onto2vec_map and prot2 in opa2vec_map): cosine_onto = cosine(v1_onto, v2_onto) cosine_opa = cosine (v1_opa, v2_opa) with open (f'data/{i}/{org_id}.onto_sim','w') as onto_cos: with open (f'data/{i}/{org_id}.opa_sim','w') as opa_cos: onto_cos.write (f'{cosine_onto}\n') opa_cos.write (f'{cosine_onto}\n') query =str(sys.argv[1]) n = int (sys.argv[2]) #query ="A0A024RBG1" #n=10 vectors=numpy.loadtxt("data/{org_id}.opa2vec_vecs"); text_file="data/train/protein_list" classfile=open (text_file) mylist=[] for linec in classfile: mystr=linec.strip() mylist.append(mystr) #3.Mapping Entities to Vectors vectors_map={} for i in range(0,len(mylist)): vectors_map[mylist[i]]=vectors[i,:] cosine_sim={} for x in range(0,len(mylist)): if (mylist[x]!=query): v1=vectors_map[mylist[x]] v2=vectors_map[query] value=cosine(v1,v2) cosine_sim[mylist[x]]=value classes = mylist #5.Retrieving neighbors sortedmap=sorted(cosine_sim,key=cosine_sim.get, reverse=True) iterator=islice(sortedmap,n) i =1 for d in iterator: print (str(i)+". "+ str(d) +"\t"+str(cosine_sim[d])+"\n") i +=1 # - # ## Evaluation # + from scipy.stats import rankdata def load_test_data(data_file, classes): data = [] with open(data_file, 'r') as f: for line in f: it = line.strip().split() id1 = f'http://{it[0]}' id2 = f'http://{it[1]}' data.append((id1, id2)) return data def compute_rank_roc(ranks, n_prots): auc_x = list(ranks.keys()) auc_x.sort() auc_y = [] tpr = 0 sum_rank = sum(ranks.values()) for x in auc_x: tpr += ranks[x] auc_y.append(tpr / sum_rank) auc_x.append(n_prots) auc_y.append(1) auc = np.trapz(auc_y, auc_x) / n_prots return auc # Load test data and compute ranks for each protein test_data = load_test_data(f'data/test/{org_id}.protein.links.v11.0.txt', classes) top1 = 0 top10 = 0 top100 = 0 mean_rank = 0 ftop1 = 0 ftop10 = 0 ftop100 = 0 fmean_rank = 0 labels = {} preds = {} ranks = {} franks = {} eval_data = test_data n = len(eval_data) for c, d in eval_data: c, d = prot_dict[classes[c]], prot_dict[classes[d]] labels = np.zeros((len(onto2vec_map), len(onto2vec_map)), dtype=np.int32) preds = np.zeros((len(onto2vec_map), len(onto2vec_map)), dtype=np.float32) labels[c, d] = 1 ec = onto2vec_map[c, :] #er = rembeds[r, :] #ec += er # Compute distance #dst = np.linalg.norm(prot_embeds - ec.reshape(1, -1), axis=1) res = numpy.loadtxt('onto_cos.write') preds[c, :] = res index = rankdata(res, method='average') rank = index[d] if rank == 1: top1 += 1 if rank <= 10: top10 += 1 if rank <= 100: top100 += 1 mean_rank += rank if rank not in ranks: ranks[rank] = 0 ranks[rank] += 1 # Filtered rank index = rankdata((res * trlabels[c, :]), method='average') rank = index[d] if rank == 1: ftop1 += 1 if rank <= 10: ftop10 += 1 if rank <= 100: ftop100 += 1 fmean_rank += rank if rank not in franks: franks[rank] = 0 franks[rank] += 1 top1 /= n top10 /= n top100 /= n mean_rank /= n ftop1 /= n ftop10 /= n ftop100 /= n fmean_rank /= n rank_auc = compute_rank_roc(ranks, len(proteins)) frank_auc = compute_rank_roc(franks, len(proteins)) print(f'{top10:.2f} {top100:.2f} {mean_rank:.2f} {rank_auc:.2f}') print(f'{ftop10:.2f} {ftop100:.2f} {fmean_rank:.2f} {frank_auc:.2f}') # - # ## Siamese neural network # + import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader from random import randint import numpy as np import time import os import sys import numpy import sklearn #Hyperparameters num_epochs = 100 num_classes = 2 batch_size = 50 learning_rate = 0.0001 #Load dataset X_train_1= numpy.loadtxt("data/train/{org_id}.embeddings_1") X_train_2= numpy.loadtxt("data/train/{org_id}.embeddings_2") y_train= numpy.loadtxt("data/train/{org_id}.labels") X_test_1= numpy.loadtxt("data/test/{org_id}.embeddings_1") X_test_2= numpy.loadtxt("data/test/{org_id}.embeddings_2") y_test= numpy.loadtxt("data/test/{org_id}.labels") #transform to torch train_x1= torch.from_numpy(X_train_1).float() train_x2= torch.from_numpy(X_train_2).float() train_x = [train_x1, train_x2] train_label= torch.from_numpy(y_train).long() test_x1 = torch.from_numpy(X_test_1).float() test_x2 = torch.from_numpy(X_test_2).float() test_x=[test_x1, test_x2] test_label= torch.from_numpy(y_test).long() train_data = [] train_data.append([train_x, train_label]) test_data = [] test_data.append([test_x,test_label]) train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=True) #Define Network class Net (nn.Module): def __init__(self): super(Net, self).__init__() self.layer1 = nn.Sequential( nn.Linear (200, 600), nn.ReLU()) self.layer2 = nn.Sequential ( nn.Linear (600,400), nn.ReLU()) self.layer3 = nn.Sequential( nn.Linear (400, 200), nn.ReLU()) self.drop_out = nn.Dropout() self.dis = nn.Linear (200,2) def forward (self, data): res = [] for i in range(2): x = data[i] out = self.layer1(x) out = self.layer2(out) out = self.layer3(out) out = self.drop_out(out) #out = out.reshape(out.size(0),-1) res.append(out) output = torch.abs(res[1] - res[0]) #output = torch.mm(res[1] , res[0]) output = self.dis(output) return output #Create network network = Net() # Use Cross Entropy for back propagation criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam (network.parameters(),lr=learning_rate) # Train the model total_step = len(train_loader) loss_list = [] acc_list = [] for epoch in range (num_epochs): for i, (train_x, train_label) in enumerate (train_loader): # Get data inputs = train_x labels = train_label # Run the forward pass outputs = network (inputs) outputs=outputs.reshape(-1,2) labels=labels.reshape(-1) #print (outputs.size()) #print (labels.size()) loss = criterion (outputs, labels) loss_list.append(loss.item()) # Back propagation and optimization optimizer.zero_grad() loss.backward() optimizer.step() # Get prediction total = labels.size(0) _,predicted = torch.max(outputs.data,1) correct = (predicted == labels).sum().item() acc_list.append (correct/total) #if (i + 1) % 100 == 0: print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}, Accuracy: {:.2f}%'.format(epoch + 1, num_epochs, i + 1, total_step, loss.item(), (correct/total)*100)) # Test the model network.eval() with torch.no_grad(): correct = 0 total = 0 for test_x,test_label in test_loader: outputs = network (test_x) labels = test_label outputs=outputs.reshape(-1,2) array = outputs.data.cpu().numpy() numpy.savetxt('output.csv',array) labels=labels.reshape(-1) _, predicted = torch.max(outputs.data,1) total += labels.size(0) correct += (predicted == labels).sum().item() #print ('Accuracy of model on test dataset is: {} %'.format((correct / total) *100))
onto2vec_opa2vec.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 # --- # # Predicting Protein Secondary Structures with Convolutional Neural Networks (CNNs) # # This Notebook contains the data engineering, model creation and training of 2 CNNS. # # the first CNN takes protein sequences (as a numeric vector) as input to predict the secondary structure of an single amino acid, based on its environment. The network classifies the amino acid either as helix, beta-sheet or as loop. The trained network is then used to classify every amino acid of every sequence, which will serve as input for the second network. # The second network will take the output from the first network an will reclassify the results based, now with added (predicted) secondary structure information of its neighbors. # importing necessary modules and libraries import pandas as pd import numpy as np import os import tensorflow as tf from tensorflow import keras from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt # # The Training Data # # 1. First download the most recent collection of secondary structures based on the protein database from Kabsch and Sanders translation website: # # this is a terminal command which requires wget and time stamps the file you download from the site. # # wget https://cdn.rcsb.org/etl/kabschSander/ss.txt.gz -O ${DATE_STAMP}-ss.txt.gz # # 2. The Python file generate_ss_files contains a generate_files function which takes this file and a directory name and puts each secondary structure into it's own file. This is so we can avoid having to due random access lookups in the ss file. All ss files are put into the directory dir # # 3. The three generate_training files will create a training file as well as a file stating which files the trainingdata came from and at which location in the sequence. # (comments are still lacking though) # # Some sequences in the data set contain strange amino acids, which I removed # + # Function to load the secondary structure files from correspronding directory ss_dir = "ss_dir" def load_proteins(dir): ''' go to secondary structure directory and load sequence and structure information into python. arguments: dir: directory returns: names, sequences, ss_structures ''' names = [] sequences = [] ss_structures = [] for file in os.listdir(dir): with open(os.path.join(dir, file), 'r') as f: lines = f.readlines() name = file.split('.')[0] sequence = lines[0].replace('\n','') ss_structure = lines[1].replace('\n','') names.append(name) sequences.append(sequence.replace(',','')) ss_structures.append(ss_structure.replace(',','')) return names, sequences, ss_structures # - names, sequences, ss_structures = load_proteins(ss_dir) # Defining the Dataframe which contains the name of the protein, the sequence and secondary structure information. d = {"name":names,"sequence":sequences, "ss_structure":ss_structures} raw_data = pd.DataFrame(d) raw_data raw_data.to_pickle('data/raw_data.pkl') # + cleaned_data = raw_data # inserted from cell below for test strange = ["B","U","O","X"," '","'","Z"] strange_rows = [] for row in cleaned_data.iterrows(): #print(row[1][1]) for x in strange: if x in row[1][1]: # row[1][1] == sequence strange_rows.append(row[0]) print(f"dropping {len(strange_rows)} strange rows") # cleaned data cleaned_data = cleaned_data.drop(strange_rows) # - cleaned_data.to_pickle('data/cleaned_data.pkl') # + # transform amino acid data to numerical values # used for changing amino acids to numerical values, so it can be used as input for NN aas = {"A":0, "C":1, "D":2, "E":3, "F":4, "G":5, "H":6, "I":7, "K":8, "L":9, "M":10, "N":11, "P":12, "Q":13, "R":14, "S":15, "T":16, "V":17, "W":18, "X":19, "Y":20} numerical_sequences = [] for protein in cleaned_data.iterrows(): sequence = protein[1][1] array=np.zeros((len(sequence),21)) for i,aa in enumerate(sequence): array[i,aas[aa]] = 1 numerical_sequences.append(array) print(len(numerical_sequences)) # + cat_labels = {'B':0, 'E':1, 'G':2, 'H':3, 'I':4, 'S':5, 'T':6, '-':7} # the labels can simplified to helices, loops and sheets # helix - E,B - E 0 # sheet - H,G,I - H 1 # loop - S,T - '-' 2 numerical_labels = [] for protein in cleaned_data.iterrows(): label = protein[1][2] label=label.replace('B',"0").replace('E',"0").replace('G',"1").replace('H',"1").replace('I',"1").replace('S',"2").replace('T',"2").replace('-',"2") numerical_labels.append(label) print(len(numerical_labels)) # + # creating numerical data dataframe cleaned_names = cleaned_data.name.to_list() numerical_data = pd.DataFrame({ "name":cleaned_names, "numeric_sequence":numerical_sequences, "numeric_ss":numerical_labels }) numerical_data # - numerical_data.to_pickle('data/numerical_data.pkl') # # Numeric Sequences # # The sequences were stored as a vector with the dimensions (sequence_length x 21). the rows of the vector correspond to the index of an amino acid in the sequence and the columns to a specific amino acid. # # $ # \begin{pmatrix} # 0 & \dots & 0 & 1 \\ # \vdots & \ddots & & 0 \\ # \vdots & & \ddots & 1 \\ # 0 & \dots & 1 & 0 # \end{pmatrix} # $ # # If the first amino acid of sequence is an alanine, then the vector at index (0,0) will be 1 and the rest of the row will be zero. # There are 21 columns for the 20 amino acids and 1 pseudo amino acid, which I use for padding in when creating the data points # # ## From Numeric Sequences to Data Points # # To train the model I picked random amino acids from the sequences and added an environment of a fixed size. The randomly picked amino acid is classified and the environment just used for further information. If environment of the picked amino acid exceeds the sequence length, psuedo amino acids are added to generate a vector of the desired length. # + environment = 10 def create_in_data(center,environment,full_seq_vector): """ Function to create datapoints for single numerical sequences. params: center (type int) :: index of amino acid, which will be classified environment (type int) :: the size of the environment - left & right boarder - considered for classification. full_seq_vector (type np.array) :: the full sequence considered for classification returns: returns output vector as np.array (environment*2+1 x 20) """ center_stack = full_seq_vector[center] # determin if upstream padding is required usp = False if center - environment < 0: usp = True usp_length = environment - center # determin if downstream padding is required seq_length = full_seq_vector.shape[0] dsp = False if center + environment >= seq_length: dsp = True dsp_length = center + environment - seq_length + 1 # create upstream padding if usp if usp: us_padding = np.zeros((usp_length,21)) for i in range(usp_length): us_padding[i,19] = 1 # create upstream padding if dsp if dsp: ds_padding = np.zeros((dsp_length,21)) for i in range(dsp_length): ds_padding[i,19] = 1 # now construct the out_vector if usp and dsp: middle = full_seq_vector[0:seq_length] out_vector = np.vstack([us_padding,middle,ds_padding]) return out_vector if usp: # out has right dimensions data = full_seq_vector[0:center+environment+1] out_vector = np.vstack([us_padding,data]) return out_vector if dsp: # out has right dimensions start = center-environment data = full_seq_vector[start:seq_length+1] out_vector = np.vstack([data,ds_padding]) return out_vector start = center - environment end = center + environment + 1 out_vector = full_seq_vector[start:end] return out_vector def get_dataset(environment, df, name_col="name", input_col="numeric_sequence", label_col="numeric_ss"): """ creates input vector and label for each sequence in df DataFrame. returns a dataframe with the columns: name, input_vector, label. params: environment (type int) :: size of environment considered for classification df (type pd.DataFrame) :: dataframe consisting of numerical data - see numerical data name_col (type string) :: name of column storing the names input_col (type sting) :: name of column storing the numeric sequences label_col (type string):: name of column storing the sequence labels returns: dataframe with datapoints - ready for training / testing """ names = df[name_col].to_list() input_values = df[input_col].to_list() label_values = df[label_col].to_list() xs = [] ys =[] for i in range(len(names)): center = np.random.randint(0,len(input_values[i])) x = create_in_data(center=center, environment=environment, full_seq_vector=input_values[i]) y = np.int8(label_values[i][center]) xs.append(x) ys.append(y) out_df = pd.DataFrame({"name":names, "x":xs, "y":ys}) return(out_df) # + # divide data into training and testing sets numerical_data.sample(frac=1) d_points = 333400 training_set=numerical_data.iloc[:d_points] testing_set=numerical_data.iloc[d_points+1:] # def make_train_and_test(ntrain,train_set,test_set,environment=environment): ''' A.) Creates n data points per sequence in for the train_set - given by variable ntrain. The data points are collected in a single training_data DataFrame and returned. B.) Create 1 data point per sequence in test_set and return them as testing_data DataFrame. params: ntrain (type int) :: number of data points per sequence in train_set train_set (type pd.DataFrame) :: training data in form of pd.DataFrame test_set (type pd.DataFrame) :: testing data in form of pd.DataFrame environment (type int) :: size of the environment -> needed for get_dataset() returns: training_data (type pd.DataFrame) testing_data (type pd.DataFrame) ''' training_sets =[] for n in range(ntrain): tr_set = get_dataset(environment=environment,df=train_set) training_sets.append(tr_set) training_data = pd.concat(training_sets) testing_data = get_dataset(environment=environment,df=testing_set) return training_data, testing_data # + # make training and testing data training_data, testing_data = make_train_and_test(ntrain=1,train_set=training_set, test_set=testing_set) # transforming training and testing data to numpy arrays train_sequences = np.array(training_data.x.to_list()) train_labels = np.array(training_data.y.to_list()) test_sequences = np.array(testing_data.x.to_list()) test_labels = np.array(testing_data.y.to_list()) # + # reshape def reshape(array): old_array_shape = array.shape new_array = np.zeros(old_array_shape) new_array = new_array.reshape(new_array.shape + (1,)) for i in range(len(array)): new_array[i] = array[i].reshape(array[i].shape + (1,)) return new_array train_sequences = reshape(train_sequences) train_labels = reshape(train_labels) test_sequences = reshape(test_sequences) test_labels = reshape(test_labels) # - train_sequences.shape # + # Create checkpoints during training checkpoint_path = "DNN/lvl1/cp.ckpt" checkpoint_dir = os.path.dirname(checkpoint_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, monitor='val_loss', save_best_only=True, save_weights_only=False, mode='auto', save_freq='epoch', verbose=1) def create_deep_model(): # Building the Convolutional Neural Network input_size=(environment*2+1,21,1) model = models.Sequential() model.add(layers.Conv2D(64, (3,3), activation='relu', input_shape=input_size, padding='same')) model.add(layers.BatchNormalization()) model.add(layers.Conv2D(64, (3,3), activation='relu', input_shape=input_size, padding='same')) model.add(layers.BatchNormalization()) model.add(layers.Conv2D(64, (3,3), activation='relu', input_shape=input_size, padding='same')) model.add(layers.BatchNormalization()) model.add(layers.Conv2D(64, (3,3), activation='relu', input_shape=input_size, padding='same')) model.add(layers.BatchNormalization()) model.add(layers.Conv2D(64, (3,3), activation='relu', input_shape=input_size, padding='same')) model.add(layers.BatchNormalization()) model.add(layers.Conv2D(64, (3,3), activation='relu', input_shape=input_size, padding='same')) model.add(layers.BatchNormalization()) model.add(layers.Conv2D(64, (3,3), activation='relu', input_shape=input_size)) model.add(layers.BatchNormalization()) model.add(layers.Conv2D(64, (3,3), activation='relu', input_shape=input_size)) model.add(layers.MaxPooling2D((2,2))) model.add(layers.Conv2D(64, (3,3), activation='relu')) model.add(layers.MaxPooling2D((2,2))) model.add(layers.BatchNormalization()) model.add(layers.Conv2D(64, (3,3), activation='relu')) model.add(layers.BatchNormalization()) model.add(layers.Flatten()) tf.keras.layers.Dropout(0.2) model.add(layers.Dense(1600, activation='relu')) model.add(layers.Dense(1600, activation='relu')) model.add(layers.Dense(3, activation='softmax')) # Compile the model model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) return model # - DNN = create_deep_model() DNN.summary() # Training the model history = DNN.fit(train_sequences, train_labels, epochs=20, validation_data=(test_sequences, test_labels), batch_size=512, callbacks= [cp_callback]) # typical batch sizes 64, 128, 256 or 512. # + # list all data in history print(history.history.keys()) # summarize history for accuracy plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() plt.savefig('DNN.png') # -
DNN.ipynb
# <a href="https://colab.research.google.com/github/dmlc/gluon-cv/blob/onnx/scripts/onnx/notebooks/action-recognition/inceptionv3_ucf101.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # !pip3 install --upgrade onnxruntime # + import numpy as np import onnxruntime as rt import urllib.request import os.path from PIL import Image # + def fetch_model(): if not os.path.isfile("inceptionv3_ucf101.onnx"): urllib.request.urlretrieve("https://apache-mxnet.s3-us-west-2.amazonaws.com/onnx/models/gluoncv-inceptionv3_ucf101-d9cda2fd.onnx", filename="inceptionv3_ucf101.onnx") return "inceptionv3_ucf101.onnx" def prepare_img(img_path, input_shape): # input_shape: BHWC height, width = input_shape[1], input_shape[2] img = Image.open(img_path).convert('RGB') img = img.resize((width, height)) img = np.asarray(img) img = np.expand_dims(img, axis=0).astype('float32') return img def prepare_label(): from gluoncv.data import UCF101Attr return UCF101Attr().classes # - # **Make sure to replace the image you want to use** # + model = fetch_model() img_path = "Your input" img = prepare_img(img_path, (1, 299, 299, 3)) label = prepare_label() # + # Create a onnx inference session and get the input name onnx_session = rt.InferenceSession(model, None) input_name = onnx_session.get_inputs()[0].name # + pred = onnx_session.run([], {input_name: img})[0] # - # # (Optional) We use mxnet to process the result. # # Feel free to process the result your own way # # !pip3 install --upgrade mxnet # + import mxnet as mx pred = mx.nd.array(pred) topK = 5 ind = mx.nd.topk(pred, k=topK)[0].astype('int') print('The input is classified to be') for i in range(topK): print(' [%s], with probability %.3f.'% (label[ind[i].asscalar()], mx.nd.softmax(pred)[0][ind[i]].asscalar()))
scripts/onnx/notebooks/action-recognition/inceptionv3_ucf101.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] nbgrader={} # # Ordinary Differential Equations Exercise 3 # + [markdown] nbgrader={} # ## Imports # + nbgrader={} # %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.integrate import odeint from IPython.html.widgets import interact, fixed # + [markdown] nbgrader={} # ## Damped, driven nonlinear pendulum # + [markdown] nbgrader={} # The equations of motion for a simple [pendulum](http://en.wikipedia.org/wiki/Pendulum) of mass $m$, length $l$ are: # # $$ # \frac{d^2\theta}{dt^2} = \frac{-g}{\ell}\sin\theta # $$ # # When a damping and periodic driving force are added the resulting system has much richer and interesting dynamics: # # $$ # \frac{d^2\theta}{dt^2} = \frac{-g}{\ell}\sin\theta - a \omega - b \sin(\omega_0 t) # $$ # # In this equation: # # * $a$ governs the strength of the damping. # * $b$ governs the strength of the driving force. # * $\omega_0$ is the angular frequency of the driving force. # # When $a=0$ and $b=0$, the energy/mass is conserved: # # $$E/m =g\ell(1-\cos(\theta)) + \frac{1}{2}\ell^2\omega^2$$ # + [markdown] nbgrader={} # ### Basic setup # + [markdown] nbgrader={} # Here are the basic parameters we are going to use for this exercise: # + nbgrader={} g = 9.81 # m/s^2 l = 0.5 # length of pendulum, in meters tmax = 50. # seconds t = np.linspace(0, tmax, int(100*tmax)) # + [markdown] nbgrader={} # Write a function `derivs` for usage with `scipy.integrate.odeint` that computes the derivatives for the damped, driven harmonic oscillator. The solution vector at each time will be $\vec{y}(t) = (\theta(t),\omega(t))$. # - odeint. # + nbgrader={"checksum": "c7256bdd25791dfa8322d3b828cec74d", "solution": true} def derivs(y, t, a, b, omega0): """Compute the derivatives of the damped, driven pendulum. Parameters ---------- y : ndarray The solution vector at the current time t[i]: [theta[i],omega[i]]. t : float The current time t[i]. a, b, omega0: float The parameters in the differential equation. Returns ------- dy : ndarray The vector of derviatives at t[i]: [dtheta[i],domega[i]]. """ theta,omega=y dtheta=omega domega=[(-g/l)*np.sin(theta)-a*omega-b*np.sin(omega0*t)] dy=[dtheta,domega] return dy # + deletable=false nbgrader={"checksum": "3509b75989fc0ec30fa07c7a9331e14e", "grade": true, "grade_id": "odesex03a", "points": 2} assert np.allclose(derivs(np.array([np.pi,1.0]), 0, 1.0, 1.0, 1.0), [1.,-1.]) # + nbgrader={"checksum": "eb552816913899d79298c64989e872d4", "solution": true} def energy(y): """Compute the energy for the state array y. The state array y can have two forms: 1. It could be an ndim=1 array of np.array([theta,omega]) at a single time. 2. It could be an ndim=2 array where each row is the [theta,omega] at single time. Parameters ---------- y : ndarray, list, tuple A solution vector Returns ------- E/m : float (ndim=1) or ndarray (ndim=2) The energy per mass. """ theta=y[0,::1] omega=y[1,::1] Em=g*l*(1-np.cos(theta))+.5*l**2*omega**2 return Em # - a=np.ones((10,2)) print(a[::1,0]) # + deletable=false nbgrader={"checksum": "3eda6ae22611b37df76850d7cdc960d0", "grade": true, "grade_id": "odesex03b", "points": 2} #assert np.allclose(energy(np.array([np.pi,0])),g) assert np.allclose(energy(np.ones((10,2))), np.ones(10)*energy(np.array([1,1]))) # + [markdown] nbgrader={} # ### Simple pendulum # + [markdown] nbgrader={} # Use the above functions to integrate the simple pendulum for the case where it starts at rest pointing vertically upwards. In this case, it should remain at rest with constant energy. # # * Integrate the equations of motion. # * Plot $E/m$ versus time. # * Plot $\theta(t)$ and $\omega(t)$ versus time. # * Tune the `atol` and `rtol` arguments of `odeint` until $E/m$, $\theta(t)$ and $\omega(t)$ are constant. # # Anytime you have a differential equation with a a conserved quantity, it is critical to make sure the numerical solutions conserve that quantity as well. This also gives you an opportunity to find other bugs in your code. The default error tolerances (`atol` and `rtol`) used by `odeint` are not sufficiently small for this problem. Start by trying `atol=1e-3`, `rtol=1e-2` and then decrease each by an order of magnitude until your solutions are stable. # + deletable=false nbgrader={"checksum": "6cff4e8e53b15273846c3aecaea84a3d", "solution": true} # YOUR CODE HERE raise NotImplementedError() # + deletable=false nbgrader={"checksum": "6cff4e8e53b15273846c3aecaea84a3d", "solution": true} # YOUR CODE HERE raise NotImplementedError() # + deletable=false nbgrader={"checksum": "6cff4e8e53b15273846c3aecaea84a3d", "solution": true} # YOUR CODE HERE raise NotImplementedError() # + deletable=false nbgrader={"checksum": "afb5bca3311c3e9c7ac5070b15f2435c", "grade": true, "grade_id": "odesex03c", "points": 3} assert True # leave this to grade the two plots and their tuning of atol, rtol. # + [markdown] nbgrader={} # ## Damped pendulum # + [markdown] nbgrader={} # Write a `plot_pendulum` function that integrates the damped, driven pendulum differential equation for a particular set of parameters $[a,b,\omega_0]$. # # * Use the initial conditions $\theta(0)=-\pi + 0.1$ and $\omega=0$. # * Decrease your `atol` and `rtol` even futher and make sure your solutions have converged. # * Make a parametric plot of $[\theta(t),\omega(t)]$ versus time. # * Use the plot limits $\theta \in [-2 \pi,2 \pi]$ and $\theta \in [-10,10]$ # * Label your axes and customize your plot to make it beautiful and effective. # + nbgrader={"checksum": "82dc6206b4de351b8afc48dba9d0b915", "solution": true} def plot_pendulum(a=0.0, b=0.0, omega0=0.0): """Integrate the damped, driven pendulum and make a phase plot of the solution.""" # YOUR CODE HERE raise NotImplementedError() # + [markdown] nbgrader={} # Here is an example of the output of your `plot_pendulum` function that should show a decaying spiral. # + nbgrader={} plot_pendulum(0.5, 0.0, 0.0) # + [markdown] nbgrader={} # Use `interact` to explore the `plot_pendulum` function with: # # * `a`: a float slider over the interval $[0.0,1.0]$ with steps of $0.1$. # * `b`: a float slider over the interval $[0.0,10.0]$ with steps of $0.1$. # * `omega0`: a float slider over the interval $[0.0,10.0]$ with steps of $0.1$. # + deletable=false nbgrader={"checksum": "6cff4e8e53b15273846c3aecaea84a3d", "solution": true} # YOUR CODE HERE raise NotImplementedError() # + [markdown] nbgrader={} # Use your interactive plot to explore the behavior of the damped, driven pendulum by varying the values of $a$, $b$ and $\omega_0$. # # * First start by increasing $a$ with $b=0$ and $\omega_0=0$. # * Then fix $a$ at a non-zero value and start to increase $b$ and $\omega_0$. # # Describe the different *classes* of behaviors you observe below. # + [markdown] deletable=false nbgrader={"checksum": "40364759d02737525e2503b814608893", "grade": true, "grade_id": "odesex03d", "points": 3, "solution": true} # YOUR ANSWER HERE
assignments/assignment10/ODEsEx03.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.7 64-bit (''machinelearning'': conda)' # name: python3 # --- # + import os import tarfile import urllib.request import pandas as pd DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/" HOUSING_PATH = os.path.join("datasets", "housing") HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz" def fetch_housing_data(housing_url=HOUSING_URL,housing_path=HOUSING_PATH): os.makedirs(housing_path,exist_ok=True) tgz_path = os.path.join(housing_path,"housing.tgz") urllib.request.urlretrieve(housing_url, tgz_path) housing_tgz = tarfile.open(tgz_path) housing_tgz.extractall(path=housing_path) housing_tgz.close() def load_housing_data(housing_path=HOUSING_PATH): csv_path = os.path.join(housing_path,"housing.csv") return pd.read_csv(csv_path) # + #running the functions to fetch and load data fetch_housing_data() housing = load_housing_data() #getting the dataframe information: print(housing.head()) print(housing.info()) print(housing.describe()) print(housing["ocean_proximity"].value_counts()) # - #data viusualization: import matplotlib.pyplot as plt housing.hist(bins=50, figsize=(20,15)) plt.show() #spliting the data into training and testing sets: from sklearn.model_selection import train_test_split train_set,test_set=train_test_split(housing,test_size=0.25,random_state=42) #defining the income categories: import numpy as np housing["income_cat"]= pd.cut(housing["median_income"],bins=[0.,1.5,3,4.5,6.,np.inf],labels=[1,2,3,4,5]) housing["income_cat"].hist() plt.show() # + from sklearn.model_selection import StratifiedShuffleSplit split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42) for train_index, test_index in split.split(housing,housing["income_cat"]): strat_train_set=housing.loc[train_index] strat_test_set=housing.loc[test_index] #droping the income cat columns of the set: for set_ in (strat_train_set,strat_test_set): set_.drop("income_cat", axis=1, inplace=True) # - #exploring the data through visualization: housing=strat_train_set.copy() housing.plot(kind="scatter",x="longitude",y="latitude",alpha=0.1) #exploring the data through visualization: housing=strat_train_set.copy() housing.plot(kind="scatter",x="longitude",y="latitude",alpha=0.4,s=housing["population"]/100,label="population",figsize=(10,7),c="median_house_value",cmap=plt.get_cmap("jet")) plt.legend() plt.show() # + #explorign the data through corelation matrix: corr_matrix = housing.corr() housing.head() print(list(enumerate(housing.keys()))) print(corr_matrix["median_house_value"].sort_values(ascending=False)) plt.matshow(housing.corr()) plt.show() # - #explorign the data through correlation plots: from pandas.plotting import scatter_matrix attrbutes=['median_house_value','median_income','total_rooms','housing_median_age'] scatter_matrix(housing[attrbutes],figsize=(12,8)) print(list(enumerate(housing.keys()))) # + #defining new attributes for the dataset: housing["rooms_per_household"]=housing["total_rooms"]/housing["households"] housing["bedrooms_per_room"]=housing["total_bedrooms"]/housing["total_rooms"] housing["population_per_household"]=housing["population"]/housing["households"] corr_matrix = housing.corr() print(corr_matrix["median_house_value"].sort_values(ascending=False)) plt.matshow(housing.corr()) plt.show() # + #preparing the data for machine learning implementation: #clean start: housing = strat_train_set.drop("median_house_value",axis=1) housing_labels = strat_train_set["median_house_value"].copy() #replaceing the NaN values with the calculated mean. ''' median = housing["total_bedrooms"].median() housing["total_bedrooms"].fillna(median,inplace=True) ''' from sklearn.impute import SimpleImputer imputer = SimpleImputer(strategy="mean") #only numerical data: housing_num = housing.drop("ocean_proximity",axis=1) imputer.fit(housing_num) #creating final traingin data: X = imputer.transform(housing_num) housing_tr=pd.DataFrame(X,columns=housing_num.columns,index=housing_num.index) print(X) print(housing_tr) # - #transfering categorical variables into numeric description: - machine learning algoritms dont work on text they work on vectors/tensors from sklearn.preprocessing import OneHotEncoder cat_econder = OneHotEncoder() housing_cat=housing[["ocean_proximity"]] housing_cat_1hot = cat_econder.fit_transform(housing_cat) #print(housing_cat_1hot) print(housing_cat_1hot.toarray()) print(cat_econder.categories_) #reminder on what is housing data: print(type(housing)) #a DataFrame print(housing.head()) print(housing.keys()) print(housing.values) #creating custom transformers: from sklearn.base import BaseEstimator, TransformerMixin #defining indexes of attibutes in the dataset: rooms_ix, bedrooms_ix, population_ix,households_ix= 3,4,5,6 #defining the class that inherits from sklearn transformers to enable adding parameters to the dataset: class CombinedAttibutesAdder(BaseEstimator,TransformerMixin): def __init__(self,add_bedrooms_per_room=True): self.add_bedrooms_per_room = add_bedrooms_per_room def fit(self,X,y=None): return self def transform(self,X): rooms_per_household=X[:,rooms_ix]/X[:,households_ix] population_per_household=X[:,population_ix]/X[:,households_ix] if self.add_bedrooms_per_room: bedrooms_per_room=X[:,bedrooms_ix]/X[:,rooms_ix] return np.c_[X,rooms_per_household,population_per_household,bedrooms_per_room] else: return np.c_[X,rooms_per_household,population_per_household] #read up on what np.c_ does! - arrays concatination along axis. ''' np.c_[np.array([1,2,3]), np.array([4,5,6])] array([[1, 4], [2, 5], [3, 6]]) ''' attr_adder=CombinedAttibutesAdder(add_bedrooms_per_room=False) housing_extra_attirbs = attr_adder.transform(housing.values) # + #feature scaling for optimal learning experience :) #STANDARDIZATION & MIN-MAX SCALING as two basica algorythms: #sklearn PIPELINES: - execution of data transfromations in a tipical order: from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer num_pipeline = Pipeline([ #imputer allows to clean the data form NANs and replace them with median values: ("imputer",SimpleImputer(strategy="median")), #attribs_adder has been defined in a previous block as a class that allows to extend the attributes: ("attribs_adder",CombinedAttibutesAdder()), #std_scaler standardizes the data: ("std_scaler",StandardScaler()), ]) #learning ready data: housing_num_tr = num_pipeline.fit_transform(housing_num) # + #Column transformer - allows to perform transformations of a pipeline column by column and distinguish numeriacal and cathegorical data: from sklearn.compose import ColumnTransformer """ print(housing_num) print(list(housing_num)) """ num_attribs=list(housing_num) cat_attribs=["ocean_proximity"] #combined pipeline that applies different transformations based on the attibutes of the datafarme: full_pipeline = ColumnTransformer([ ("num",num_pipeline,num_attribs), ("cat",OneHotEncoder(),cat_attribs), ]) housing_prepared=full_pipeline.fit_transform(housing) housing_labels = strat_train_set["median_house_value"].copy() # - print(housing) # + #choosing the model and training: #linear regression model: from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(housing_prepared,housing_labels) #testing the model: some_data = housing.iloc[:5] some_labels = housing_labels.iloc[:5] some_data_prepared = housing_prepared[:5] print("Predictions: ",lin_reg.predict(some_data_prepared)) print("Actual Values: ",list(some_labels)) print(lin_reg.score(some_data_prepared,some_labels)) #model underfitting # + #choosing the model and training: #decision tree model: from sklearn.tree import DecisionTreeRegressor tree_reg = DecisionTreeRegressor() tree_reg.fit(housing_prepared,housing_labels) #testing the model: some_data = housing.iloc[:5] some_labels = housing_labels.iloc[:5] some_data_prepared = housing_prepared[:5] print("Predictions: ",tree_reg.predict(some_data_prepared)) print("Actual Values: ",list(some_labels)) print(tree_reg.score(some_data_prepared,some_labels)) #model overfitting # + #model cross validation for more precise understanding of performance: from sklearn.model_selection import cross_val_score scores = cross_val_score(tree_reg,housing_prepared,housing_labels,scoring="neg_mean_squared_error",cv=10) tree_rmse_scores = np.sqrt(-scores) # + def display_scores(scores): print("Scores: ",scores) print("Mean :",scores.mean()) print("Standard Deviation :",scores.std()) display_scores(tree_rmse_scores) # - lin_scores = cross_val_score(lin_reg,housing_prepared,housing_labels,scoring="neg_mean_squared_error",cv=10) lin_rmse_scores = np.sqrt(-lin_scores) # + def display_scores(scores): print("Scores: ",scores) print("Mean :",scores.mean()) print("Standard Deviation :",scores.std()) display_scores(lin_rmse_scores) # + from sklearn.ensemble import RandomForestRegressor forest_reg = RandomForestRegressor() forest_reg.fit(housing_prepared,housing_labels) #testing the model: some_data = housing.iloc[:5] some_labels = housing_labels.iloc[:5] some_data_prepared = housing_prepared[:5] print("Predictions: ",forest_reg.predict(some_data_prepared)) print("Actual Values: ",list(some_labels)) print(tree_reg.score(some_data_prepared,some_labels)) forest_scores = cross_val_score(forest_reg,housing_prepared,housing_labels,scoring="neg_mean_squared_error",cv=10) forest_rmse_scores = np.sqrt(-forest_scores) def display_scores(scores): print("Scores: ",scores) print("Mean :",scores.mean()) print("Standard Deviation :",scores.std()) display_scores(forest_rmse_scores) # + #Finetuning the models: #01.Grid search #02.Randomize search #03.Ensemble methods from sklearn.model_selection import GridSearchCV param_grid = [ # try 12 (3×4) combinations of hyperparameters {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]}, # then try 6 (2×3) combinations with bootstrap set as False {'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]}, ] forest_reg = RandomForestRegressor(random_state=42) # train across 5 folds, that's a total of (12+6)*5=90 rounds of training grid_search = GridSearchCV(forest_reg, param_grid, cv=5, scoring='neg_mean_squared_error', return_train_score=True) grid_search.fit(housing_prepared, housing_labels) # - grid_search.best_params_ grid_search.best_estimator_ # + cvres = grid_search.cv_results_ for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]): print(np.sqrt(-mean_score), params) pd.DataFrame(grid_search.cv_results_) # + feature_importances = grid_search.best_estimator_.feature_importances_ feature_importances extra_attribs = ["rooms_per_hhold", "pop_per_hhold", "bedrooms_per_room"] #cat_encoder = cat_pipeline.named_steps["cat_encoder"] # old solution cat_encoder = full_pipeline.named_transformers_["cat"] cat_one_hot_attribs = list(cat_encoder.categories_[0]) attributes = num_attribs + extra_attribs + cat_one_hot_attribs sorted(zip(feature_importances, attributes), reverse=True) # + from sklearn.metrics import mean_squared_error final_model = grid_search.best_estimator_ housing = strat_train_set.drop("median_house_value",axis=1) housing_labels = strat_train_set["median_house_value"].copy() housing_prepared=full_pipeline.fit_transform(housing) housing_test = strat_test_set.drop("median_house_value",axis=1) housing_test_lables = strat_test_set["median_house_value"].copy() housing_test_prepared=full_pipeline.fit_transform(housing) final_predictions = final_model.predict(housing_test_prepared) final_score = final_model.score(housing_test_prepared,housing_labels) print(final_score)
Chapter_02_End_to_End_Machine_Learning_Project/End_to_End_Machine_Learning_Project.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 # --- import pandas as pd import sys import matplotlib water23 = pd.read_csv("../data/waterlevel/Water23.csv", index_col='date') # %pylab inline climate = pd.read_csv("../data/waterlevel/ClimateWater.csv", index_col='date') climate newindex = [] for ind in water23.index: newindex.append(ind.split()[0]) vals, inds = np.unique(newindex, return_inverse=True) # + upperh_med = np.ones(vals.size)*np.nan downh_med = np.ones(vals.size)*np.nan upperh_std = np.ones(vals.size)*np.nan downh_std = np.ones(vals.size)*np.nan for i in range (vals.size): active = inds==i upperh_med[i] = np.median(water23["upperlevel"].values[active]) downh_med[i] = np.median(water23["downlevel"].values[active]) upperh_std[i] = np.std(water23["upperlevel"].values[active]) downh_std[i] = np.std(water23["downlevel"].values[active]) # - date = climate.index.values climate.keys() actind = np.in1d(date, vals) upperh = np.ones(date.size)*np.nan downh = np.ones(date.size)*np.nan upperh[actind] = upperh_med downh[actind] = downh_med waterdataset = list (zip(date, climate['WaterH1'].values, upperh, downh,\ climate['Rainfall(mm)'].values, climate['SurfaceTemp(surC)'].values, climate['Moisture(%)'].values)) df = pd.DataFrame(data = waterdataset, columns=['date', 'reservoirH', 'upperH_med', 'downH_med',\ 'Rainfall (mm)', 'Temp (degree)', 'Moisture (percent)']) df.set_index('date') df['upperH_med'].plot(figsize=(20,3),color='k') # + fig = plt.figure(figsize=(12,4)) ax1 = plt.subplot(111) ax1_1 = ax1.twinx() df['upperH_med'].plot(figsize=(20,3), ax=ax1, color='k') df['reservoirH'].plot(figsize=(20,3), ax=ax1, color='b') df['downH_med'].plot(figsize=(20,3), ax=ax1_1, color='r') grid(True) # - df.keys() ax1 = plt.subplot(111) ax1_1 = ax1.twinx() df.plot(figsize=(12,3), x='date', y='reservoirH', ax=ax1, color='k', linestyle='-', lw=2, marker='.', ms=2) df.plot(figsize=(12,3), x='date', y='upperH_med', ax=ax1, color='k', linestyle='--', lw=2) df.plot(figsize=(12,3), x='date', y='downH_med', ax=ax1_1, color='r', linestyle='-') ax1_1.legend(loc=4) ax1.grid(True) indst, indend = 80, 100 ax1.plot(np.r_[indst, indst], np.r_[28, 42], 'k-') ax1.plot(np.r_[indend, indend], np.r_[28, 42], 'k--') print df['date'].values[indst], df['date'].values[indst] # ax1.set_ylim(39.5, 40.5) # ax1.set_xlim(indst, indend) ax1 = plt.subplot(111) ax1_1 = ax1.twinx() df.plot(figsize=(12,3), x='date', y='reservoirH', ax=ax1, color='k', linestyle='-', lw=2, marker='.', ms=2) df.plot(figsize=(12,3), x='date', y='upperH_med', ax=ax1, color='k', linestyle='--', lw=2) df.plot(figsize=(12,3), x='date', y='downH_med', ax=ax1_1, color='r', linestyle='-') ax1_1.legend(loc=4) ax1.grid(True) indst, indend = 80, 100 ax1.plot(np.r_[indst, indst], np.r_[28, 42], 'k-') ax1.plot(np.r_[indend, indend], np.r_[28, 42], 'k--') print df['date'].values[indst], df['date'].values[indst] ax1.set_ylim(39.5, 40.5) ax1.set_xlim(indst, indend) ax1 = plt.subplot(111) df.plot(figsize=(12,3), x='date', y='Rainfall (mm)', ax=ax1, color='b', marker='o', linestyle="-", ms=3) df.plot(figsize=(12,3), x='date', y='Temp (degree)', ax=ax1, color='k', marker='None', linestyle="-", ms=3) plt.tight_layout() # + import sys sys.path.append("../codes/") from Readfiles import getFnames from DCdata import readReservoirDC_data, readReservoirDC_all directory = "../data/ChungCheonDC/" fnames = getFnames(directory, dtype="apr", minimumsize=7000.) # - import datetime import numpy as np def getdate(fstring): temp = fstring.split('.')[0] return datetime.date(int(temp[:4]), int(temp[4:6]), int(temp[6:8])) date_temp = getdate(fnames[20]) date_temp.strftime("%Y-%m-%d") # + # for i in range (vals.size): # active = inds==i # upperh_med[i] = np.median(water23["upperlevel"].values[active]) # downh_med[i] = np.median(water23["downlevel"].values[active]) # upperh_std[i] = np.std(water23["upperlevel"].values[active]) # downh_std[i] = np.std(water23["downlevel"].values[active]) # - dat_temp, htemp, ID = readReservoirDC_all(directory+fnames[0]) ID.append('date') ID.append('fnames') ntimes = len(fnames) DATA = np.zeros((dat_temp.shape[0], ntimes))*np.nan index = np.ones(ntimes, dtype='bool') for i, fname in enumerate(fnames): dat_temp = readReservoirDC_data(directory+fname) if dat_temp.shape[0] == 380: DATA[:,i] = dat_temp[:,-1] else: print fname,dat_temp.shape[0] index[i] = False fnameDC = np.array(fnames)[index] datesDC = [] for i in range(fnameDC.size): tempdate = getdate(fnameDC[i]) datesDC.append(tempdate.strftime("%Y-%m-%d")) datesDC = np.array(datesDC) datesDC.size vals, inds = np.unique(datesDC, return_inverse=True) DATA_active = DATA[:,index] DATA_DC = np.zeros((vals.size,DATA.shape[0]))*np.nan DATA_DC_std = np.zeros((vals.size,DATA.shape[0]))*np.nan for i in range (vals.size): active = inds==i DATA_DC[i,:] = np.median(DATA_active[:,active], axis=1) DATA_DC_std[i,:] = np.std(DATA_active[:,active], axis=1) actind = np.in1d(date, vals) DATA_DC_final = np.zeros((365,DATA.shape[0]))*np.nan DATA_DC_std_final = np.zeros((365,DATA.shape[0]))*np.nan DATA_DC_final[actind,:] = DATA_DC DATA_DC_std_final[actind,:] = DATA_DC_std DATA_DC_final.shape date.shape DATA_DC_std_final.shape date.reshape([-1,1]).shape len(ID) date len(ID) DATA_DC_std_final.shape DATA_DC_std_final df_DCstd = pd.DataFrame(data = np.hstack((DATA_DC_std_final, date.reshape([-1,1]))), columns=ID[:-1]) df_DCstd.set_index('date') df_DC = pd.DataFrame(data = np.hstack((DATA_DC_final, date.reshape([-1,1]))), columns=ID[:-1]) df_DC.set_index('date') df.to_csv("../data/ChungCheonDC/CompositeETCdata.csv") df_DC.to_csv("../data/ChungCheonDC/CompositeDCdata.csv") df_DCstd.to_csv("../data/ChungCheonDC/CompositeDCstddata.csv")
notebook/CompositeData-Lim.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 # --- #Importing libraries import os import pandas as pd import numpy as np df=pd.read_csv("day.csv") df.shape df.head(10) df.isnull().sum() df.describe() df.dtypes df=df.drop(['instant'],axis=1) df['season']=df['season'].astype('category') #converting to correct format df['yr']=df['yr'].astype('category') df['mnth']=df['mnth'].astype('category') df['holiday']=df['holiday'].astype('category') df['weekday']=df['weekday'].astype('category') df['workingday']=df['workingday'].astype('category') df['weathersit']=df['weathersit'].astype('category') df.dtypes # # Data Distribution import matplotlib.pyplot as plt import seaborn as sns figs, axes = plt.subplots(2, 2, figsize=(20, 10), dpi=100) sns.distplot(df['temp'] , color="dodgerblue", ax=axes[0][0], axlabel='temp') sns.distplot(df['atemp'] , color="deeppink", ax=axes[0][1], axlabel='atemp') sns.distplot(df['hum'] , color="gold", ax=axes[1][0], axlabel='hum') sns.distplot(df['windspeed'] , color="black", ax=axes[1][1], axlabel='windspeed') df['season_name'] = df['season'].replace([1,2,3,4],["Spring","Summer","Fall","Winter"]) df['yr_num'] = df['yr'].replace([0,1],["2011","2012"]) df['holiday_label'] = df['holiday'].replace([0,1],["Working day","Holiday"]) df['weathersit_name'] = df['weathersit'].replace([1,2,3,4],["Clear","Cloudy/Mist","Rain/Snow/Fog","Heavy Rain/Snow/Fog"]) sns.factorplot(data=df, x='season_name', kind= 'count') sns.factorplot(data=df, x='weathersit_name', kind= 'count') sns.factorplot(data=df, x='holiday_label', kind= 'count') sns.factorplot(data=df, x='yr_num', kind= 'count') sns.factorplot(data=df, x='mnth', kind= 'count') df['holiday_label'].value_counts() # # Relationship between Independent and Dependent Variable import datetime import calendar df['dteday']=df['dteday'].astype('str') df1=[] for i in range(len(df)): a=datetime.datetime.strptime(df.loc[i,'dteday'],'%Y-%m-%d').weekday() df1.append(calendar.day_name[a]) df['day']=df1 df.head(10) fig, axes=plt.subplots(2,1, figsize=(7,7)) sns.boxplot(x='weathersit_name',y='casual',ax=axes[0], data=df) sns.boxplot(x='weathersit_name',y='registered',ax=axes[1], data=df) numeric_df=df.select_dtypes(include=float) numeric_df['cnt']=df['cnt'] l=numeric_df.columns numeric_df.head(10) c=['dodgerblue','deeppink','orange','green'] fig, axes=plt.subplots(1,len(l)-1, figsize=(20,7)) a=len(l)-1 for i in range(a): sns.boxplot(y=l[i],ax=axes[i], color=c[i], data=numeric_df) q75, q25 = np.percentile(df['windspeed'], [75 ,25]) print(q75,q25) iqr = q75 - q25 print(iqr) min = q25 - (iqr*1.5) max = q75 + (iqr*1.5) print(min) print(max) df_1 = df.drop(df[df.loc[:,'windspeed'] < min].index) dfout = df_1.drop(df_1[df_1.loc[:,'windspeed'] > max].index) dfout.shape dfout.head(10) # # Correlation Analysis dfcor=dfout.drop(['season_name','weathersit_name','yr_num','holiday_label','dteday','day'],axis=1) dfcor['season']=dfout['season'].astype('int') #converting to correct format for Correlation Analysis dfcor['yr']=dfout['yr'].astype('int') dfcor['mnth']=dfout['mnth'].astype('int') dfcor['holiday']=dfout['holiday'].astype('int') dfcor['weekday']=dfout['weekday'].astype('int') dfcor['workingday']=dfout['workingday'].astype('int') dfcor['weathersit']=dfout['weathersit'].astype('int') cor_mat= dfcor[:].corr() mask = np.array(cor_mat) mask[np.tril_indices_from(mask)] = False fig=plt.gcf() fig.set_size_inches(20,10) sns.heatmap(data=cor_mat,mask=mask,square=True,annot=True,cbar=True) dfout.describe() # # Final Input Dataframe df_final=dfout.drop(['holiday','season_name','weathersit_name','yr_num','holiday_label', 'dteday','day','atemp','casual','registered'],axis=1) df_final.dtypes df_final.shape # # Sampling # sampling from sklearn.model_selection import train_test_split train,test = train_test_split(df_final, test_size = 0.2, random_state = 123) train.shape # # Multivariate Linear Regression import statsmodels.api as sm sns.distplot(df_final['cnt']) mlr_model = sm.OLS(train.iloc[:,9].astype(float), train.iloc[:,0:9].astype(float)).fit() mlr_model.summary() mlr_predictions = mlr_model.predict(test.iloc[:,0:9]) df_mlr = pd.DataFrame({'actual': test.iloc[:,9], 'pred': mlr_predictions}) df_mlr.head() #Function for Mean Absolute Percentage Error def MAPE(y_actual,y_pred): mape = np.mean(np.abs((y_actual - y_pred)/y_actual)*100) return mape MAPE(test.iloc[:,9],mlr_predictions) # # Decision Tree from sklearn.tree import DecisionTreeRegressor tree_model = DecisionTreeRegressor(random_state=123).fit(train.iloc[:,0:9], train.iloc[:,9]) tree_predictions = tree_model.predict(test.iloc[:,0:9]) df_tree = pd.DataFrame({'actual': test.iloc[:,9], 'pred': tree_predictions}) df_tree.head() MAPE(test.iloc[:,9],tree_predictions) # # Random Forest from sklearn.ensemble import RandomForestRegressor rf_model = RandomForestRegressor(n_estimators=500,random_state=123).fit(train.iloc[:,0:9], train.iloc[:,9]) rf_predictions = rf_model.predict(test.iloc[:,0:9]) df_rf = pd.DataFrame({'actual': test.iloc[:,9], 'pred': rf_predictions}) df_rf.head() #Calculate MAPE MAPE(test.iloc[:,9],rf_predictions) # # XGBoost import xgboost as xgb #One hot encoding ONE_HOT_COLS = ["season", "mnth", "weekday","weathersit"] print("Starting DF shape: %d, %d" % df_final.shape) df_x=df_final.copy() for col in ONE_HOT_COLS: s = df_x[col].unique() # Create a One Hot Dataframe with 1 row for each unique value one_hot_df = pd.get_dummies(s, prefix='%s_' % col) one_hot_df[col] = s print("Adding One Hot values for %s (the column has %d unique values)" % (col, len(s))) pre_len = len(df_x) # Merge the one hot columns df_x = df_x.merge(one_hot_df, on=[col], how="left") assert len(df_x) == pre_len print(df_x.shape) df_xg=df_x.copy() df_xg['workingday']=df_xg['workingday'].astype('uint8') df_xg['yr']=df_xg['yr'].astype('uint8') df_xg.dtypes df_xg=df_xg.drop(['season','weekday','mnth','weathersit','season__4','weekday__6','mnth__12','weathersit__3'], axis=1).reset_index(drop=True) final_y=df_xg.pop('cnt') final_x=df_xg from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(final_x, final_y, test_size=0.2, random_state=123) xgdmat=xgb.DMatrix(X_train,y_train) our_params={'eta':0.3,'subsample':0.8,'colsample_bytree':0.8,'objective':'reg:squarederror', 'max_depth':5} final_gb=xgb.train(our_params,xgdmat) tesdmat=xgb.DMatrix(X_test) y_pred=final_gb.predict(tesdmat) print(y_pred) MAPE(y_test,y_pred) xgbRegressor = xgb.XGBRegressor(n_estimators=1000, learning_rate=0.008, objective='reg:squarederror', subsample=0.8,colsample_bytree=0.8, reg_lambda=0.15, reg_alpha=0.15, max_depth=5) xgbRegressor.fit(X_train,y_train) y_pred2 = xgbRegressor.predict(X_test) MAPE(y_test,y_pred2)
Report Code 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 # --- # # 1-2 Intro Python Practice # ## Strings: input, testing, formatting # <font size="5" color="#00A0B2" face="verdana"> <B>Student will be able to</B></font> # - gather, store and use string `input()` # - format `print()` output # - test string characteristics # - format string output # - search for a string in a string # ## input() # getting input from users # [ ] get user input for a variable named remind_me print ('remind me to ') remind_me = input() # [ ] print the value of the variable remind_me print ('remind me to ' + remind_me) # use string addition to print "remember: " before the remind_me input string print("remember: " + "remind me to " + remind_me) # ### Program: Meeting Details # #### [ ] get user **input** for meeting subject and time # `what is the meeting subject?: plan for graduation` # `what is the meeting time?: 3:00 PM on Monday` # # #### [ ] print **output** with descriptive labels # `Meeting Subject: plan for graduation` # `Meeting Time: 3:00 PM on Monday` # + # [ ] get user input for 2 variables: meeting_subject and meeting_time print ("what is the meeting subject?: ") meeting_subject = input ("") print ("what is the meeting time?") meeting_time = input ("") # [ ] use string addition to print meeting subject and time with labels print ("Meeting Subject: " + meeting_subject) print ("Meeting Time: " + meeting_time) # - # ## print() formatting # ### combining multiple strings separated by commas in the print() function # + # [ ] print the combined strings "Wednesday is" and "in the middle of the week" print("Wednesday is", "in the middle of the week.") # + # [ ] print combined string "Remember to" and the string variable remind_me from input above print("Remember to", remind_me) # + # [ ] Combine 3 variables from above with multiple strings print("Before we", meeting_subject, "remind me to " + remind_me, "at", meeting_time) # - # ### print() quotation marks # + # [ ] print a string sentence that will display an Apostrophe (') print ("Rodney's grades are depending on his personal performance") # + # [ ] print a string sentence that will display a quote(") or quotes print ('Rodney stated "Homework is imperative to learning Python"') # - # ## Boolean string tests # ### Vehicle tests # #### get user input for a variable named vehicle # print the following tests results # - check True or False if vehicle is All alphabetical characters using .isalpha() # - check True or False if vehicle is only All alphabetical & numeric characters # - check True or False if vehicle is Capitalized (first letter only) # - check True or False if vehicle is All lowercase # - **bonus** print description for each test (e.g.- `"All Alpha: True"`) # + # [ ] complete vehicle tests print("vehicle".isalpha()) print("vehicle".isalnum()) print("vehicle".istitle()) print("vehicle".islower()) # - # [ ] print True or False if color starts with "b" print ("color".startswith("b")) # ## Sting formatting # [ ] print the string variable capital_this Capitalizing only the first letter capitalize_this = "the TIME is Noon." print(capitalize_this.capitalize()) # print the string variable swap_this in swapped case swap_this = "wHO writes LIKE tHIS?" print(swap_this.swapcase()) # + # print the string variable whisper_this in all lowercase whisper_this = "Can you hear me?" print(whisper_this.lower()) # - # print the string variable yell_this in all UPPERCASE yell_this = "Can you hear me Now!?" print (yell_this.upper()) #format input using .upper(), .lower(), .swapcase, .capitalize() format_input = input('enter a string to reformat: ') print(format_input.upper()) print(format_input.lower()) print(format_input.swapcase()) print(format_input.capitalize()) # ### input() formatting # [ ] get user input for a variable named color color = input() # [ ] modify color to be all lowercase and print print (color.lower()) # [ ] get user input using variable remind_me and format to all **lowercase** and print remind_me = input() print(remind_me.lower()) # [ ] test using input with mixed upper and lower cases print(remind_me.isupper()) print(remind_me.islower()) # [] get user input for the variable yell_this and format as a "YELL" to ALL CAPS yell_this = input() print(yell_this.upper()) # ## "in" keyword # ### boolean: short_str in long_str # + # [ ] get user input for the name of some animals in the variable animals_input animals_input = input () # [ ] print true or false if 'cat' is in the string variable animals_input print('cat' in animals_input) # + # [ ] get user input for color color = input() # [ ] print True or False for starts with "b" print(color.startswith('b')) # [ ] print color variable value exactly as input # test with input: "Blue", "BLUE", "bLUE" print (color) print ('Blue' in color) print ('BLUE' in color) print ('bLUE'.lower()in color) # - # ## Program: guess what I'm reading # ### short_str in long_str # # 1. **[ ]** get user **`input`** for a single word describing something that can be read # save in a variable called **can_read** # e.g. - "website", "newspaper", "blog", "textbook" # &nbsp; # 2. **[ ]** get user **`input`** for 3 things can be read # save in a variable called **can_read_things** # &nbsp; # # 3. **[ ]** print **`true`** if the **can_read** string is found # **in** the **can_read_things** string variable # # *example of program input and output* # [![01 02 practice Allergy-input](https://iajupyterprodblobs.blob.core.windows.net/imagecontainer/guess_reading.gif) ](https://1drv.ms/i/s!Am_KPRosgtaij7A_G6RtDlWZeYA3ZA) # # + # project: "guess what I'm reading" # 1[ ] get 1 word input for can_read variable can_read = input("enter 1 word item than can be read: ") # 2[ ] get 3 things input for can_read_things variable can_read_things = input("enter 3 items that can be read: ") # 3[ ] print True if can_read is in can_read_things print (can_read in can_read_things) # [] challenge: format the output to read "item found = True" (or false) # hint: look print formatting exercises print ('item found = ', "blog" in can_read_things) # - # ## Program: Allergy Check # # 1. **[ ]** get user **`input`** for categories of food eaten in the last 24 hours # save in a variable called **input_test** # *example input* # [![01 02 practice Allergy-input](https://iajupyterprodblobs.blob.core.windows.net/imagecontainer/eaten_input.gif) ](https://1drv.ms/i/s!Am_KPRosgtaij65qzFD5CGvv95-ijg) # &nbsp; # 2. **[ ]** print **`True`** if "dairy" is in the **input_test** string # **[ ]** Test the code so far # &nbsp; # 3. **[ ]** modify the print statement to output similar to below # *example output* # [![01 02 Allergy output](https://iajupyterprodblobs.blob.core.windows.net/imagecontainer/eaten_output.gif) ](https://1drv.ms/i/s!Am_KPRosgtaij65rET-wmlpCdMX7CQ) # Test the code so far trying input including the string "dairy" and without # &nbsp; # # 4. **[ ]** repeat the process checking the input for "nuts", **challenge** add "Seafood" and "chocolate" # **[ ]** Test your code # &nbsp; # # 5. **[ ] challenge:** make your code work for input regardless of case, e.g. - print **`True`** for "Nuts", "NuTs", "NUTS" or "nuts" # # + # Allergy check # 1[ ] get input for test input_test =input("enter something eaten in last 24 hrs") # 2/3[ ] print True if "dairy" is in the input or False if not print('It is True that "seafood, dairy, nuts, and chocolate cake" contains "diary" =', 'dairy' in input_test) # 4[ ] Check if "nuts" are in the input print ("nuts".lower() in input_test.lower()) # 4+[ ] Challenge: Check if "seafood" is in the input print ("seafood" in input_test) # 4+[ ] Challenge: Check if "chocolate" is in the input print ("chocolate" in input_test) # - # [Terms of use](http://go.microsoft.com/fwlink/?LinkID=206977) &nbsp; [Privacy & cookies](https://go.microsoft.com/fwlink/?LinkId=521839) &nbsp; © 2017 Microsoft
Python Absolute Beginner/Module_1_Practice_2_IntroPy.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 # # ### Powerful PyTorch # # #### Accompanying notebook to Video 1.1 # + # Import libs from __future__ import print_function import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader import random import time # - # Setup globals batch_size = 1 in_features = 10 hidden = 20 out_features = 1 # Sequential API example # Create model model = nn.Sequential( nn.Linear(in_features, hidden), nn.ReLU(), nn.Linear(hidden, out_features) ) print(model) # Create dummy input x = Variable(torch.randn(batch_size, in_features)) # Run forward pass output = model(x) print(output) # + # Functional API example # Create model class CustomNet(nn.Module): def __init__(self, in_features, hidden, out_features): """ Create three linear layers """ super(CustomNet, self).__init__() self.linear1 = nn.Linear(in_features, hidden) self.linear2 = nn.Linear(hidden, hidden) self.linear3 = nn.Linear(hidden, out_features) def forward(self, x): """ Draw a random number from [0, 10]. If it's 0, skip the second layer. Otherwise loop it! """ x = F.relu(self.linear1(x)) while random.randint(0, 10) != 0: #while x.norm() > 2: print('2nd layer used') x = F.relu(self.linear2(x)) x = self.linear3(x) return x custom_model = CustomNet(in_features, hidden, out_features) print(custom_model) # - # Run forward pass with same dummy variable output = custom_model(x) print(output) # + # ConvNet example # - # ![ConvNet](images/conv_functional2.png) # + # Debug example # Create Convnet class ConvNet(nn.Module): def __init__(self, in_channels, hidden, out_features): """ Create ConvNet with two parallel convolutions """ super(ConvNet, self).__init__() self.conv1_1 = nn.Conv2d(in_channels=in_channels, out_channels=10, kernel_size=3, padding=1) self.conv1_2 = nn.Conv2d(in_channels=in_channels, out_channels=10, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(in_channels=20, out_channels=1, kernel_size=3, padding=1) self.linear1 = nn.Linear(hidden, out_features) def forward(self, x): """ Pass input through both ConvLayers and stack them afterwards """ x1 = F.relu(self.conv1_1(x)) x2 = F.relu(self.conv1_2(x)) x = torch.cat((x1, x2), dim=1) x = self.conv2(x) print('x size (after conv2): {}'.format(x.shape)) x = x.view(x.size(0), -1) x = self.linear1(x) return x conv_model = ConvNet(in_channels=3, hidden=576, out_features=out_features) # Create dummy input x_conv = Variable(torch.randn(batch_size, 3, 24, 24)) # - # Run forward pass output = conv_model(x_conv) print(output) ## Dataset / DataLoader example # Create a random Dataset class RandomDataset(Dataset): def __init__(self, nb_samples, consume_time=False): self.data = torch.randn(nb_samples, in_features) self.target = torch.randn(nb_samples, out_features) self.consume_time=consume_time def __getitem__(self, index): x = self.data[index] y = self.target[index] # Transform data x = x + torch.FloatTensor(x.shape).normal_() * 1e-2 if self.consume_time: # Do some time consuming operation for i in xrange(5000000): j = i + 1 return x, y def __len__(self): return len(self.data) # Training loop criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=1e-2) def train(loader): for batch_idx, (data, target) in enumerate(loader): # Wrap data and target into a Variable data, target = Variable(data), Variable(target) # Clear gradients optimizer.zero_grad() # Forward pass output = model(data) # Calculate loss loss = criterion(output, target) # Backward pass loss.backward() # Weight update optimizer.step() print('Batch {}\tLoss {}'.format(batch_idx, loss.data.numpy()[0])) # Create Dataset data = RandomDataset(nb_samples=30) # Create DataLoader loader = DataLoader(dataset=data, batch_size=batch_size, num_workers=0, shuffle=True) # Start training t0 = time.time() train(loader) time_fast = time.time() - t0 print('Training finished in {:.2f} seconds'.format(time_fast)) # Create time consuming Dataset data_slow = RandomDataset(nb_samples=30, consume_time=True) loader_slow = DataLoader(dataset=data_slow, batch_size=batch_size, num_workers=0, shuffle=True) # Start training t0 = time.time() train(loader_slow) time_slow = time.time() - t0 print('Training finished in {:.2f} seconds'.format(time_slow)) loader_slow_multi_proc = DataLoader(dataset=data_slow, batch_size=batch_size, num_workers=4, shuffle=True) # Start training t0 = time.time() train(loader_slow_multi_proc) time_multi_proc = time.time() - t0 print('Training finished in {:.2f} seconds'.format(time_multi_proc))
code/section1/video1_1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Copyright 2021 <NAME>. # # <i>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](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. # # Icons made by <a href="https://www.flaticon.com/authors/freepik" title="Freepik">Freepik</a>, <a href="https://www.flaticon.com/authors/pixel-perfect" title="Pixel perfect">Pixel perfect</a>, <a href="https://www.flaticon.com/authors/becris" title="Becris">Becris</a>, <a href="https://www.flaticon.com/authors/smashicons" title="Smashicons">Smashicons</a>, <a href="https://www.flaticon.com/authors/srip" title="srip">srip</a>, <a href="https://www.flaticon.com/authors/adib-sulthon" title="Adib">Adib</a>, <a href="https://www.flaticon.com/authors/flat-icons" title="Flat Icons">Flat Icons</a> and <a href="https://www.flaticon.com/authors/dinosoftlabs" title="Pixel perfect">DinosoftLabs</a> from <a href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a></i> # # TP 3 : Words Embeddings # <img src="https://github.com/AntoineSimoulin/m2-data-sciences/blob/master/TP3%20-%20Word%20Embeddings/tp3-header.png?raw=True" width="1000"> # On va s'appuyer sur le corpus collecté par <span class="badge badge-secondary">([Panckhurst et al., 2016](#panckhurst-2016))</span> qui rassemble 88,000 sms collectés dans la région de Montpellier. Le corpus a été dé-identifié (en particulier, les noms sont remplacés par [ _forename_ ]). Pour chaque sms, on a identifié les Emojis dans le texte. # # Il y avait beaucoup de type d'Emojis. Dans le TP, ils ont été simplifiés selon le tableau suivant. Tous les Emojis de la colonne `Emoji list` ont été remplacé par l'emoji de la colonne `Generic`. Dans le TP les Emojis n'apparaissent pas dans le texte du sms car on cherche à les prédire. # # # | Generic Emoji | Emoji list | # |:--------------:|:------------------------------------------------------------------:| # | 😃 | '=P', ':)', ':P', '=)', ':p', ':d', ':-)', '=D', ':D', '^^' | # | 😲 | ':O', 'o_o', ':o', ':&' | # | 😔 | '"-.-'''", '<_>', '-_-', "--'", "-.-'", '-.-', "-.-''", "-\_-'" | # | 😠 | ':/', ':-/', ':-(', ':(', ':-<' | # | 😆 | '>.<', '¤.¤', '<>','><', '*.*', 'xd', 'XD', 'xD', 'x)',';)', ';-)' | # | 😍 | '</3', '<3' | # # # Finalement pour le TP, on a filtré le jeu de données pour ne conserver que les sms contenant qu'un seul Emoji. On a par ailleurs <i>down samplé</i> les classes majoritaires pour limiter le déséquilibre du jeu de données. En effet les sms avec un smiley 😃 était largement sur-représentés. # # <b>L'objet du TP est de prédire l'émoji associé à chaque message. Pour cela on vectorisera le texte en utilisant les méthodes d'embeddings.</b> # + # %%capture # Check environment if 'google.colab' in str(get_ipython()): IN_COLAB = True else: IN_COLAB = False if IN_COLAB: # ⚠️ Execute only if running in Colab # !pip install -q scikit-learn==0.23.2 matplotlib==3.1.3 pandas==1.1.3 gensim==3.8.1 torch==1.6.0 torchvision==0.7.0 # !pip install skorch==0.10.0 # then restart runtime environment # + from gensim.models import KeyedVectors from collections import Counter import numpy as np import pandas as pd import re from sklearn.base import BaseEstimator, TransformerMixin from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import LinearSVC from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, roc_auc_score import os, sys # IPython automatically reload all changed code # %load_ext autoreload # %autoreload 2 # Inline Figures with matplotlib # %matplotlib inline # %config InlineBackend.figure_format='retina' # + # import extrenal modules import urllib.request class_names = ['happy', 'joke', 'astonished', 'angry', 'bored', 'heart'] repo_url = 'https://raw.githubusercontent.com/AntoineSimoulin/m2-data-sciences/master/' _ = urllib.request.urlretrieve(repo_url + 'src/plots.py', 'plots.py') if not os.path.exists('smileys'): os.makedirs('smileys') for c in class_names: _ = urllib.request.urlretrieve( repo_url + 'TP3%20-%20Word%20Embeddings/smileys/{}.png'.format(c), 'smileys/{}.png'.format(c)) # - # On va utiliser les embeddings déjà entrainé que nous avons manipulé au cours précédent. Pour limiter la taille du fichier d'embeddings, on a sauvegardé que les `10,000` mots les plus fréquents. <b>Vous devez récupérer le fichier d'embeddings aisni que le jeu de données directement sur le [Moodle](https://moodle.u-paris.fr/course/view.php?id=11048).</b> w2v_model = KeyedVectors.load_word2vec_format("oscar.fr.300.10k.model") w2v_model.init_sims(replace=True) len(w2v_model.vocab) # + # On crée un array avec les 10,000 premiers mots et on crée le dictionaire de vocabulaire word_count = {k: w2v_model.vocab[k].count for k in w2v_model.vocab} word_count = Counter(word_count) word_count.most_common(10) idx2w = {i: w for (i, (w, f)) in enumerate(word_count.most_common(10000), 2)} idx2w[0] = 'unk' idx2w[1] = 'pad' w2idx = {w: i for (i, (w, f)) in enumerate(word_count.most_common(10000), 2)} w2idx['unk'] = 0 w2idx['pad'] = 1 embeddings_vectors = [w2v_model[w] for (w, f) in word_count.most_common(10000)] word2vec_embeddings = np.vstack(embeddings_vectors) word2vec_embeddings = np.concatenate((word2vec_embeddings, np.zeros_like(word2vec_embeddings[0:2])), 0) # - word2vec_embeddings.shape w2idx['Oh'] word2vec_embeddings[3664][:10] w2v_model['Oh'][:10] dataset = pd.read_csv('emojis.csv') dataset.head() dataset.loc[3, 'sms'] class_names = ['happy', 'joke', 'astonished', 'angry', 'bored', 'heart'] dataset.shape # On va utiliser la même fonction de tokenization qui a été utilisée pour entrainer les embeddings. # + token_pattern = re.compile(r"(\->|(?::\)|:-\)|:\(|:-\(|;\);-\)|:-O|8-|:P|:D|:\||:S|:\$|:@|8o\||\+o\(|\(H\)|\(C\)|\(\?\))|(?:[\d.,]+)|([^\s\w0-9])\2*|(?:[\w0-9\.]+['’]?)(?<!\.))") def tokenize(text): tokens = [groups[0] for groups in re.findall(token_pattern, str(text))] tokens = [t.strip() for t in tokens] return tokens # - dataset['tokens'] = dataset['sms'].apply(tokenize) dataset.head() # ### Exploration de données # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice :</b> Observer la distribution des classes.</p> # </div> # <hr> # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice :</b> Evaluer la proportion de tokens qui sont hors du vocabulaire des embeddings.</p> # </div> # <hr> # ### Vectorization # Les embeddings de mots permettent de représenter chaque <i>token</i> par un vecteur. Pour obtenir un vecteur qui représente le sms, on va agréger les différents mots du texte. On considérera plusieurs fonctions d'agrégation : la somme, la moyenne, me maximum ou le minimum. # # En pratique nous verrons dans le dernier cours d'ouverture qu'il existe des méthodes plus évoluées pour composer les mots de la phrase. Néanmoins une simple fonction d'agrégation nous donnera déjà une bonne <i>baseline</i>. # <img src="https://github.com/AntoineSimoulin/m2-data-sciences/blob/master/TP3%20-%20Word%20Embeddings/model.png?raw=True" width="500"> # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice :</b> Ecrire une fonction qui permet de vectoriser un sms.</p> # </div> # <hr> # + # # %load solutions/vectorize_1.py def vectorize(tokens, agg_method='mean'): #TODO à compléter # associer chaque token à son embedding. # Attention, certains tokens peuvent ne pas être dans le vocabulaire # Agréger les représentations de chaque token. # Le vecteur de sortie doit être de taille (300, ) if agg_method == 'mean': sentence_embedding = elif agg_method == 'max': sentence_embedding = elif agg_method == 'sum': sentence_embedding = return # - vectorize(dataset['tokens'][0], agg_method='max') # On voudrait attribuer un poids moins important aux embeddings des mots moins caractéristiques. Pour ça, on voudrait pondérer la contribution des vecteurs de chaque mot en fonction de leur score TF-IDF. # <img src="https://github.com/AntoineSimoulin/m2-data-sciences/blob/master/TP3%20-%20Word%20Embeddings/model-tfidf.png?raw=True" width="700"> # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice :</b> Utiliser la pondération TF-IDF pour pondérer chacun des vecteurs.</p> # </div> # <hr> # + tfidf_vectorizer = TfidfVectorizer(tokenizer=lambda x: x, lowercase=False) tfidf_vectorizer.fit(dataset['tokens']) w2idx_tfidf = {w: idx for (idx, w) in enumerate(tfidf_vectorizer.get_feature_names())} idx_tfidf2w = {idx: w for (idx, w) in enumerate(tfidf_vectorizer.get_feature_names())} # + # # %load solutions/vectorize_2.py def vectorize(tokens, agg_method='mean', tfidf_vectorizer=None): #TODO à compléter if agg_method == 'mean': sentence_embedding = elif agg_method == 'max': sentence_embedding = elif agg_method == 'sum': sentence_embedding = elif agg_method == 'tfidf': return # - X = [vectorize(sms) for sms in dataset['tokens']] X = np.array(X) print(X.shape) # On va intégrer la fonction `vectorize` dans un module compatible avec les fonctions de `sklearn`. # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice :</b> Intégrer votre fonction de vectorization dans la classe Vectorizer ci-dessous. Vous devez simoplement la copier/coller en replaçant tfidf_vectorizer par self.tfidf_vectorizer car c'est maintenant un attribut de la class</p> # </div> # <hr> # + # 6 choses à faire pour l'excercice sur la class Vectorizer : # copier votre fonction vectorize dans la class # ajouter l'argument self dans la fonction vectorize # supprimer l'argument tfidf_vectorizer de la fonction vectorize # remplacer toutes les occurences de agg_method par self.agg_method dans la fonction vectorize # supprimer l'argument agg_method de la fonction vectorize # remplacer toutes les occurences de w2idx_tfidf par self.w2idx_tfidf dans la fonction vectorize # + # # %load solutions/vectorizer.py class Vectorizer(BaseEstimator, TransformerMixin): def __init__(self, agg_method='mean', normalize=False): self.agg_method = agg_method self.normalize = normalize self.tfidf_vectorizer = TfidfVectorizer(tokenizer=lambda x: x, lowercase=False, token_pattern=None) def vectorize(self, tokens): token_embeddings = [] vect_vide = np.zeros_like(embeddings_vectors[0]) # associer chaque token à son embedding. # Attention, certains tokens peuvent ne pas être dans le vocabulaire # self.tfidf_vectorizer for t in tokens: if t in w2idx: t_idx = w2idx[t] token_embeddings.append(embeddings_vectors[t_idx]) else: token_embeddings.append(vect_vide) token_embeddings_arr = np.array(token_embeddings) # Agréger les représentations de chaque token. # Le vecteur de sortie doit être de taille (300, ) if self.agg_method == 'mean': sentence_embedding = np.mean(token_embeddings_arr, axis=0) elif self.agg_method == 'max': sentence_embedding = np.max(token_embeddings_arr, axis=0) elif self.agg_method == 'sum': sentence_embedding = np.sum(token_embeddings_arr, axis=0) elif self.agg_method == 'tfidf': pass return sentence_embedding def _vectorize(self, tokens): return vectorize(tokens) def fit(self, X, y=None): self.tfidf_vectorizer.fit(X['tokens']) self.w2idx_tfidf = {w: idx for (idx, w) in enumerate(self.tfidf_vectorizer.get_feature_names())} self.idx_tfidf2w = {idx: w for (idx, w) in enumerate(self.tfidf_vectorizer.get_feature_names())} return self def transform(self, X, y=None, eps=1e-12): X = [self.vectorize(sms) for sms in X['tokens']] X = np.array(X) if self.normalize: X = X / np.linalg.norm(X + eps, axis=1, keepdims=True) return X # - vectorizer = Vectorizer(agg_method='tfidf') X = vectorizer.fit_transform(dataset) X.shape # ### Classification # On compare deux algorithmes de classification : Une régression logistique et un SVM ou l'on pénalise les classes majoritaires. # + X_train, X_test = train_test_split( dataset, test_size=0.33, random_state=42) y_train = X_train[['happy', 'joke', 'astonished', 'angry', 'bored', 'heart']].astype(int).values y_train = [x.tolist().index(1) for x in y_train] y_test = X_test[['happy', 'joke', 'astonished', 'angry', 'bored', 'heart']].astype(int).values y_test = [x.tolist().index(1) for x in y_test] # - len(y_train) X_train.shape # + LogReg_pipeline = Pipeline([ ('vect', Vectorizer('tfidf')), ('clf', OneVsRestClassifier(LogisticRegression(solver='sag'))), ]) # Training logistic regression model on train data LogReg_pipeline.fit(X_train, y_train) # Infering data on test set prediction_LogReg = LogReg_pipeline.predict(X_test) # + SVC_pipeline = Pipeline([ ('vect', Vectorizer('tfidf')), ('clf', OneVsRestClassifier(SVC(kernel='linear', class_weight='balanced', # penalize probability=True), n_jobs=-1)) ]) SVC_pipeline.fit(X_train, y_train) prediction_SVC = SVC_pipeline.predict(X_test) # - # ### Evaluation import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from plots import plot_confusion_matrix # + print('Test accuracy is {}'.format(accuracy_score(y_test, prediction_SVC))) print('Test ROC socre is {}'.format(roc_auc_score(np.eye(np.max(y_test) + 1)[y_test], SVC_pipeline.predict_proba(X_test), multi_class='ovo'))) plot_confusion_matrix(confusion_matrix(y_test, prediction_SVC), classes=class_names, title='Confusion matrix, without normalization') # + print('Test accuracy is {}'.format(accuracy_score(y_test, prediction_LogReg))) print('Test ROC socre is {}'.format(roc_auc_score(np.eye(np.max(y_test) + 1)[y_test], LogReg_pipeline.predict_proba(X_test), multi_class='ovo'))) plot_confusion_matrix(confusion_matrix(y_test, prediction_LogReg), classes=class_names, title='Confusion matrix, without normalization') # - # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice :</b> Quelle mesure de performance vous semble le plus adaptée pour ce cas d'usage ?</p> # </div> # <hr> # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice :</b> Comparer les résultats obtenus avec les deux algorithmes de classifications</p> # </div> # <hr> # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice :</b> Comparer les différentes méthodes d'agrégation proposées. (Mean, Max, Sum, Moyenne pondérée par le TF-IDF)</p> # </div> # <hr> # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice (Bonus) :</b> Comparer les résultats obtenus avec un réseau de neurones récurent (RNN).</p> # </div> # <hr> # # Nous ferons une ouverture sur les réseaux de neurones et leur utilisation pour le texte lors de la dernière séance. Néanmoins, cela peut être une bonne occasion de se familiariser avec leur utilisation. Nous allons utiliser la librairie [skorch](https://github.com/skorch-dev/skorch) qui est un wrapper de la librairie [PyTorch](https://pytorch.org/) compatible avec [scikit-learn](https://scikit-learn.org/). Cela permet en particulier de simplifier les aspects d'optimisation. Ici on utilise un réseau récurent de type LSTM <span class="badge badge-secondary">([Cho and al., 2014](#cho-2014)</span>, <span class="badge badge-secondary">[<NAME> Schmidhuber, 1997](#schmidhuber-1997))</span>. Les réseaux de neurones récurrents modélisent les phrases comme des séquences d’embeddings de mots. Ils traitent l’entrée séquentiellement. A chaque étape, le vecteur de sortie est calculé en fonction de l’embedding du mot courant et de l’état caché précédent. # # <img src="https://github.com/AntoineSimoulin/m2-data-sciences/blob/master/TP3%20-%20Word%20Embeddings/lstm.png?raw=True" width="700"> # + import torch from torch import nn from skorch import NeuralNet, NeuralNetClassifier from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence import torch.nn.functional as F from sklearn.utils.class_weight import compute_class_weight class RNNClassifier(nn.Module): def __init__(self, n_classes, embeddings_weights, hidden_dim=100, embedding_dim=300, dropout=0.5): super(RNNClassifier, self).__init__() self.embeddings = nn.Embedding.from_pretrained(embeddings_weights, sparse=True) self.embeddings.weight.requires_grad = False self.lstm = nn.LSTM(embedding_dim, hidden_dim) self.dense = nn.Linear(hidden_dim, n_classes) self.dropout = dropout self.drop = nn.Dropout(self.dropout) def forward(self, X, **kwargs): X, X_len = X X = self.embeddings(X) # On utilise une méthode de pytorch pour tenir compte de la longueur des phrases # et ainsi s'adapter au padding. X_packed = pack_padded_sequence(X, X_len, batch_first=True, enforce_sorted=False) X_packed, (h, c) = self.lstm(X_packed)# [1][0] # .transpose(0, 1) # https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html#torch.nn.LSTM X, output_lengths = pad_packed_sequence(X_packed, batch_first=True) # X = torch.sigmoid(X) out = F.softmax(self.dense(h.squeeze()), dim=-1) return out class_weights = compute_class_weight( 'balanced', classes=range(len(class_names)), y=y_train) # On va donner un poids plus important aux classes minoritaires # mais pas proportionnel à leur distribution pour ne pas trop les favoriser # au détriment de la précision globale class_weights = [1, 1, 1.3, 1, 1.3, 1] class_weights = torch.tensor(class_weights, dtype=torch.float) net = NeuralNetClassifier( # NeuralNet RNNClassifier(len(class_names), torch.tensor(word2vec_embeddings)), max_epochs=10, lr=0.001, optimizer=torch.optim.Adam, criterion=torch.nn.NLLLoss, criterion__weight=class_weights ) sequences = [torch.tensor([w2idx.get(t, 0) for t in tokens]) for tokens in X_train['tokens']] sequences_length = torch.tensor([len(s) for s in sequences]) # On "pad" les séquences pour qu'elles aient toutes la même longueur. padded_sequences = pad_sequence(sequences, batch_first=True, padding_value=1) net.fit((padded_sequences, sequences_length), torch.tensor(y_train)) # - sequences_test = [torch.tensor([w2idx.get(t, 0) for t in tokens]) for tokens in X_test['tokens']] sequences_test_length = torch.tensor([len(s) for s in sequences_test]) # On "pad" les séquences pour qu'elles aient toutes la même longueur. padded_sequences_test = pad_sequence(sequences_test, batch_first=True, padding_value=1) prediction_LSTM = net.predict((padded_sequences_test, sequences_test_length)) # + print('Test accuracy is {}'.format(accuracy_score(y_test, prediction_LSTM))) print('Test ROC socre is {}'.format(roc_auc_score(np.eye(np.max(y_test) + 1)[y_test], net.predict_proba((padded_sequences_test, sequences_test_length)), multi_class='ovo'))) plot_confusion_matrix(confusion_matrix(y_test, prediction_LSTM), classes=class_names, title='Confusion matrix, without normalization') # - # L'utilisation des méthodes de down-sampling ou up-sampling peut s'avérer fastidieux (on va se priver de données ou en utiliser d'autres plusieurs fois. La sélection des données doit se faire précisémment pour ne pas impacter les capacités de généralisation de l'algorithme). Nous avons préféré ici utiliser un algorithme qui pénalise les classes majoritaires et une mesure d'erreur adaptée. Il existe un bon article de blog pour gérer les classes déséquilibrées : https://elitedatascience.com/imbalanced-classes. # On peut se faire une idée des limites et des points fort de l'algorithme en regardant des prédictions. humors = ['happy', 'astonished', 'bored', 'angry', 'joke', 'heart'] meta_smiley = [b'\xF0\x9F\x98\x83'.decode("utf-8"), b'\xF0\x9F\x98\xB2'.decode("utf-8"), b'\xF0\x9F\x98\x94'.decode("utf-8"), b'\xF0\x9F\x98\xA0'.decode("utf-8"), b'\xF0\x9F\x98\x86'.decode("utf-8"), b'\xF0\x9F\x98\x8D'.decode("utf-8")] humor_2_emoji = {h: ms for (h, ms) in zip(humors, meta_smiley)} X_test.shape for _ in range(10): idx = np.random.randint(0, len(X_test)) emojis = humor_2_emoji[class_names[prediction_SVC[idx]]] true_emojis = humor_2_emoji[class_names[y_test[idx]]] print(X_test['sms'].values[idx], '(Pred)', emojis, '(True)', true_emojis, '\n') # ### Visualisation # On peut aussi essayer de visualiser plus globalement les représentations. Pour ça on peut utiliser des algorithmes de réduction de dimension pour visualiser nos données. On a déjà parlé de UMAP et t-SNE. De manière intutive, l'algorithme projete les représentations dans un espace de plus faible dimension en s'efforcant de respecter les distances entre les points entre l'espace de départ et d'arrivée. Il permet de visualiser facilement les données. On va utiliser l'outil `Tensorboard` qui intègre les principales méthodes de réduction de dimensions. # + from pathlib import Path from PIL import Image import os from os import listdir from os.path import isfile, join from torchvision import transforms from torch.utils.tensorboard import SummaryWriter import torch import tensorflow as tf import tensorboard as tb tf.io.gfile = tb.compat.tensorflow_stub.io.gfile # - pil_img = Image.open('./smileys/happy.png').convert('RGB') pil_img = pil_img.resize((100, 100)) smileys_images = [f for f in listdir('./smileys') if isfile(join('./smileys', f))] imgs_tb = {} for s in smileys_images: pil_img = Image.open(os.path.join('smileys', s)).convert('RGB') pil_img = pil_img.resize((25, 25)) pil_to_tensor = transforms.ToTensor()(pil_img).unsqueeze_(0) imgs_tb[Path(os.path.join('smileys', s)).stem] = pil_to_tensor # + writer_embeddings = SummaryWriter(log_dir=os.path.join("./tfb/")) vectorizer = Vectorizer(agg_method='tfidf', normalize=True) emb_test = vectorizer.fit_transform(X_test) writer_embeddings.add_embedding(torch.tensor(emb_test), metadata=[(r, s, l) for (r, s, l) in zip( X_test['sms'].values, [humor_2_emoji[class_names[y]] for y in y_test], [humor_2_emoji[class_names[y]] for y in prediction_SVC]) ], label_img=torch.cat([imgs_tb[class_names[y]] for y in y_test]), metadata_header=['sms','label', 'prediction'], tag="SMS-EMB-CLS") # - # Pour visualiser les représentations, lancer un tensorboard. Dans un terminal, se placer dans le dossier ou est éxécuté le notebook et exécuter: # # ``` # tensorboard --logdir ./tfb/ # ``` # # Dans **Colab** on va lancer le tensorboard directement dans le notebook en éxécutant les cellules suivante : # # ``` # # %load_ext tensorboard # ``` # # ``` # # %tensorboard --logdir ./tfb/ # ``` # Load the TensorBoard notebook extension # %load_ext tensorboard from tensorboard import notebook notebook.list() # View open TensorBoard instances # Control TensorBoard display. If no port is provided, # the most recently launched TensorBoard is used notebook.display(port=6006, height=1000); # <hr> # <div class="alert alert-info" role="alert"> # <p><b>📝 Exercice :</b> Utiliser les méthodes UMAP, PCA et t-SNE pour projeter les données. Comparez les différentes méthodes de projections et interprétez qualitativement les propriétés de vos représentations.</p> # </div> # <hr> # La compatibilité entre Jupyter/Colab et Tensorboard est un parfois instable (c.f. https://www.tensorflow.org/tensorboard/tensorboard_in_notebooks). Si vous êtes sur Colab, vous pouvez télécharger le dossier directement sur votre ordinateur. Téléchargez le .zip, sur votre ordinateur, dezipé le. # # ``` # # !zip -r tfb.zip ./tfb/ # ``` # # Sur votre ordinateur, dans un terminal, se placer dans le dossier ou est le notebook et exécuter: # # ``` # tensorboard --logdir ./tfb/ # ``` # # Vous devriez avoir un visuel comme ci-dessous. Vous pouvez cliquer sur un sms et vous avez à droite les sms les plus proches en terme de distance cosine comme nous l'avons fait pour word2vec. Par ailleurs chaque sms est représenté par le smiley correspondant. Vous pouvez faire varier les méthodes de projection dans le panneau de gauche. # # <img src="https://github.com/AntoineSimoulin/m2-data-sciences/blob/master/TP3%20-%20Word%20Embeddings/tfb-viz.png?raw=True" width="1000"> # ## 📚 References # # > <div id="panckhurst-2016">Panckhurst, Rachel, et al. <a href=https://hal.archives-ouvertes.fr/hal-01485560> 88milSMS. A corpus of authentic text messages in French.</a> Banque de corpus CoMeRe. Chanier T.(éd)-Ortolang: Nancy (2016).</div> # # > <div id="schmidhuber-1997"><NAME>, <NAME>. <a href=https://dl.acm.org/doi/10.1162/neco.1997.9.8.1735> Long Short-Term Memory.</a> Neural Comput. 9(8): 1735-1780 (1997).</div> # # > <div id="cho-2014"><NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>: <a href=https://doi.org/10.3115/v1/d14-1179> Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation.</a> EMNLP 2014: 1724-1734.</div> # # #
TP3 - Word Embeddings/EmojiFy.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 re from sklearn.naive_bayes import GaussianNB from sklearn.metrics import confusion_matrix from sklearn.svm import SVC from sklearn.linear_model import LogisticRegressionCV import os veryNegative = [] Negative = [] Positive = [] veryPositive = [] data_X = "" data_Y = "" def generateStopWordList(): #Fetch stopwords.txt file path stopWords_dataset = dirPath+"/Data/stopwords.txt" #stopwords List stopWords = [] #Open the stopwords txt file read the data and store in a list try: fp = open(stopWords_dataset, 'r') line = fp.readline() while line: word = line.strip() stopWords.append(word) line = fp.readline() fp.close() except: print("ERROR: Opening File") return stopWords def generate_AffinityList(datasetLink): affin_dataset = datasetLink try: affin_list = open(affin_dataset).readlines() except: print("", affin_dataset) exit(0) return affin_list def createDictionaryFromPolarity(affin_list): # Create list to store the words and its polarity score words = [] score = [] # Iterate and assign words and thier polarities for word in affin_list: words.append(word.split("\t")[0].lower()) score.append(int(word.split("\t")[1].split("\n")[0])) #Categorize words into different categories based on polarities for elem in range(len(words)): if score[elem] == -4 or score[elem] == -5: veryNegative.append(words[elem]) elif score[elem] == -3 or score[elem] == -2 or score[elem] == -1: Negative.append(words[elem]) elif score[elem] == 3 or score[elem] == 2 or score[elem] == 1: Positive.append(words[elem]) elif score[elem] == 4 or score[elem] == 5: veryPositive.append(words[elem]) def preprocessing(dataSet): processed_data = [] #Make a list of all the Stopwords to be removed stopWords = generateStopWordList() #For every TWEET in the dataset do, for tweet in dataSet: temp_tweet = tweet #Convert @username to USER_MENTION tweet = re.sub('@[^\s]+','USER_MENTION',tweet).lower() tweet.replace(temp_tweet, tweet) #Remove the unnecessary white spaces tweet = re.sub('[\s]+',' ', tweet) tweet.replace(temp_tweet,tweet) #Replace HASH (#) symbol in hastag tweet = re.sub(r'#([^\s]+)', r'\1', tweet) #Replace all the numeric terms tweet = re.sub('[0-9]+', "",tweet) tweet.replace(temp_tweet,tweet) #Remove all the STOP WORDS for sw in stopWords: if sw in tweet: tweet = re.sub(r'\b' + sw + r'\b'+" ","",tweet) tweet.replace(temp_tweet, tweet) #Replace all Punctuations tweet = re.sub('[^a-zA-z ]',"",tweet) tweet.replace(temp_tweet,tweet) #Remove additional white spaces tweet = re.sub('[\s]+',' ', tweet) tweet.replace(temp_tweet,tweet) #Save the Processed Tweet after data cleansing processed_data.append(tweet) return processed_data def FeaturizeTrainingData(dataset, type_class): neutral_list = [] i=0 # For each Tweet split the Tweet by " " (space) i.e. split every word of the Tweet data = [tweet.strip().split(" ") for tweet in dataset] #print(data) # Feature Vector is to store the feature of the TWEETs feature_vector = [] # for every sentence i.e. TWEET find the words and their category for sentence in data: # Category count for every Sentence or TWEET veryNegative_count = 0 Negative_count = 0 Positive_count = 0 veryPositive_count = 0 # for every word in sentence, categorize # and increment the count by 1 if found for word in sentence: if word in veryPositive: veryPositive_count = veryPositive_count + 1 elif word in Positive: Positive_count = Positive_count + 1 elif word in veryNegative: veryNegative_count = veryNegative_count + 1 elif word in Negative: Negative_count = Negative_count + 1 i+=1 #Assign Class Label if veryPositive_count == veryNegative_count == Positive_count == Negative_count: feature_vector.append([veryPositive_count, Positive_count, Negative_count, veryNegative_count, "neutral"]) neutral_list.append(i) else: feature_vector.append([veryPositive_count, Positive_count, Negative_count, veryNegative_count, type_class]) #print(neutral_list) return feature_vector def FeatureizeTestData(dataset): data = [tweet.strip().split(" ") for tweet in dataset] #print(data) count_Matrix = [] feature_vector = [] for sentence in data: veryNegative_count = 0 Negative_count = 0 Positive_count = 0 veryPositive_count = 0 # for every word in sentence, categorize # and increment the count by 1 if found for word in sentence: if word in veryPositive: veryPositive_count = veryPositive_count + 1 elif word in Positive: Positive_count = Positive_count + 1 elif word in veryNegative: veryNegative_count = veryNegative_count + 1 elif word in Negative: Negative_count = Negative_count + 1 if (veryPositive_count + Positive_count) > (veryNegative_count + Negative_count): feature_vector.append([veryPositive_count, Positive_count, Negative_count, veryNegative_count, "positive"]) #neutral_list.append(i) elif (veryPositive_count + Positive_count) < (veryNegative_count + Negative_count): feature_vector.append([veryPositive_count, Positive_count, Negative_count, veryNegative_count, "negative"]) else: feature_vector.append([veryPositive_count, Positive_count, Negative_count, veryNegative_count, "neutral"]) return feature_vector # + def classify_naive_bayes(train_X, train_Y, test_X): print("Classifying using Gaussian Naive Bayes ...") gnb = GaussianNB() yPred = gnb.fit(train_X,train_Y).predict(test_X) return yPred def classify_svm(train_X, train_Y, test_X): print("Classifying using Support Vector Machine ...") clf = SVC() clf.fit(train_X,train_Y) yPred = clf.predict(test_X) return yPred def classify_maxEnt(train_X, train_Y, test_X): print("Classifying using Maximum Entropy ...") maxEnt = LogisticRegressionCV() maxEnt.fit(train_X, train_Y) yPred = maxEnt.predict(test_X) return yPred #########FOR TEST DATA CLASSIFICATION######## # - # # For Twitter test data classification # + def classify_naive_bayes_twitter(train_X, train_Y, test_X, test_Y): print("Classifying using Gaussian Naive Bayes Algorithm...") gnb = GaussianNB() yPred = gnb.fit(train_X,train_Y).predict(test_X) import pandas as pd pd.DataFrame(yPred).to_csv("/Users/vineethkumarrenukuntla/Desktop/vinks/Data/PredictionsforMortalKombat/gnbpredfile.csv") conf_mat = confusion_matrix(test_Y,yPred) print(conf_mat) Accuracy = (sum(conf_mat.diagonal())) / np.sum(conf_mat) print("Accuray: ", Accuracy) evaluate_classifier(conf_mat) def classify_svm_twitter(train_X, train_Y, test_X, test_Y): print("Classifying using Support Vector Machine Algorithm...") clf = SVC() clf.fit(train_X,train_Y) yPred = clf.predict(test_X) import pandas as pd pd.DataFrame(yPred).to_csv("/Users/vineethkumarrenukuntla/Desktop/vinks/Data/PredictionsforMortalKombat/svmpredfile.csv") conf_mat = confusion_matrix(test_Y,yPred) print(conf_mat) Accuracy = (sum(conf_mat.diagonal())) / np.sum(conf_mat) print("Accuracy: ", Accuracy) evaluate_classifier(conf_mat) def classify_maxEnt_twitter(train_X, train_Y, test_X, test_Y): print("Classifying using Maximum Entropy Algorithm...") maxEnt = LogisticRegressionCV() maxEnt.fit(train_X, train_Y) yPred = maxEnt.predict(test_X) import pandas as pd #Downloading the prediction to CSV file pd.DataFrame(yPred).to_csv("/Users/vineethkumarrenukuntla/Desktop/vinks/Data/PredictionsforMortalKombat/maxEntpredfile.csv") conf_mat = confusion_matrix(test_Y,yPred) print(conf_mat) Accuracy = (sum(conf_mat.diagonal())) / np.sum(conf_mat) print("Accuracy: ", Accuracy) evaluate_classifier(conf_mat) # - def classify_twitter_data(file_name): test_data = open(dirPath+"/vinks/Data/"+file_name, encoding="utf8").readlines() test_data = preprocessing(test_data) test_data = FeatureizeTestData(test_data) test_data = np.reshape(np.asarray(test_data),newshape=(len(test_data),5)) print(len(test_data)) #Split Data into Features and Classes data_X_test = test_data[:,:4].astype(int) data_Y_test = test_data[:,4] print("Classifying",) classify_naive_bayes_twitter(data_X, data_Y, data_X_test, data_Y_test) classify_svm_twitter(data_X, data_Y, data_X_test, data_Y_test) classify_maxEnt_twitter(data_X, data_Y, data_X_test, data_Y_test) def evaluate_classifier(conf_mat): Precision = conf_mat[0,0]/(sum(conf_mat[0])) Recall = conf_mat[0,0] / (sum(conf_mat[:,0])) F_Measure = (2 * (Precision * Recall))/ (Precision + Recall) print("Precision: ",Precision) print("Recall: ", Recall) print("F-Measure: ", F_Measure) os.chdir('../') #!!!!!IMPORTANT UNCOMMENT dirPath = os.getcwd() print("Please wait while we Classify your data ...") affin_list = generate_AffinityList(dirPath+"/vinks/Data/Affin_Data.txt") createDictionaryFromPolarity(affin_list) print("Preprocessing in progress !") negative_data = open(dirPath+"/vinks/Data/Rt-polarity-neg.txt").readlines() positive_data = open(dirPath+"/vinks/Data/Rt-polarity-pos.txt").readlines() positive_data = preprocessing(positive_data) negative_data = preprocessing(negative_data) print("Generating the Feature Vectors ...") positive_sentiment = FeaturizeTrainingData(positive_data, "positive") negative_sentiment = FeaturizeTrainingData(negative_data,"negative") final_data = positive_sentiment + negative_sentiment final_data = np.reshape(np.asarray(final_data),newshape=(len(final_data),5)) data_X = final_data[:,:4].astype(int) data_Y = final_data[:,4] # + print("Training the Classifer according to the data provided ...") print("Classifying the Test Data ...") print("Evaluation Results will be displayed Shortly ...") yPred = classify_naive_bayes(data_X, data_Y, data_X) conf_mat = confusion_matrix(data_Y, yPred) print(conf_mat) Accuracy = (sum(conf_mat.diagonal())) / np.sum(conf_mat) print("Accuracy: ", Accuracy) evaluate_classifier(conf_mat) yPred = classify_svm(data_X, data_Y, data_X) conf_mat = confusion_matrix(data_Y, yPred) print(conf_mat) Accuracy = (sum(conf_mat.diagonal())) / np.sum(conf_mat) print("Accuracy: ", Accuracy) evaluate_classifier(conf_mat) yPred = classify_maxEnt(data_X, data_Y, data_X) conf_mat = confusion_matrix(data_Y, yPred) print(conf_mat) Accuracy = (sum(conf_mat.diagonal())) / np.sum(conf_mat) print("Accuracy: ", Accuracy) evaluate_classifier(conf_mat) # - # # Using trained models to depict the sentiment in Movie Tweets (#MortalKombatmovie) classify_twitter_data(file_name="MortalKombattweets40K.txt")
WebText_Movie_Sentiment copy.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_ext autoreload # %autoreload 2 import Grbl import serial # + from IPython.core.magic import (register_line_magic, register_cell_magic, register_line_cell_magic) @register_line_magic def lmagic(line): "my line magic" return line @register_cell_magic def cmagic(line, cell): "my cell magic" return line, cell @register_line_cell_magic def lcmagic(line, cell=None): "Magic that works both as %lcmagic and as %%lcmagic" if cell is None: print("Called as line magic") return line else: print("Called as cell magic") return line, cell # - # %lmagic lmagic line # %%cmagic cmagic_line1 cmagic_line2 # %lcmagic Hello World! # %%lcmagic Hello World! # + from IPython.core.magic import (register_line_magic, register_cell_magic, register_line_cell_magic) @register_cell_magic def grbl(cfg, cell): "# Sending G-Code" grbl=Grbl.Grbl(port=cfg) grbl.run(cell) @register_line_cell_magic def lcmagic(line, cell=None): "Magic that works both as %lcmagic and as %%lcmagic" if cell is None: print("Called as line magic") return line else: print("Called as cell magic") return line, cell # - grbl1=Grbl.Grbl(port="/dev/ttyUSB0") grbl1.status grbl1.laser_mode grbl1.run("G91G21") grbl1.serial.close() # %%grbl /dev/ttyUSB0 G91 G21 grbl=Grbl.Grbl(port="/dev/ttyUSB0") grbl.status grbl.run(""" G0 M3S1 G1F1 """) grbl.run(""" M5 """) def aim_laser(self, laser_power:int = 1): """Run laser at specified power to aim laser. *** Warning. Will turn on laser. *** *** Warning. Do not look at laser with remaining eye. *** laser_power [int:1]: laser power to use. [0, 255] """ input("Press Enter to start aiming laser.") self.run(""" G0 M3S1 G1F1 """) input("Press Enter to stop aiming laser.") self.run(""" M5 """)
Development/development_JupyterMagics.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/perfectpanda-works/machine-learning/blob/master/VISUALIZING_MODELS%2C_DATA%2C_AND_TRAINING_WITH_TENSORBOARD.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="ecR6oNhVG_tK" colab_type="text" # #Anaconda環境、JupyterNotebook実行用 # + id="Bv_Qg7KpGVK7" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 437, "referenced_widgets": ["42d4b0cedc49442eb84f31cc0660ec24", "9e10821b1d6b4900a2e3ef6e7d7c6c7d", "073d77925cf146ca8da349d704ebdf39", "3ca0f924200f4bbda81480f35eb105b4", "564aed902d244922a87f8306990fa8e9", "e74212246c864de295e3554081ebee49", "4379ca91a51e4382a9c92204034d6f5d", "0514f5ccb96b4357afc1e354e5c6437c", "dc5b13f2a6d449389ba123e8c7c69eba", "<KEY>", "c02a0df3e0614841bb02e4468e8129bd", "<KEY>", "<KEY>", "fd2785aa122d44a285ca0fae6f4f4f37", "64d1f5d86ce94ff2b5719fe9a39d1755", "4ed5e89b0ef749a09702e6477d1be01b", "<KEY>", "f734379a84404ce99b800bc41a9479a7", "5b9cee6874aa4049b739e27068ef548b", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "89d5ffa8bc424ca58d26b43d2a5955f4", "<KEY>", "1a63edf5f98d4c658ab012e3b771146d", "94da00776fca44e38b27afd956bea00a", "1b50374ad31943adae531e458f2a9a55", "<KEY>", "9f707e3d2c1248f0821259eec4ef230c", "8b73dde4f4ac4ad2a4c792db76315947", "441c47ab62874cef8ccfda84bde33483"]} outputId="21c446a4-e983-4f53-8bd1-7acf382ec0c1" # imports import matplotlib.pyplot as plt import numpy as np import torch import torchvision import torchvision.transforms as transforms #functionalはas F とするのが一般的 import torch.nn as nn import torch.nn.functional as F import torch.optim as optim #データを-1~1の範囲にノーマライズ(MNISTのため1チャンネル画像) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) #FashionMNISTデータセット trainset = torchvision.datasets.FashionMNIST('./data', download=True, train=True, transform=transform) testset = torchvision.datasets.FashionMNIST('./data', download=True, train=False, transform=transform) #データローダー、バッチサイズは4とする。 trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2) #答え(ラベル)の定義 classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot') # + id="iCyka6hNGxsL" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="33700195-5fe3-424a-f97f-80f7eda2e2bc" # FashionMNISTの画像確認用関数 def matplotlib_imshow(img, one_channel=False): if one_channel: img = img.mean(dim=0) img = img / 2 + 0.5 # unnormalize npimg = img.numpy() if one_channel: plt.imshow(npimg, cmap="Greys") else: plt.imshow(np.transpose(npimg, (1, 2, 0))) class Net(nn.Module): def __init__(self): super(Net, self).__init__() #一番最初の畳み込み層の入力チャンネルが1になっている。 self.conv1 = nn.Conv2d(1, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) #全結合層の入力時には、画像が16チャンネルの4×4画像となっているので「4×4」に変更しています。 #(画像サイズはforwardメソッドに記載) self.fc1 = nn.Linear(16 * 4 * 4, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): #Conv①:6チャンネルの24×24画像→MaxPool:12×12画像 x = self.pool(F.relu(self.conv1(x))) #Conv②:16チャンネルの8×8画像に→MaxPool:4×4画像 x = self.pool(F.relu(self.conv2(x))) #全結合層に入力するためには、1画像のデータを全て横並びにする。 #行が画像枚数、列が4×4の16チャンネルの画像ピクセルデータが横並びになったデータ x = x.view(-1, 16 * 4 * 4) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() # + id="JKTvGpoTP580" colab_type="code" colab={} criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # + [markdown] id="uiHOo0LSIXZf" colab_type="text" # #1.TensorBoardのセットアップ # + id="ySfvWRC2I4ul" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="02aa8b79-10cc-444f-efe7-82b3c0f38633" from torch.utils.tensorboard import SummaryWriter # default `log_dir` is "runs" - we'll be more specific here writer = SummaryWriter('runs/fashion_mnist_experiment_1') # + [markdown] id="JCiXaUF4MYBn" colab_type="text" # #2.TensorBoardへの書き込み # + id="odXw9IlZJLrA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 138} outputId="f10366f8-4532-4f64-c2e2-a6b18ebc1e2d" #trainloaderのイテレータを取得 dataiter = iter(trainloader) #イテレータでミニバッチ(画像4枚)を取得 images, labels = dataiter.next() #make_grid関数で画像を書き込み、並べて表示できる img_grid = torchvision.utils.make_grid(images) #matplotlibで先ほどmake_gridで並べた画像を表示する。 matplotlib_imshow(img_grid, one_channel=True) #tensorboardに並べた4枚の画像を書き込む。 writer.add_image('four_fashion_mnist_images', img_grid) # + [markdown] id="-vZgPmDCUJ7O" colab_type="text" # # #3.TensorBoardを使用してモデルを検査する # + id="022VWwrudgMX" colab_type="code" colab={} writer.add_graph(net, images) writer.close() # + [markdown] id="cRazX4Rlk6Vh" colab_type="text" # #4.「Projector」を追加する # + id="QXZhK1AiNW5z" colab_type="code" colab={} #①追加のプログラム============================= #TensorFlowパッケージが存在してしまっている場合は #以下プログラムで一時しのぎが可能 #import tensorflow as tf #import tensorboard as tb #tf.io.gfile = tb.compat.tensorflow_stub.io.gfile #=============================================== #ヘルパー関数 def select_n_random(data, labels, n=100): ''' Selects n random datapoints and their corresponding labels from a dataset ''' assert len(data) == len(labels) perm = torch.randperm(len(data)) return data[perm][:n], labels[perm][:n] # select random images and their target indices images, labels = select_n_random(trainset.data, trainset.targets) # get the class labels for each image class_labels = [classes[lab] for lab in labels] # log embeddings features = images.view(-1, 28 * 28) writer.add_embedding(features, metadata=class_labels, label_img=images.unsqueeze(1)) writer.close() # + [markdown] id="jVEVY8m2PURp" colab_type="text" # ここで出るエラーについては以下を参考にしました。 # # https://github.com/pytorch/pytorch/issues/30966 # + [markdown] id="9rLVhHyvG5eV" colab_type="text" # ##macでの階層指定 # ターミナルでtensorboardを起動します。私のmac環境では、「/Python」の階層にJupyterノートを配置しています。そのため、コマンドのlogdirを次のように指定したらうまく動作しました。 # # tensorboard --logdir=/Python/runs # # ##windowsでの階層指定 # AnacondaPromptでTensorBoardを起動します。私のwindows環境では、「C:\Users\ユーザー名(任意)\Python」階層にJupyterノートブックのPythonプログラムを保存しています。そのため、以下のようにlogdirを指定するとうまくいきました。 # # tensorboard --logdir=C:\Users\ユーザー名(任意)\Python\runs # # ##TensorBoardへのアクセス # # ブラウザにて、 # # http://localhost:6006/ # # を入力してTensorBoardにアクセス。 # + [markdown] id="8YWu3ZxhlbJh" colab_type="text" # #5. 訓練のトラッキングをする # + id="oF3XlKV1lTsT" colab_type="code" colab={} #ヘルパー関数 def images_to_probs(net, images): ''' ニューラルネットに画像を入れて、予測を行い、出力である確率を取得します。 ''' output = net(images) #ニューラルネットの出力で最大の値の確率値を取得 _, preds_tensor = torch.max(output, 1) preds = np.squeeze(preds_tensor.numpy())#tensorからnumpyに return preds, [F.softmax(el, dim=0)[i].item() for i, el in zip(preds, output)] def plot_classes_preds(net, images, labels): ''' 「images_to_probs」関数の予測値に、matplotlibの図を生成し加えます。 ''' preds, probs = images_to_probs(net, images) #予測と正解を一緒にしてミニバッチのデータをプロットします。 fig = plt.figure(figsize=(12, 48)) for idx in np.arange(4): ax = fig.add_subplot(1, 4, idx+1, xticks=[], yticks=[]) matplotlib_imshow(images[idx], one_channel=True) ax.set_title("{0}, {1:.1f}%\n(label: {2})".format( classes[preds[idx]], probs[idx] * 100.0, classes[labels[idx]]), color=("green" if preds[idx]==labels[idx].item() else "red")) return fig # + id="YG3djVYI9ioj" colab_type="code" colab={} device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") net.to(device) #net.cpu()#CPU利用 criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # + [markdown] id="0burVtBTkX5W" colab_type="text" # 最後に、前のチュートリアルと同じモデルトレーニングコードを使用してモデルをトレーニングしますが、コンソールに出力するのではなく、1000バッチごとに結果をTensorBoardに書き込みます。これは、add_scalar関数を使用して行われます。 # # さらに、トレーニング中に、モデルの予測と、そのバッチに含まれる4つの画像の実際の結果を示す画像を生成します。 # + id="-v7-UucOljA9" colab_type="code" colab={} running_loss = 0.0 #訓練ループ for epoch in range(1): #ミニバッチループ for i, data in enumerate(trainloader, 0): #入力データ。「data」は [inputs, labels]のリスト。 #【GPU】 #inputs, labels = data[0].to(device) , data[1].to(device) #【CPU】 inputs, labels = data#CPU #勾配の初期化 optimizer.zero_grad() #順伝播、誤差計算、逆伝播、最適化を行います。 outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() #損失の計算を行い、変数「runnning_loss」に累積 running_loss += loss.item() if i % 1000 == 999: #1000ミニバッチ毎に処理(画像4000枚ごと) #TensorBoardに1000ミニバッチの損失平均を書き込みます #add_scalarには、「データ名」「Y軸データの値」「X軸データ」で与えています。 #X軸のデータとして、ミニバッチ数を計算しています。 writer.add_scalar('training loss', running_loss / 1000, epoch * len(trainloader) + i) #「predictions vs. actuals」を作成します。 #1000ミニバッチ毎にひとつのミニバッチの正解を視覚的に表示します。 writer.add_figure('predictions vs. actuals', #【GPU】 #plot_classes_preds(net.cpu(), inputs.cpu(), labels.cpu()),#GPU利用時ここではCPUで処理 #【CPU】 plot_classes_preds(net, inputs, labels), global_step=epoch * len(trainloader) + i) #【GPU】 #net.cuda(), inputs.cuda(), labels.cuda() print("チェックポイント") #「running_loss」変数の初期化 running_loss = 0.0 print('Finished Training') # + [markdown] id="KMQ-lbl_kbn5" colab_type="text" # これで、スカラータブを見て、トレーニングの15,000回の反復にわたってプロットされたランニングロスを確認できます。 # # さらに、学習を通じてモデルが任意のバッチで行った予測を確認できます。これを確認するには、「画像」タブを表示し、「予測vs実績」ビジュアライゼーションの下にスクロールしてください。これは、たとえば、わずか3000回のトレーニングを繰り返しただけで、モデルはシャツ、スニーカー、コートなどの視覚的に区別できるクラスをすでに区別できたことを示していますが、トレーニングの後半ほどは確信が持てません。 # # 前のチュートリアルでは、モデルがトレーニングされた後、クラスごとの精度を調べました。ここでは、TensorBoardを使用して、各クラスの精度-再現率曲線(ここで適切な説明)をプロットします。 # + [markdown] id="B8MhB1_nkiz0" colab_type="text" # #6.TensorBoardでモデルを評価する # + [markdown] id="bPjmf9ITFaih" colab_type="text" # ##softmaxの挙動の確認 # + id="MWdV84svFDYt" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 102} outputId="98b0954f-7e47-493f-d080-cf02993e9b14" #Softmaxを行う(2階のテンソル、行列の場合、dim1で行の方向に処理を行う設定) m = nn.Softmax(dim=1) print(m) #2行3列のテンソルをランダムな値で初期化 input = torch.randn(2, 3) print(input) #テンソルにSoftMaxの処理を行う output = m(input) print(output) # + id="GiGh1MWuFYg7" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="ee3c545e-6559-4760-f32a-c25146f96818" #行方向にテンソルを合計する print(torch.sum(output, dim=1)) # + [markdown] id="fOFuQ_b7FL9s" colab_type="text" # PyTorchのsoftmax関数 # # https://pytorch.org/docs/master/generated/torch.nn.Softmax.html # + [markdown] id="s4gd2yqHoCY_" colab_type="text" # ##torch.catとstackの挙動 # + id="TPFB_R7Cm7Vc" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="52fa71b6-6bc2-4529-8ea5-dc1ca4e2d428" x = torch.randn(2, 3) x # + id="mPiWLq0ZnVB0" colab_type="code" colab={} #リストを作成します。 x_list = [] x_list.append(x) x_list.append(x) x_list.append(x) # + id="Fd-Dv13MolBa" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 170} outputId="0e0f0f71-4115-49d6-b6f2-8df4b6ce8421" print(torch.stack(x_list)) torch.stack(x_list).size() # + [markdown] id="f2X1vBZ_pzh7" colab_type="text" # torch.stack # # https://pytorch.org/docs/master/generated/torch.stack.html # + id="Mlg9eLX1ntPq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 136} outputId="b414064f-a883-4004-f6a4-cdb71d526cd8" print(torch.cat(x_list)) torch.cat(x_list).size() # + [markdown] id="7DC_0vE2n5Ba" colab_type="text" # catにリストを与えることで、行方向に結合ができる。 # # torch.cat # # https://pytorch.org/docs/master/generated/torch.cat.html?highlight=torch%20cat#torch.cat # + id="wnQS6Rnekb93" colab_type="code" colab={} #1. テストデータの「probability」の値を求めます(モデルが出力する確率の値です) #2. テストデータのモデルの予測値を求めます。 #この処理には10秒程度かかります。 class_probs = [] class_preds = [] with torch.no_grad(): for data in testloader: #【GPU】 #images, labels = data[0].to(device) , data[1].to(device) #【CPU】 images, labels = data output = net(images) #テンソルの行(画像1枚当たりの出力)をソフトマックス関数に通す #class_probs_batchはリスト。 class_probs_batch = [F.softmax(el, dim=0) for el in output] #一番値が大きいクラスをMax関数で選択して予測回答とする(第二引数が1で行の中の最大値を取る) _, class_preds_batch = torch.max(output, 1)     #Pythonのリストに「probability」と「予測回答」を追加していきます #class_probsはリスト。 class_probs.append(class_probs_batch) class_preds.append(class_preds_batch) #[torch.stack(batch) for batch in class_probs] #テンソルを要素に持つリストをテンソルに変換 test_probs = torch.cat([torch.stack(batch) for batch in class_probs]) #print(test_probs.size())#ここで、[10000,10]の行列となる。 test_preds = torch.cat(class_preds) #print(test_preds.size())#ここで、[10000]のベクトルとなる。 # ヘルパー関数 def add_pr_curve_tensorboard(class_index, test_probs, test_preds, global_step=0): ''' Takes in a "class_index" from 0 to 9 and plots the corresponding precision-recall curve ''' #ラベル(class_index)と等しいtest_predsの値がtensorboard_predsとなる。 tensorboard_preds = test_preds == class_index #ラベルの列のみを取得してtensorboard_probsとする。 tensorboard_probs = test_probs[:, class_index] writer.add_pr_curve(classes[class_index], tensorboard_preds, tensorboard_probs, global_step=global_step) writer.close() # PRカーブを作成する。0~9までのラベルで作成するのでループする。 for i in range(len(classes)): add_pr_curve_tensorboard(i, test_probs, test_preds)
VISUALIZING_MODELS,_DATA,_AND_TRAINING_WITH_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 # language: python # name: python3 # --- # ## Data Analysis # Our goal is to find the correlation between temperature and the amount of crime. <br/> # However, we analyze the crime and weather separately, because we might find something interesting here. # ### Crime Data # - Load the csv file # + import pandas as pd crime = pd.read_csv('../data/crimeandweather.csv') crime['OCCURRED_ON_DATE'] = pd.to_datetime(crime['OCCURRED_ON_DATE']) crime['DATE'] = pd.to_datetime(crime['DATE']) crime['Lat'] = pd.to_numeric(crime['Lat']) crime['Long'] = pd.to_numeric(crime['Long']) print("strat date:", crime['OCCURRED_ON_DATE'].min()) print("end date:", crime['OCCURRED_ON_DATE'].max()) crime.head() # - # - Create hour column and count the amount of crimes in each hour and plot # + crimehour = pd.DataFrame() crimehour['HOUR'] = crime.apply(lambda x : x['TIME'][0:2], axis = 1) crimehourcount = pd.DataFrame() crimehourcount['COUNT'] = crimehour['HOUR'].value_counts(sort=False) crimehourcount = crimehourcount.sort_index() import matplotlib.pyplot as plt # %matplotlib inline # average line avg = crime['OCCURRED_ON_DATE'].count()/24 plt.figure(figsize=(20,10)) plt.axhline(y=avg, color='red') plt.bar(crimehourcount.index.tolist(), crimehourcount['COUNT'], 0.5) plt.show # - # The lowest point of crime is on 4-5 am, and the peak is at 5 pm.<br/> # The red line is an average amount of crime for all. After 10 pm, the crimes drop below the average line and go beyond the average line at 8 am.<br/> # Note that the 0 am hour also contains the crimes that do not have a create time, so they set the time to 00:00:00. # - Create day column and count the amount of crimes in each day and plot # + crimedaycount = pd.DataFrame() daylist = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] crimedaycount['COUNT'] = crime['DAY_OF_WEEK'].value_counts(sort=False) crimedaycount['DAY'] = crimedaycount.apply(lambda x : daylist.index(x.name), axis = 1) crimedaycount = crimedaycount.sort_values(['DAY']) # average line avg = crime['OCCURRED_ON_DATE'].count()/7 plt.figure(figsize=(20,10)) plt.axhline(y=avg, color='red') plt.bar(crimedaycount.index.tolist(), crimedaycount['COUNT'], 0.5) plt.show # - # The crime rates drop on the weekend and peak on Friday. It seems like criminals need to rest too. # - Count the amount of crimes in each district and plot # + crimedistrictcount = pd.DataFrame() crimedistrictcount['DISTRICT'] = crime['DISTRICT'].value_counts(sort=False) crimedistrictcount = crimedistrictcount.sort_values(['DISTRICT'], ascending=False) crimedistrictcount.head() # average line avg = crime['DISTRICT'].count()/crimedistrictcount['DISTRICT'].count() plt.figure(figsize=(20,10)) plt.axhline(y=avg, color='red') plt.bar(crimedistrictcount.index.tolist(), crimedistrictcount['DISTRICT'], 0.5) plt.show # - # The district "B2" has the highest rate of crime, which is Roxbury. The lowest is in the "A15" district, Charlestown. # - Count the amount of vehicle accident in each hour and plot # + crimemotorhour = pd.DataFrame() crimemotorhour['HOUR'] = crime[crime['OFFENSE_CODE_GROUP'] == 'Motor Vehicle Accident Response'].apply(lambda x : x['TIME'][0:2], axis = 1) crimemotorhourcount = pd.DataFrame() crimemotorhourcount['HOUR'] = crimemotorhour['HOUR'].value_counts(sort=False).index crimemotorhourcount['COUNT'] = crimemotorhour['HOUR'].value_counts(sort=False).values crimemotorhourcount = crimemotorhourcount.sort_values(by=['HOUR']) # average line avg = crime[crime['OFFENSE_CODE_GROUP'] == 'Motor Vehicle Accident Response']['OCCURRED_ON_DATE'].count()/crimemotorhourcount['HOUR'].count() plt.figure(figsize=(20,10)) plt.axhline(y=avg, color='red') plt.bar(crimemotorhourcount['HOUR'].tolist(), crimemotorhourcount['COUNT'], 0.5) plt.show # - # The vehicle accident rate decrease after the sunset and rise in the morning.<br/> # Maybe because the number of people drives at night is less compare with the day. # - Count the amount of robbery in each day and plot # + crimerobberyday = pd.DataFrame() crimerobberyday['DAY'] = crime[crime['OFFENSE_CODE_GROUP'] == 'Robbery'].apply(lambda x : x['DATE'].day, axis = 1) crimerobberydaycount = pd.DataFrame() crimerobberydaycount['DAY'] = crimerobberyday['DAY'].value_counts(sort=False).index crimerobberydaycount['COUNT'] = crimerobberyday['DAY'].value_counts(sort=False).values crimerobberydaycount = crimerobberydaycount.sort_values(by=['DAY']) # average line avg = crime[crime['OFFENSE_CODE_GROUP'] == 'Robbery']['DATE'].count()/crimerobberydaycount['DAY'].count() plt.figure(figsize=(20,10)) plt.axhline(y=avg, color='red') plt.bar(crimerobberydaycount['DAY'].tolist(), crimerobberydaycount['COUNT'], 0.5) plt.show # - # Unfortunately, there is not a significate pattern between robbery and day.<br/> # The 31st day have less crime because not every month have 31 days. # ### Weather Data # Since weather data contain only two columns, there is not many things we can analyze. # - Plot temperature distribution # + crimetempcount = pd.DataFrame() crimetempcount['TAVG'] = crime['TAVG'].value_counts(sort=False) crimetempcount = crimetempcount.sort_index() crimetempcount.head() plt.figure(figsize=(20,10)) plt.bar(crimetempcount.index.tolist(), crimetempcount['TAVG'], 0.5) plt.show # + from scipy import stats _, p = stats.normaltest(crimetempcount['TAVG']) alpha = 0.05 print("p =",p) if p < alpha: # null hypothesis: x comes from a normal distribution print("The null hypothesis can be rejected") else: print("The null hypothesis cannot be rejected") # - # The distribution is left-skewed. Most of the temperature is between 40 to 80 degrees. # - Plot average temperature by districts plt.figure(figsize=(20,10)) plt.scatter(crime.groupby(['DISTRICT']).mean()['TAVG'].index, crime.groupby(['DISTRICT']).mean()['TAVG'].values, linewidths =10) plt.show # The difference between the average temperature of each district is within 1 degree, which is close. # The weather data alone is not insightful, we should analyze it with crime data to gain more insight. # ### Crime and Weather Data # We want to see the relationship between crimes and weather, and we got the tempurature data by day, <br/> # so we need to group the crimes data by day and marge it with weather data. # - Group the crime data by day and plot # + crimedatecount = pd.DataFrame() crimedatecount['DATE'] = crime['DATE'].value_counts(sort=False).index crimedatecount['COUNT'] = crime['DATE'].value_counts(sort=False).values crimedatecount = crimedatecount.sort_values(['DATE']) from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() plt.figure(figsize=(20,10)) plt.plot(crimedatecount['DATE'], crimedatecount['COUNT']) # - # The crime rate is moving like a cycle with peaks at the same time of year. # - Group the crime data by day and plot # + temp = crime[['DATE', 'TAVG']] temp = temp.drop_duplicates(keep = 'first') temp = temp.sort_values(by='DATE') plt.figure(figsize=(20,10)) plt.plot(temp['DATE'], temp['TAVG']) # - # The temperature has a cycle, too, and it looks like the crime data. # - Marge the crime and weather data and plot # + crimedatecountontem = pd.merge(crimedatecount, temp, how='left', on='DATE') crimedatecountontem = crimedatecountontem.set_index('DATE') plt.figure(figsize=(20,10)) plt.plot(crimedatecountontem.index,crimedatecountontem['COUNT'], label="amount of crime in days") plt.plot(crimedatecountontem.index,crimedatecountontem['TAVG'], label="temperature") plt.legend() # - # Due to the fluctuations of both data, we cannot tell the relationship between them.<br/> # We can apply the technique in time series analysis, which is moving the average, the technique is used to aggregate data, and the lines will be smoother. # - Apply moving average and plot # + crimetempma = crimedatecountontem.rolling(window=30).mean() crimetempma = crimetempma.dropna() plt.figure(figsize=(20,10)) plt.plot(crimetempma.index,crimetempma['COUNT'], label="amount of crime in days") plt.plot(crimetempma.index,crimetempma['TAVG'], label="temperature") plt.legend() # - # When the line is smoother, we can see the trend of the lines. <br/> # However, we will make the lines closer for a better interpretation. # - Magnify temperate line # we add 200 to each temperature, so the lines become closer crimetempma['TAVG'] = crimetempma['TAVG'] + 200 plt.figure(figsize=(20,10)) plt.plot(crimetempma.index,crimetempma['COUNT'], label="amount of crime in days") plt.plot(crimetempma.index,crimetempma['TAVG'], label="temperature") plt.legend() # Now we can see that when the temperature rises the crime rate rise too, and when it drops, the crime rate also drops.<br/> # The essential part is when the temperature is sideway, the crime rate also follows the same pattern. (between 2017-01 to 2017-07,2018-01 to 2018-07 and 2019-01 to 2019-07) # Since we know that there is a relationship between two data, we can measure the relationship with linear regression. <br/> # We can group the data by temperatures and count the average number of crimes that happen in the days with the temperature. # - Group a number of crimes on each day by temperature and plot # + tempandcrime = crimedatecountontem.groupby('TAVG').mean() plt.figure(figsize=(20,10)) plt.scatter(tempandcrime.index,tempandcrime['COUNT'],s=30) # - # There is clearly a trend between two quantities, but we will look more into this in the next file.
analysis/.ipynb_checkpoints/data_analysis_overall-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] id="hToErIuE9G27" # # Salient Attention U-Net Model with One Contour Saliency Maps # # It implements our proposed Salient Attention U-Net model using saliency masks with a single contour # + [markdown] id="FK9tFS7kig2O" # # Import libraries # + id="IBcnYMFqT2VV" import numpy as np from keras.models import Model from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, Conv2DTranspose, multiply, Lambda, add, Activation from keras.layers import concatenate from keras.optimizers import * import keras.backend as K from keras.callbacks import EarlyStopping from keras.preprocessing import image import tensorflow as tf import matplotlib.pyplot as plt # %matplotlib inline from sklearn.metrics import roc_curve, roc_auc_score, confusion_matrix from sklearn.model_selection import KFold import os from os import listdir import natsort # it may need to be installed by 'pip install natsort' import datetime now = datetime.datetime.now # + [markdown] id="UBrcOZP4i3Rx" # # Load the images # + colab={"base_uri": "https://localhost:8080/"} id="mkO5IJkQT2Vc" outputId="85071379-3f45-4fab-8856-161b7f520be8" # Directory with salient masks, images, and ground truths path_sals = "../Data/saliency_maps_one_contour/" path_imgs = "../Data/images/" path_masks = "../Data/masks/" imagesList = listdir(path_sals) # Sort the images in ascending order imgList=natsort.natsorted(imagesList) # Introduce parameters img_row = 256 img_col = 256 img_chan = 1 epochnum = 200 batchnum = 4 input_size = (img_row, img_col, img_chan) num_imgs = len(imgList) print("Number of images:", num_imgs) # + colab={"base_uri": "https://localhost:8080/"} id="opkb-9ErvJAI" outputId="cc6e8c91-3f9f-4c9e-91e3-facae9110cf3" # Load the images def img_load(dir_path, imgs_list, imgs_array): for i in range(num_imgs): tmp_img = image.load_img(os.path.join(dir_path, imgs_list[i]), target_size=(img_row, img_col, img_chan)) img = image.img_to_array(tmp_img) imgs_array[i] = img[:,:,0]/255.0 # Expand the dimensions of the arrays imgs_array = np.expand_dims(imgs_array, axis=3) return imgs_array # Initialize the arrays imgs = np.zeros((num_imgs, img_row, img_col)) masks = np.zeros_like(imgs) sals = np.zeros_like(imgs) imgs = img_load(path_imgs, imgList, imgs) masks = img_load(path_masks, imgList, masks) sals = img_load(path_sals, imgList, sals) print("Images", imgs.shape) print("Masks", masks.shape) print("Sals", sals.shape) # + colab={"base_uri": "https://localhost:8080/", "height": 441} id="VWpyLVPkvJAO" outputId="f8f44872-9593-4cee-b516-516fbad0be3b" # Plot the first and last images plt.figure(figsize = (14,6)) plt.subplot(231) plt.imshow(np.squeeze(imgs[2]), cmap = "gray") plt.title('First image') plt.subplot(232) plt.imshow(np.squeeze(masks[2]), cmap = "gray") plt.title('First mask') plt.subplot(233) plt.imshow(np.squeeze(sals[2]), cmap = "gray") plt.title('First saliency') plt.subplot(234) plt.imshow(np.squeeze(imgs[-1]), cmap = "gray") plt.title('Last image') plt.subplot(235) plt.imshow(np.squeeze(masks[-1]), cmap = "gray") plt.title('Last mask') plt.subplot(236) plt.imshow(np.squeeze(sals[-1]), cmap = "gray") plt.title('Last saliency') plt.tight_layout() plt.show() # + [markdown] id="JiUcEv90jHPB" # # Performance metrics # + id="6Q3vyYv-pUeM" # Define loss and performance metrics # Partially from Abraham and Khan (2019) - A Novel Focal Tversly Loss Funciton for Lesion Segmentation # Dice score coefficient and Dice loss def dsc(y_true, y_pred): smooth = 1. # masks y_true_fm = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_fm * y_pred_f) score = (2. * intersection + smooth) / (K.sum(y_true_fm) + K.sum(y_pred_f) + smooth) return score def dice_loss(y_true, y_pred): loss = 1 - dsc(y_true, y_pred) return loss # Performance metrics: Dice score coefficient, IOU, recall, sensitivity def auc(y_true, y_pred): y_pred_pos = np.round(np.clip(y_pred, 0, 1)) y_pred_neg = 1 - y_pred_pos y_pos = np.round(np.clip(y_true, 0, 1)) # ground truth y_neg = 1 - y_pos tp = np.sum(y_pos * y_pred_pos) tn = np.sum(y_neg * y_pred_neg) fp = np.sum(y_neg * y_pred_pos) fn = np.sum(y_pos * y_pred_neg) tpr = (tp + K.epsilon()) / (tp + fn + K.epsilon()) #recall tnr = (tn + K.epsilon()) / (tn + fp + K.epsilon()) prec = (tp + K.epsilon()) / (tp + fp + K.epsilon()) #precision iou = (tp + K.epsilon()) / (tp + fn + fp + K.epsilon()) #intersection over union dsc = (2*tp + K.epsilon()) / (2*tp + fn + fp + K.epsilon()) #dice score return [dsc, iou, tpr, prec] # Expand a tensor by repeating the elements in a dimension def expend_as(tensor, rep): my_repeat = Lambda(lambda x, repnum: K.repeat_elements(x, repnum, axis=3), arguments={'repnum': rep})(tensor) return my_repeat # + id="H5kFD10fC3SM" # Salient attention block def SalientAttentionBlock(f_maps, sal_ins, pool_maps, num_fmaps): # Inputs: feature maps from UNet, saliency images, pooled layers from UNet, number of output feature maps conv1_salins = Conv2D(128, (1, 1), activation='relu')(sal_ins) conv1_fmaps = Conv2D(128, (1, 1), strides=(2, 2), activation='relu')(f_maps) attn_add = add([conv1_fmaps,conv1_salins]) conv_1d = Conv2D(128, (3, 3), activation='relu', padding='same')(attn_add) conv_1d = Conv2D(128, (3, 3), activation='relu', padding='same')(conv_1d) conv_1d = Conv2D(1, (1, 1), activation='relu')(conv_1d) conv_1d = expend_as(conv_1d,32) conv_nd = Conv2D(num_fmaps, (1, 1), activation='relu')(conv_1d) attn_act = Activation('sigmoid')(conv_nd) attn = multiply([attn_act, pool_maps]) return attn # Convolutional block for UNet def UNetBlock(in_fmaps, num_fmaps): # Inputs: feature maps for UNet, number of output feature maps conv1 = Conv2D(num_fmaps, (3, 3), activation='relu', padding='same')(in_fmaps) conv_out = Conv2D(num_fmaps, (3, 3), activation='relu', padding='same')(conv1) return conv_out # + [markdown] id="mUqrVcP3javq" # # Network # + id="S4rkx4tFpUeO" # Build the model def Network(): input = Input(shape=input_size) conv1 = UNetBlock(input, 32) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) input2 = Input(shape=input_size) dwns1 = MaxPooling2D(2,2)(input2) attn1 = SalientAttentionBlock(conv1, dwns1, pool1, 32) conv2 = UNetBlock(attn1, 32) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) dwns2 = MaxPooling2D(4,4)(input2) attn2 = SalientAttentionBlock(conv2, dwns2, pool2, 32) conv3 = UNetBlock(attn2, 64) pool3 = MaxPooling2D(pool_size=(2, 2))(conv3) dwns3 = MaxPooling2D(8,8)(input2) attn3 = SalientAttentionBlock(conv3, dwns3, pool3, 64) conv4 = UNetBlock(attn3, 64) pool4 = MaxPooling2D(pool_size=(2, 2))(conv4) dwns4 = MaxPooling2D(16,16)(input2) attn4 = SalientAttentionBlock(conv4, dwns4, pool4, 64) conv5 = UNetBlock(attn4, 128) up6 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv5), attn3], axis=3) conv6 = UNetBlock(up6, 64) up7 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv6), attn2], axis=3) conv7 = UNetBlock(up7, 64) up8 = concatenate([Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv7), attn1], axis=3) conv8 = UNetBlock(up8, 32) up9 = concatenate([Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv8), conv1], axis=3) conv9 = UNetBlock(up9, 32) conv10 = Conv2D(1, (1, 1), activation='sigmoid')(conv9) model = Model(inputs = [input, input2], outputs = conv10) return model # + [markdown] id="NeiBGh5ojroI" # # Training and cross-validation # + id="FRbeJfnw3IkY" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="a67e2035-174d-4269-a834-6b2fd0b863ce" # Evaluate the models using using k-fold cross-validation n_folds = 5 numepochs = np.zeros(n_folds,) dice_score = np.zeros(n_folds,) iou_score = np.zeros_like(dice_score) rec_score = np.zeros_like(dice_score) prec_score = np.zeros_like(dice_score) globacc_score = np.zeros_like(dice_score) auc_roc_score = np.zeros_like(dice_score) # Prepare cross-validation kfold = KFold(n_folds, shuffle=True, random_state=1) run = 0; # enumerate splits for train_ix, test_ix in kfold.split(imgs): # Display the run number print('Run #', run+1) # Define the model model = Network() # Split into train and test sets imgs_train, masks_train, sals_train, imgs_test, masks_test, sals_test = imgs[train_ix], masks[train_ix], sals[train_ix], imgs[test_ix], masks[test_ix], sals[test_ix] # Compile and fit the model model.compile(optimizer = Adam(lr = 0.0001), loss = dice_loss, metrics = [dsc]) t = now() callbacks = [EarlyStopping(monitor='val_loss', patience = 20)] history = model.fit([imgs_train, sals_train], masks_train, validation_split=0.15, batch_size=batchnum, epochs=epochnum, verbose=0, callbacks=callbacks) print('Training time: %s' % (now() - t)) # Plot the loss and accuracy train_loss = history.history['loss'] val_loss = history.history['val_loss'] acc = history.history['dsc'] val_acc = history.history['val_dsc'] epochsn = np.arange(1, len(train_loss)+1,1) plt.figure(figsize = (12,5)) plt.subplot(121) plt.plot(epochsn,train_loss, 'b', label='Training Loss') plt.plot(epochsn,val_loss, 'r', label='Validation Loss') plt.grid(color='gray', linestyle='--') plt.legend() plt.title('LOSS, Epochs={}, Batch={}'.format(epochnum, batchnum)) plt.xlabel('Epochs') plt.ylabel('Loss') plt.subplot(122) plt.plot(epochsn, acc, 'b', label='Training Dice Coefficient') plt.plot(epochsn, val_acc, 'r', label='Validation Dice Coefficient') plt.grid(color='gray', linestyle='--') plt.legend() plt.title('DSC, Epochs={}, Batch={}'.format(epochnum, batchnum)) plt.xlabel('Epochs') plt.ylabel('CSC') plt.show() # Make predictions t = now() preds = model.predict([imgs_test, sals_test]) print('Testing time: %s' % (now() - t)) # Evaluate model num_test = len(imgs_test) # Calculate performance metrics dsc_sc = np.zeros((num_test,1)) iou_sc = np.zeros_like(dsc_sc) rec_sc = np.zeros_like(dsc_sc) tn_sc = np.zeros_like(dsc_sc) prec_sc = np.zeros_like(dsc_sc) thresh = 0.5 for i in range(num_test): dsc_sc[i], iou_sc[i], rec_sc[i], prec_sc[i] = auc(masks_test[i], preds[i] >thresh) print('-'*30) print('USING THRESHOLD', thresh) print('\n DSC \t\t{0:^.3f} \n IOU \t\t{1:^.3f} \n Recall \t{2:^.3f} \n Precision\t{3:^.3f}'.format( np.sum(dsc_sc)/num_test, np.sum(iou_sc)/num_test, np.sum(rec_sc)/num_test, np.sum(prec_sc)/num_test )) ''' # To plot a set of images with predicted masks uncomment these lines num_disp = 10 j=1 plt.figure(figsize = (14,num_disp*3)) for i in range(num_disp): plt.subplot(num_disp,5,j) plt.imshow(np.squeeze(imgs_test[i]), cmap='gray') plt.title('Image') j +=1 plt.subplot(num_disp,5,j) plt.imshow(np.squeeze(sals_test[i]),cmap='gray') plt.title('Saliency') j +=1 plt.subplot(num_disp,5,j) plt.imshow(np.squeeze(masks_test[i]),cmap='gray') plt.title('Mask') j +=1 plt.subplot(num_disp,5,j) plt.imshow(np.squeeze(preds[i])) plt.title('Prediction') j +=1 plt.subplot(num_disp,5,j) plt.imshow(np.squeeze(np.round(preds[i])), cmap='gray') plt.title('Rounded; IOU=%0.2f, Rec=%0.2f, Prec=%0.2f' %(iou_sc[i], rec_sc[i], prec_sc[i])) j +=1 plt.tight_layout() plt.show() ''' # Confusion matrix confusion = confusion_matrix( masks_test.ravel(),preds.ravel()>thresh) accuracy = 0 if float(np.sum(confusion))!=0: accuracy = float(confusion[0,0]+confusion[1,1])/float(np.sum(confusion)) print(' Global Acc \t{0:^.3f}'.format(accuracy)) # Area under the ROC curve AUC_ROC = roc_auc_score(preds.ravel()>thresh, masks_test.ravel()) print(' AUC ROC \t{0:^.3f}'.format(AUC_ROC)) print('\n') print('*'*60) # Save outputs numepochs[run] = epochsn[-1] dice_score[run] = np.sum(dsc_sc)/num_test iou_score[run] = np.sum(iou_sc)/num_test rec_score[run] = np.sum(rec_sc)/num_test prec_score[run] = np.sum(prec_sc)/num_test globacc_score[run] = accuracy auc_roc_score[run] = AUC_ROC run +=1 # + [markdown] id="zJFQDU1hj1pw" # # Display the Results # + id="p-3sA63cB2Xn" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="cf08333b-6493-406d-cd41-2ed4fa76f687" # Display the scores in a table import pandas from pandas import DataFrame df = DataFrame({'Epochs Number': numepochs, 'Dice Score': dice_score, 'IOU Score': iou_score, 'Recall (Sensitivity)': rec_score, 'Precision': prec_score, 'Global Accuracy': globacc_score, 'AUC-ROC': auc_roc_score}) df # + id="eKRErUJ8a2dD" colab={"base_uri": "https://localhost:8080/", "height": 80} outputId="4e59b160-896e-4aa6-8032-a48a8ecd7f80" # Calculate mean values of the scores numepochs_mean = np.mean(numepochs) dice_mean = np.mean(dice_score) iou_mean = np.mean(iou_score) rec_mean = np.mean(rec_score) prec_mean = np.mean(prec_score) globacc_mean = np.mean(globacc_score) auc_roc_mean = np.mean(auc_roc_score) # Mean values of the scores df2 = DataFrame({'Epochs Number Mean': numepochs_mean, 'Dice Score Mean': dice_mean, 'IOU Score Mean': iou_mean, 'Recall (Sensitivity) Mean': rec_mean, 'Precision Mean': prec_mean, 'Global Accuracy Mean': globacc_mean, 'AUC-ROC Mean': auc_roc_mean},index=[5]) df2 # + id="iLjytCI59vdo" colab={"base_uri": "https://localhost:8080/", "height": 80} outputId="f0810d08-22cd-4cfb-b320-823511cf10f3" # Calculate standard deviations of the scores dice_std = np.std(dice_score) iou_std = np.std(iou_score) rec_std = np.std(rec_score) prec_std = np.std(prec_score) globacc_std = np.std(globacc_score) auc_roc_std = np.std(auc_roc_score) # Standard deviations of the scores df3 = DataFrame({'Dice Score STD': dice_std, 'IOU Score STD': iou_std, 'Recall (Sensitivity) STD': rec_std, 'Precision STD': prec_std, 'Global Accuracy STD': globacc_std, 'AUC-ROC STD': auc_roc_std}, index=[5]) df3
Codes/UNet_SA_C.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 # --- # #!/usr/bin/env python3 from __future__ import print_function import cv2 import os from subprocess import call import subprocess import threading import time class directoryLoop(): def __init__(self,root,fps=10,ipm=None,replay=False): self.root=root self.replay=replay self.ipm=ipm self.img_files=os.listdir(self.root) self.img_files.sort() self.sleep_time=1/fps; self.kill=False def loop(self): while self.kill is not True: for img_name in self.img_files: file_path=os.path.join(self.root,img_name) if os.path.isfile(file_path): frame = cv2.imread(file_path) if self.ipm is not None: self.ipm.img_publish(frame) else: print(f'File {img_name} captured') time.sleep(self.sleep_time) if replay==False: break; root='/media/rouholla/My Passport/Dataset/Kitti/Odometry/dataset/sequences/00/image_2' directory_loop=directoryLoop(root) class imgPubliherMachine(): def __init__(self,params, img_topic="camera/image_raw",camera_info_topic="camera/cameraInfo"): self.params=params self.transform=params['~img_transforms'].split(',') self.pub = rospy.Publisher(camera_info_topic,CameraInfo,queue_size=1) self.pub_Image = rospy.Publisher(img_topic,Image,queue_size=1) self.image=Image() self.bridge = CvBridge() self.encoding = "8UC3" calib_load=(True if params['~path_to_calib_file'] is not None else False) if calib_load: camera_name, self.camera_info = readCalibration(params['~path_to_calib_file']) else: self.camera_info=CameraInfo() self.tranform_fncs={'to_gray':self.img_prepare_gray} def to_gray(self,img): self.encoding='mono8' return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def apply_transforms(self,img): for transform in self.transforms: img=self.tranform_fncs[transform](img) return img def img_publish(self,img): img=self.apply_transforms(img) try: self.image=self.bridge.cv2_to_imgmsg(img, encoding) self.image.header.stamp=self.camera_info.header.stamp except CvBridgeError as e: print(e) self.camera_info.header.stamp=rospy.Time.now() self.pub.publish(self.camera_info) self.pub_Image.publish(self.image)
camera_nodes/ps3_eye/ros/image_publisher/nodes/.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: transformer-program # language: python # name: transformer-program # --- import karel_env.dataset_karel as dataset dataset_train, _, _ = dataset.create_default_splits('datasets/karel_dataset/', num_k=10) data_id = dataset_train.ids obs = dataset_train.get_data(data_id[0]) obs[2][:, :, :,:,:].shape obs[1] from karel_env import karel_util from PIL import Image karel_util.state2symbol(dataset_train.get_data(data_id[1000])[3][4, 8, :,:,:]) karel_util.state2image(dataset_train.get_data(data_id[1000])[3][3, 5, :,:,:]).shape # + import numpy as np pad_per_data = dataset_train.get_data(data_id[1000])[11] def convert_to_dec(row): if 2 in row: return 32 elif 3 in row: return 33 else: return int(''.join(row.astype(int).astype(str)), 2) np.apply_along_axis(convert_to_dec, 2, pad_per_data) # - import matplotlib.pyplot as plt for i in range(20): plt.imshow(karel_util.state2image(dataset_train.get_data(data_id[1000])[3][2, i, :,:,:])) plt.show() import math import numpy as np import os import torch from torch import nn import torch.nn.functional as F from torch.utils.data import DataLoader, random_split import pytorch_lightning as pl from torchvision import transforms from torchmetrics import Accuracy from karel_env.dsl import get_KarelDSL class PositionalEncoding(nn.Module): def __init__(self, dim_model, dropout_p, max_len): super().__init__() # Modified version from: https://pytorch.org/tutorials/beginner/transformer_tutorial.html # max_len determines how far the position can have an effect on a token (window) # Info self.dropout = nn.Dropout(dropout_p) # Encoding - From formula pos_encoding = torch.zeros(max_len, dim_model) positions_list = torch.arange(0, max_len, dtype=torch.float).view(-1, 1) # 0, 1, 2, 3, 4, 5 division_term = torch.exp(torch.arange(0, dim_model, 2).float() * (-math.log(10000.0)) / dim_model) # 1000^(2i/dim_model) # PE(pos, 2i) = sin(pos/1000^(2i/dim_model)) pos_encoding[:, 0::2] = torch.sin(positions_list * division_term) # PE(pos, 2i + 1) = cos(pos/1000^(2i/dim_model)) pos_encoding[:, 1::2] = torch.cos(positions_list * division_term) # Saving buffer (same as parameter without gradients needed) pos_encoding = pos_encoding.unsqueeze(0).transpose(0, 1) self.register_buffer("pos_encoding",pos_encoding) def forward(self, token_embedding: torch.tensor) -> torch.tensor: # Residual connection + pos encoding return self.dropout(token_embedding + self.pos_encoding[:token_embedding.size(0), :]) # + import karel_env.dataset_karel as dataset from torch.utils.data import Dataset class KarelVideoDataset(Dataset): def __init__(self, dataset_path='datasets/karel_dataset/', num_k=10, train=False, test=False, val=False): check_arr = [train, test, val] if check_arr.count(True) == 0: raise RuntimeError('No Dataset type specified') if check_arr.count(True) > 1: raise RuntimeError('Multiple Dataset types specified') dataset_train, dataset_test, dataset_val \ = dataset.create_default_splits(dataset_path, num_k=num_k) self.train = train self.test = test self.val = val if self.train: self.data_ids = dataset_train.ids#[:128] self.dataset = dataset_train elif self.test: self.data_ids = dataset_test.ids#[:64] self.dataset = dataset_test else: self.data_ids = dataset_val.ids self.dataset = dataset_val #self.data_ids = dataset_test.ids#[:64] #self.dataset = dataset_test def __len__(self): return len(self.data_ids) def __getitem__(self, idx): data_id = self.data_ids[idx] data = self.dataset.get_data(data_id) observation = data[2] padded_program_tokens = data[1] observation = torch.as_tensor(observation, dtype=torch.float32) demo_length = torch.as_tensor(data[9], dtype=torch.float32) padded_program_tokens = torch.as_tensor(padded_program_tokens, dtype=torch.long) padded_action_history_tokens = torch.as_tensor(data[5], dtype=torch.long) pad_per_data = torch.as_tensor(data[11], dtype=torch.long) demo_length = torch.as_tensor(data[9], dtype=torch.long) """ get_data(id) returns: 0: program, 1: padded_program_tokens, 2: demo[:self.num_k], 3: test_demo, 4: action_history[:self.num_k], 5: padded_action_history_tokens[:self.num_k], 6: test_action_history, 7: padded_test_action_history_tokens, 8: program_length 9: demo_length[:self.num_k] 10: test_demo_length, 11: pad_per_data[:self.num_k], 12: pad_test_per_data 13: program tokens """ return observation, padded_program_tokens, padded_action_history_tokens, pad_per_data, demo_length # - class KarelVideoDataModule(pl.LightningDataModule): def __init__(self, batch_size=32): super().__init__() self.batch_size = batch_size # OPTIONAL, called for every GPU/machine (assigning state is OK) def setup(self, stage = None): # transforms # split dataset if stage in (None, "fit"): # in the paper they use the test for training and not the val # acutally the terms are somehow mixed self.karel_train = KarelVideoDataset(train=True) self.karel_val = KarelVideoDataset(test=True) if stage == "test": self.karel_test = KarelVideoDataset(val=True) if stage == "predict": self.karel_predict = KarelVideoDataset(val=True) # return the dataloader for each split def train_dataloader(self): return DataLoader(self.karel_train, batch_size=self.batch_size) def val_dataloader(self): return DataLoader(self.karel_val, batch_size=self.batch_size) def test_dataloader(self): return DataLoader(self.karel_test, batch_size=self.batch_size) def predict_dataloader(self): return DataLoader(self.karel_predict, batch_size=self.batch_size) PAD_IDX = 50 PAD_IDX_ACTION = 6 PAD_IDX_PERCEPTION = 33 class ProgramSynthesisTransformer(pl.LightningModule): def __init__(self, depth=16, w=8, h=8, k=10, max_demo_len=20, max_program_len=43): super().__init__() self.dataset_type = 'karel' self.dim_model = 256 self.depth = depth self.k = k self.w = w self.h = h self.max_demo_len = max_demo_len self.max_program_len = max_program_len # Metrics self.train_program_acc = Accuracy() self.val_program_acc = Accuracy() """ The CNN for encoding of the single frames of the video. Adapted from the Original Tensorflow implementation of the paper: Neural Program Synthesis from diverse Demonstration Videos. """ self.cnn_encoder = nn.Sequential( nn.Conv2d(depth, 16, kernel_size=3, stride=2, padding=5), nn.LeakyReLU(0.2), nn.BatchNorm2d(16), #nn.GroupNorm(1, 16), nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=5), nn.LeakyReLU(0.2), nn.BatchNorm2d(32), #nn.GroupNorm(1, 32), nn.Conv2d(32, 48, kernel_size=3, stride=2, padding=5), nn.LeakyReLU(0.2), nn.BatchNorm2d(48), #nn.GroupNorm(1, 48), nn.Flatten(), nn.Linear(48*self.h*self.w, self.dim_model) ) self.vocab_size = 50 + 1 self.program_embedding = nn.Embedding(self.vocab_size, self.dim_model) """ Transformer Encoder for the multiple demonstrations received from the CNNs with learned positional embeddings similar to the Vision Transformer. """ encoder_layer = nn.TransformerEncoderLayer(d_model=self.dim_model, nhead=8, batch_first=True, dropout=0.3, activation='gelu', dim_feedforward=256) self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=8) self.transformer_encoder_out = nn.Sequential( nn.Flatten(), nn.Linear(self.dim_model*self.k, self.dim_model), ) # position embedding is learned, similar to ViT self.pos_embedding = nn.Parameter(torch.randn(1, self.max_demo_len + 1, self.dim_model)) """ Program Transformer with an Encoder-Decoder Architecture for creating the program from the output of the transformer_encoder. Modelling the problem in an autoregressive way, predicting each token after each other. """ self.transformer = nn.Transformer(nhead=8, num_encoder_layers=8, num_decoder_layers=3, batch_first=True, d_model=self.dim_model, dropout=0.3, activation="gelu", dim_feedforward=256) self.out = nn.Linear(self.dim_model, self.vocab_size) # pos encoder for the program tokens, similar to original paper as we have tokens self.positional_encoder = PositionalEncoding( dim_model=self.dim_model, dropout_p=0.2, max_len=5000 ) """ Use Xavier Initialization for the weights. """ for p in self.transformer.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) for p in self.transformer_encoder.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) # from: https://towardsdatascience.com/a-detailed-guide-to-pytorchs-nn-transformer-module-c80afbc9ffb1 def get_tgt_mask(self, tgt, pad_idx=None) -> torch.tensor: size = tgt.size(1) # Generates a squeare matrix where the each row allows one word more to be seen mask = torch.tril(torch.ones(size, size) == 1) # Lower triangular matrix mask = mask.float() mask = mask.masked_fill(mask == 0, float('-inf')) # Convert zeros to -inf mask = mask.masked_fill(mask == 1, float(0.0)) # Convert ones to 0 if pad_idx == None: pad_idx = PAD_IDX tgt_padding_mask = (tgt == pad_idx) # EX for size=5: # [[0., -inf, -inf, -inf, -inf], # [0., 0., -inf, -inf, -inf], # [0., 0., 0., -inf, -inf], # [0., 0., 0., 0., -inf], # [0., 0., 0., 0., 0.]] return mask.to(self.device), tgt_padding_mask def get_src_padding_mask(self, demo_length): mask = torch.ones((demo_length.size(0), demo_length.size(1), self.max_demo_len)) for i in range(demo_length.size(0)): for j in range(demo_length.size(1)): mask[i, j, :demo_length[i][j]] = 0 mask = mask.bool() return mask.to(self.device) def create_pad_mask(self, matrix: torch.tensor, pad_token: int) -> torch.tensor: # If matrix = [1,2,3,0,0,0] where pad_token=0, the result mask is # [False, False, False, True, True, True] return (matrix == pad_token) def forward(self, x): # in lightning, forward defines the prediction/inference actions embedding = self.encoder(x) return embedding def stack_demos(self, x, batch_size, demo_length): # (32, 10, 20, 8, 8, 16) # (batch_size, demos, demo_len, w, h, depth) demo_tensors = None for i in range(self.max_demo_len): s_h = x[:, :, i, :, :, :] s_h = s_h.reshape([-1, self.h, self.w, self.depth]).permute(0, 3, 1, 2) s_h = self.cnn_encoder(s_h) s_h = s_h.reshape(batch_size, self.k, -1) s_h += self.pos_embedding[:, :self.k] s_t = self.transformer_encoder(s_h) s_t = self.transformer_encoder_out(s_t) if demo_tensors is None: demo_tensors = s_t.unsqueeze(0) else: demo_tensors = torch.cat([demo_tensors, s_t.unsqueeze(0)]) demo_tensors = demo_tensors.permute(1, 0, 2) return demo_tensors def run_program_transformer(self, y, demo_tensors): emb_program = self.program_embedding(y) emb_program = self.positional_encoder(emb_program) tgt_mask, pad_mask = self.get_tgt_mask(y) output = self.transformer(demo_tensors, emb_program, tgt_mask=tgt_mask, tgt_key_padding_mask=pad_mask) output = self.out(output) output = F.softmax(output, dim=-1) output = output.permute(0, 2, 1) return output def training_step(self, batch, batch_idx): # training_step defined the train loop. # It is independent of forward x, y, _, _, demo_length = batch batch_size = len(batch[0]) src_pad_mask = self.get_src_padding_mask(demo_length) demo_summary_tensor = self.stack_demos(x, batch_size, demo_length) output = self.run_program_transformer(y, demo_summary_tensor) # Logging to TensorBoard by default program_loss = F.cross_entropy(output, y, ignore_index=PAD_IDX) self.log("train_program_loss", program_loss) self.train_program_acc(output, y) self.log('train_program_acc', self.train_program_acc, on_step=True, on_epoch=False) return program_loss def validation_step(self, batch, batch_idx): x, y, _, _, demo_length = batch batch_size = len(batch[0]) #src_pad_mask = self.get_src_padding_mask(demo_length) demo_summary_tensor = self.stack_demos(x, batch_size, demo_length) output = self.run_program_transformer(y, demo_summary_tensor) if batch_idx == 0: print() print('Program GT:', y[0]) print('Program PRED:', torch.argmax(output[0], dim=1)) # Logging to TensorBoard by default program_loss = F.cross_entropy(output, y, ignore_index=PAD_IDX) self.log("val_program_loss", program_loss) self.val_program_acc(output, y) self.log('val_program_acc', self.val_program_acc, on_step=True, on_epoch=False) def test_step(self, batch, batch_idx): x, y, _, _, demo_length = batch #print('actions', actions_inp[1]) #print('perceptions', perceptions_inp[0]) batch_size = len(batch[0]) src_pad_mask = self.get_src_padding_mask(demo_length) demo_summary_tensor = self.stack_demos(x, batch_size, demo_length) output = self.run_program_transformer(y, demo_summary_tensor) print() print('Program GT:', y[0]) print('Program PRED:', torch.argmax(output[0], dim=1)) def configure_optimizers(self): optimizer = torch.optim.SGD(self.parameters(), lr=0.01, momentum=0.9) #optimizer = torch.optim.Adam(self.parameters(), lr=0.001, betas=(0.9, 0.98), eps=1e-9) return optimizer # init model model = ProgramSynthesisTransformer() train_loader = KarelVideoDataModule(batch_size=64) # most basic trainer, uses good defaults (auto-tensorboard, checkpoints, logs, and more) # trainer = pl.Trainer(gpus=8) (if you have GPUs) trainer = pl.Trainer(gpus=1, gradient_clip_val=0.5, stochastic_weight_avg=True, ) trainer.fit(model, train_loader) trainer.test(model=model, datamodule=train_loader) from karel_env.dsl import get_KarelDSL vocab = get_KarelDSL(dsl_type=dataset_train.dsl_type.decode(), seed=123) vocab.__dict__
Neural Program Synthesis with Summarizer Transformer.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 # --- # # Studying Hohmann transfers # + import numpy as np import matplotlib.pyplot as plt plt.ion() from astropy import units as u from poliastro.util import norm from poliastro.bodies import Earth from poliastro.twobody import Orbit from poliastro.maneuver import Maneuver # - Earth.k ss_i = Orbit.circular(Earth, alt=800 * u.km) ss_i r_i = ss_i.a.to(u.km) r_i v_i_vec = ss_i.v.to(u.km / u.s) v_i = norm(v_i_vec) v_i N = 1000 dv_a_vector = np.zeros(N) * u.km / u.s dv_b_vector = dv_a_vector.copy() r_f_vector = r_i * np.linspace(1, 100, num=N) for ii, r_f in enumerate(r_f_vector): man = Maneuver.hohmann(ss_i, r_f) (_, dv_a), (_, dv_b) = man.impulses dv_a_vector[ii] = norm(dv_a) dv_b_vector[ii] = norm(dv_b) # + fig, ax = plt.subplots(figsize=(7, 7)) ax.plot((r_f_vector / r_i).value, (dv_a_vector / v_i).value, label="First impulse") ax.plot((r_f_vector / r_i).value, (dv_b_vector / v_i).value, label="Second impulse") ax.plot((r_f_vector / r_i).value, ((dv_a_vector + dv_b_vector) / v_i).value, label="Total cost") ax.plot((r_f_vector / r_i).value, np.full(N, np.sqrt(2) - 1), 'k--') ax.plot((r_f_vector / r_i).value, (1 / np.sqrt(r_f_vector / r_i)).value, 'k--') ax.set_ylim(0, 0.7) ax.set_xlabel("$R$") ax.set_ylabel("$\Delta v_a / v_i$") plt.legend() fig.savefig("hohmann.png")
docs/source/examples/Studying Hohmann transfers.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 # --- # # Hands-on Introduction to Python And Machine Learning # Instructor: <NAME> # # (Readers are assumed to have a little bit programming background.) # # ### 2. Similarity-based algorithms # When dealing with data, we often need to define how much a data point is similar to other data points. If we know how similar or dissimilar any two data points are, we can then divide the data points into groups where the elements in the same group are similar. and thus achieve machine learning. *Classification* and *clustering* are two groups of similarity-based machine learning algorithms. How good the classification or clustering result is almost always depends on how suitable the similarity metric is. # # Classification algorithms are supervised learning machine learning algorithms, whereas clustering algorithms are unsupervised. # # Example of classification algorithms: # - k-nearest neighbours # # Examples of clustering algorithms: # - k-means # - Expectation-maximization # #### K-nearest neighbours # K-nearest neighbours is a supervised classification algorithm. Its procedures: # 1. Build a database of samples whose classes are known (the samples have been labelled) # 2. If we want to classify an unseen piece of data $d$, we need to: # 1. Find the $k$ most similar samples in the database, which are known as the $k$-nearest neighbours, and then # 2. Find the majority class of the $k$ nearest neighbours, and assign it to $d$ # Let write our simplest implementation of k-nearest neighbours in Python from scratch! # + # Importing libraries import numpy as np def euclideanDistance(data1, data2): """ calculate sum of the squares of each column """ total_distance = np.sum(np.square(data1[1] - data2[1])) eucliden = np.sqrt(total_distance) return eucliden def kNearestNeighboursPredict(trainingData, k, testData): """ Inputs: trainingData is an array of tuples k specifies the number of nearest neighbours testData is an array of tuples a trainingData should be a tuple (class, numpy array of features) so trainingData is [(class 1, numpy array of features), (class 2, numpy array of features), ...] the format of testData is the same as trainingData Calculates the class of the given data using Eucliden distance as the similarity metric. """ predicted_classes = [] for d in testData: # calculate the Euclidean distance distances = [(tr, euclideanDistance(d, tr)) for tr in trainingData] # sorted_distances = sorted(distances, key=lambda tup: tup[1])[:k] kNeighbours = [d[0] for d in sorted_distances] classes = {} for n in kNeighbours: if n[0] not in classes: classes[n[0]] = 1 else: classes[n[0]] += 1 classes = sorted(classes.items(), key=lambda entry: entry[1]) predicted_classes.append(classes[0][0]) return predicted_classes trainingData = [('A', np.array([1])), ('A', np.array([2])), ('B', np.array([11])), ('B', np.array([12]))] testData = [('X', np.array([13])), ('X', np.array([4]))] predictedData = kNearestNeighboursPredict(trainingData, 2, testData) print(predictedData) # - # Using scikit-learn is more convenient... # + # given 'HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed', can we figure out the Type of the Pokemon? import matplotlib.pyplot as plt import numpy as np from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import mean_squared_error, r2_score import pandas as pd # Load the dataset pokemons = pd.read_csv("pokemon.csv") print(pokemons['Type 1'].unique()) pokemons = pokemons.sample(frac=1) # .sample(frac=1) randomize the data, and select 100% from the randomized label_column = ['Type 1'] features_columns = ['HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed'] pokemons_features = pokemons[features_columns] pokemons_label = pokemons[label_column] # normalise every columns in pokemons_features # pokemons_features = pokemons_features.apply(lambda x: (x - x.min())/(x.max() - x.min())) # .values convert the datastructure from pandas's dataframe into numpy's array # Split the data into training/test sets last_index = -int(0.20*len(pokemons_features)) pokemons_features_train = pokemons_features[:last_index].values pokemons_features_test = pokemons_features[last_index:].values last_index = -int(0.20*len(pokemons_label)) pokemons_label_train = pokemons_label[:last_index].values.flatten() # the expected labels pokemons_label_test = pokemons_label[last_index:].values.flatten() # the expected labels # Create a k-nearest neighbours classifier neigh = KNeighborsClassifier(n_neighbors=20) # Train the model using the training sets neigh.fit(pokemons_features_train, pokemons_label_train) # Make predictions using the testing set pokemons_label_pred = neigh.predict(pokemons_features_test) # the actual labels correct = 0.0 for i in range(0, len(pokemons_label_test)): print('expected {} VS. actual {}'.format(pokemons_label_test[i], pokemons_label_pred[i])) if pokemons_label_pred[i] == pokemons_label_test[i]: correct = correct+1 print('Accuracy: {}%'.format(correct/len(pokemons_label_test) * 100)) # What if we change k, and/or select a different set of features, and/or limit the number of Type? # - # You may have already noticed that the choice of the parameters such as $k$ and the features greatly affect the performance of k-nearest neighbours. Indeed, the parameters of the model are as important as the (dis)similarity metric in machine learning algorithms. Selecting the most suitable parameters is a big research topic per se. # #### K-means # K-means is an unsupervised clustering algorithm. It is different from k-nearest neighours, but k-nearest neighours is sometimes applied to implement k-means (as shown below). The procedures of k-means are listed below: # 1. Guess $k$ cluster centres # 2. For each data point, assign it to one of the closest clusters. Here a similarity metric defining the distance betweeen a data point and a cluster centre is required. # 3. Update the centres of the clusters # 4. Repeat step 2-3 until the centres of the clusters do not change # + import numpy as np import matplotlib.pyplot as plt # ---------------------------- the same functions defined for k-nearest neighbours BEGIN def euclideanDistance(data1, data2): """ calculate sum of the squares of each column """ total_distance = np.sum(np.square(data1[1] - data2[1])) eucliden = np.sqrt(total_distance) return eucliden def kNearestNeighboursPredict(centres, k, testData): """ Inputs: centres is an array of tuples k specifies the number of nearest neighbours testData is an array of tuples a centres should be a tuple (class, numpy array of features) so centres is [(class 1, numpy array of features), (class 2, numpy array of features), ...] the format of testData is the same as centres Calculates the class of the given data using Eucliden distance as the similarity metric. """ predicted_classes = [] for d in testData: # calculate the Euclidean distance distances = [(tr, euclideanDistance(d, tr)) for tr in centres] # sorted_distances = sorted(distances, key=lambda tup: tup[1])[:k] kNeighbours = [d[0] for d in sorted_distances] classes = {} for n in kNeighbours: if n[0] not in classes: classes[n[0]] = 1 else: classes[n[0]] += 1 classes = sorted(classes.items(), key=lambda entry: entry[1]) predicted_classes.append(classes[0][0]) return predicted_classes # ---------------------------- the same functions defined for k-nearest neighbours END def kmeansFit(data, k): # generate k random centres rand_int = np.random.randint(-100, 100, 1)[0] centre_values = [-rand_int, rand_int] # food for thought, why do we pick the initial centre values in this way? # how about randomly generating them, say, from the range [-100, 100] instead? print('initial random centre values: {}'.format(centre_values)) # centres is an array in the form [ (classA, [numpy array of features]), (classB, [numpy array of features]), ...] centres = [] for i, c in enumerate(centre_values): centres.append((i, np.array([c]))) prev_centres = None classes = {} while True: # assign a class to every data assigned_classes = kNearestNeighboursPredict(centres, 1, data) print(assigned_classes) # store the class info as a dictionary in the following format: # { class A: array of data, class B: array of data, ...} for i in range(0, k): classes[i] = [] for i, c in enumerate(assigned_classes): data[i] = (c, data[i][1]) classes[assigned_classes[i]].append(data[i]) # update the centres of every cluster for c, elements in classes.items(): sum = np.zeros((len(data[0][1]))) for e in elements: sum += e[1] if (len(elements) > 0): mean = sum / len(elements) centres[c] = (c, mean) for c in centres: print('centre: {} has mean {}'.format(c[0], c[1])) # check if the centres are updated hasGreatlyChanged = False if prev_centres: for i, c in enumerate(centres): diff = np.sum(np.absolute(prev_centres[i][1]-centres[i][1])) print('prev: {} cur : {}', prev_centres[i][1], centres[i][1]) if diff > 0.5: hasGreatlyChanged = True break else: hasGreatlyChanged = True if not hasGreatlyChanged: break prev_centres = centres[0:] # why do we have to do this??? # can we simply do: prev_centres = centres ??? yield classes # we haven't learnt using yield yet. Can you guess what it is used for? #return classes # let's test our implementation # random data set 1 that consists of 10 integers in the range [-2, 4] data_1 = np.random.randint(-1, 5, 10) # random data set 2 that consists of 10 integers in the range [9, 15] data_2 = np.random.randint(9, 16, 10) # shuffle the concatenation of data_1 and data2 data_array = np.concatenate((data_1, data_2)) np.random.shuffle(data_array) # just assign a dummy class for each data (for format compatibility) data_array = [(0, np.array([d])) for i,d in enumerate(data_array)] iterations=0 for predictedClasses in kmeansFit(data_array, 2): print('------------------------ Iteration: {}'.format(iterations)) #print(predictedClasses) plt.figure(figsize=(10,8), dpi=100) for c,dataPoints in predictedClasses.items(): if c == 0: colour = 'red' elif c == 1: colour = 'blue' x = [x[1] for x in dataPoints] y = np.zeros(len(x)) plt.title('Clustering result at iteration: '+ str(iterations)) plt.scatter(x, y, color=colour) iterations = iterations +1 plt.show() # - # k-means using Euclidean distance as the similarity metric is defined in mathematics notations as follows: # # Given $n$ data points: $\{d_1, d_2, d_3, ..., d_n\}$, assign every data point $d_i$ to a cluster $C_i$ out of $k$ clusters such that $\sum_1^k{\sum_{d_i \in C_j}{||d_i - \mu _j||_2}}$ is minimum, where $\mu _j$ is the mean of all data points in the cluster $C_j$. # In this example, some important and valuable knowledge from human are used to train the model: # 1. An educated guess of the initial centre values # 2. An educated guess of the number of clusters # 3. An educated guess of the stopping conditions # We can see from the examples of k-nearest neighbours (supvervised classification) and k-means (unsupervised clustering) that human knowledge is required in some sense, either explicit (through data labelling) or implicit (guesses of the parameters), to train the machine learning algorithms no matter they are supervised or unsupervised. Therefore the domain knowledge of a problem is actually very important. # # That implies some people probably still have jobs even if artificial intelligence has dominated the universe! (seems legit...) # Using k-means in scikit-learn: # + # given 'HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed', can we figure out the Type of the Pokemon? import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans from sklearn.metrics import mean_squared_error, r2_score import pandas as pd # Load the dataset pokemons = pd.read_csv("pokemon.csv") print(pokemons['Type 1'].unique()) pokemons = pokemons.sample(frac=1) # .sample(frac=1) randomize the data, and select 100% from the randomized label_column = ['Type 1'] features_columns = ['HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed'] pokemons_features = pokemons[features_columns] pokemons_label = pokemons[label_column] # normalise every columns in pokemons_features # pokemons_features = pokemons_features.apply(lambda x: (x - x.min())/(x.max() - x.min())) # .values convert the datastructure from pandas's dataframe into numpy's array # Split the data into training/test sets last_index = -int(0.20*len(pokemons_features)) pokemons_features_train = pokemons_features[:last_index].values pokemons_features_test = pokemons_features[last_index:].values last_index = -int(0.20*len(pokemons_label)) pokemons_label_train = pokemons_label[:last_index].values.flatten() # the expected labels pokemons_label_test = pokemons_label[last_index:].values.flatten() # the expected labels kmeans = KMeans(n_clusters=18, random_state=0).fit(pokemons_features_train) # Make predictions using the testing set pokemons_label_pred = kmeans.predict(pokemons_features_test) # the actual labels correct = 0.0 for i in range(0, len(pokemons_label_pred)): print('Pokemon: {} actual type: {}'.format(pokemons.loc[i, 'Name'], pokemons_label_pred[i])) # - # #### Expectation-Maximization # # In k-means (clustering), we use a technique in which the centres are guessed, the data points are assigned the guessed centres, then the centres are updated according to the information that has been gathered thus far, and the procedure repeats until the result *converges*. This algorithm is actually a way of making educated and systematic trial-and-error guesses. There is a highly similar algorithm known as Expectation-Maximization. # # Expectation-Maximization is usually said to the the "soft" version of k-means. That means, instead assigning a data point to one and only one cluster, *a data point is assigned to all clusters with probability densities*; instead of characterising a cluster by its mean, a cluster is to be characterised by a *probability density function* or *mixtures of probability density functions*. The suitability that a data point belongs to a cluster depends on how it fits with the probability density functions of the cluster. # # We usually assume the probability density function is of [Gaussian](https://en.wikipedia.org/wiki/Normal_distribution). # # The two main steps of expectation-maximization: # 1. Expectation, the E step: for each data point $d_i$, compute the probability density of it belonging to each of the clusters give the current model $m$ # 2. Maximization, the M step: update the model $m$ such that every data point can be assigned to a cluster with the greatest probability density (in other words, to make clusters further away from each other) # A program is worth a thousand words. Here we go: # + import numpy as np from scipy import stats import matplotlib.pyplot as plt def estimate_mean(data, weight): return np.sum(data * weight) / np.sum(weight) def estimate_std(data, weight, mean): variance = np.sum(weight * (data - mean)**2) / np.sum(weight) return np.sqrt(variance) # --------------------------------------------------- initialization np.random.seed(110) # for reproducible random results # set parameters red_mean = 3 red_std = 0.8 blue_mean = 7 blue_std = 2 # draw 20 samples from normal distributions with red/blue parameters red = np.random.normal(red_mean, red_std, size=20) blue = np.random.normal(blue_mean, blue_std, size=20) both_colours = np.sort(np.concatenate((red, blue))) # combine the points together # From now on, assume we don't know how the data points were generate. We also don't know which cluster a data belongs to. # ------------ initial guess # estimates for the mean red_mean_guess = 1.1 blue_mean_guess = 9 # estimates for the standard deviation red_std_guess = 2 blue_std_guess = 1.7 # ------------ expectation & maximization # graph g=[i for i in range(-10, 20)] for i in range(0, 10): # just for plotting plt.figure(figsize=(10, 6), dpi=100) plt.title("Red VS. Blue (Gaussian distribution) Take: " + str(i)) red_norm = stats.norm(red_mean_guess, red_std_guess).pdf(g) blue_norm = stats.norm(blue_mean_guess, blue_std_guess).pdf(g) plt.scatter(g, red_norm) plt.scatter(g, blue_norm) plt.plot(g, red_norm, c='red') plt.plot(g, blue_norm, c='blue') # how likely is a data point belong to the clusters? likelihood_of_red = stats.norm(red_mean_guess, red_std_guess).pdf(both_colours) likelihood_of_blue = stats.norm(blue_mean_guess, blue_std_guess).pdf(both_colours) # new estimates of standard deviation likelihood_total = likelihood_of_red + likelihood_of_blue red_weight = likelihood_of_red / likelihood_total blue_weight = likelihood_of_blue / likelihood_total red_std_guess = estimate_std(both_colours, red_weight, red_mean_guess) blue_std_guess = estimate_std(both_colours, blue_weight, blue_mean_guess) # new estimates of mean red_mean_guess = estimate_mean(both_colours, red_weight) blue_mean_guess = estimate_mean(both_colours, blue_weight) plt.show() # - # ##### Do you agree? # # Both k-means and expectation-maximization can acutally be used for semi-supervised machine learning in which only a portion of the data is labelled. # ** Exercise **: # - Try to use scikit-learn's k-nearest neighbour to model the following classification problem: data = [0, 1] classes = [0, 1] # classes[i] is the class of the data point data[i] # ** Exercise **: # - Try to use scikit-learn's k-nearest neighbour to model the following classification problem: data = [[0, 0], [0,1], [1,0], [1,1]] classes = [0, 0, 1, 1] # classes[i] is the class of the data point data[i] # ** Exercise **: # - Try to use scikit-learn's k-nearest neighbour to model the following classification problem: data = [[0, 0], [0,1], [1,0], [1,1]] classes = [0, 1, 2, 3] # classes[i] is the class of the data point data[i] # ** Exercise **: # - Try to use scikit-learn's k-nearest neighbour to model the following classification problem: data = ['a', 'e', 'i', 'o', 'u', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] classes = [1, 1, 1,1, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0,0, 0, 0, 0, 0,0, 0, 0, 0, 0,0] # classes[i] is the class of the data point data[i]
Machine Learning Algos - Similarity-based - Hands-on Introduction to Python And Machine Learning.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 # --- # # Settings # --- # # ### Caution 🚧 # # 아래 내용을 수정하면 프로그램이 정상적으로 동작하지 않을 수 있습니다. # + from os.path import join url = "https://gist.githubusercontent.com/pparkddo/b6643ed4cee951e445f0f48262c6eedc/raw/e500e30ab217c6646b881c7ba11efc2936e2f3f7/" # - import numpy as np import pandas as pd # # Problems # --- # # 각 문제를 풀기전 입력값이 있는 셀을 꼭! 실행시켜주셔야 합니다. # 1. `DataFrame` `df` 의 분단위 답변 횟수(`answer` 의 개수)를 구하고자 한다. # 다만 답안에는 2021-3-10 0:00 분부터 2021-3-10 23:59 분까지 모두 포함해야 한다. # (참고 : `timetstamp` 열은 2021-3-10 9:00 ~ 2021-3-10 17:58 까지의 데이터가 있다.) # # - Hint : date_range # + # 문제의 입력값입니다. 수정하면 정답이 달라질 수 있습니다. df = pd.read_csv(join(url, "problems_records.csv"), parse_dates=["timestamp"]) # + # 답안 예시입니다. 주어진 'df' 를 조작하여 아래와 같이 만들면 됩니다. # 데이터가 없는 시간(분)에는 answer 가 0 으로 나타나지만 # 09:00 등 답변이 있었던 시간(분)에는 해당 시간에 있었던 답변의 횟수가 나타납니다. # 자세한 출력값은 아래 데이터를 참고하세요. pd.read_csv(join(url, "problems_minutes.csv")) # + # 아래에 정답코드를 작성해주세요 # - # 2. `DataFrame` `information` 은 각 학생ID(`student_id`)별 부서(`department`), 나이(`age`), 좋아하는 숫자(`favorite_number`) 데이터이다. # `information` 에서 `favorite_number` 가 3으로 나누어 떨어지는(나머지가 0인) 학생들만 고르고, # `records` 에서 위 조건에 해당하는 학생들의 답변 데이터의 개수를 시간별로 합산하여 나타내시오. # # - Hint : resample # + # 문제의 입력값입니다. 수정하면 정답이 달라질 수 있습니다. records = pd.read_csv(join(url, "problems_records.csv"), parse_dates=["timestamp"]) information = pd.read_csv(join(url, "problems_information.csv")) # + # 답안 예시입니다. 주어진 records, information 을 조작하여 아래와 같이 만들면 됩니다. pd.read_csv(join(url, "problems_resampled.csv")).set_index("timestamp") # + # 아래에 정답코드를 작성해주세요 # - # 3. `DataFrame` `df` 에서 각 학생ID(`student_id`)별 가장 빠른 답변시각(`timestamp`) 에 해당하는 행을 구하세요. # 만약 가장 빠른 답변시각이 한 학생ID별로 두개 이상일 경우에는 그 중 `answer` 값이 가장 작은 것을 고르세요. # # - Hint : groupby() first # + # 문제의 입력값입니다. 수정하면 정답이 달라질 수 있습니다. df = pd.read_csv(join(url, "problems_records.csv"), parse_dates=["timestamp"]) # + # 답안 예시입니다. 주어진 df 를 조작하여 아래와 같이 만들면 됩니다. pd.read_csv(join(url, "problems_first.csv")).set_index("student_id") # + # 아래에 정답코드를 작성해주세요
problems.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 class Person(object): def __init__(self, name='', year=0, salary=0): self.name = name self.year = year self.salary = salary person1 = Person('john', 2017, 100) person2 = Person('smith', 2016, 200) person3 = Person('roger', 2016, 500) person_list = [person1, person2, person3] df = pd.DataFrame([x.__dict__ for x in person_list]) # - df=df.append([person3.__dict__]) print(df) df df.append([{'q':'q','3':5}], sort=False) df.iloc[0:0]
notebooks/play/pandas_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 # --- # # Activity 3: Exploring Bitcoin Dataset # We explore the Bitcoin dataset in this Jupyter Notebook. First, we start by importing the required libraries. import numpy as np import pandas as pd import matplotlib.pyplot as plt # #### Magic Commands # Magic commands (those that start with `%`) are commands that modify a configuration of Jupyter Notebooks. A number of magic commands are available by default (see list [here](http://ipython.readthedocs.io/en/stable/interactive/magics.html))--and many more can be added with extensions. The magic command added in this section allows `matplotlib` to display our plots directly on the browser instead of having to save them on a local file. # %matplotlib inline # ### Introduction # We will also import our custom set of normalization functions. import normalizations # Let's load the dataset as a pandas `DataFrame`. This will make it easy to compute basic properties from the dataset and to clean any irregularities. bitcoin = pd.read_csv('data/bitcoin_dataset.csv', date_parser=['date']) bitcoin.head() # Our dataset contains 7 variables (i.e. columns). Here's what each one of them represents: # # * `date`: date of the observation. # * `open`: open value of a single Bitcoin coin. # * `high`: highest value achieved during a given day period. # * `low`: lowest value achieved during a given day period. # * `close`: value at the close of the transaction day. # * `volume`: what is the total volume of Bitcoin that was exchanged during that day. # * `iso_week`: week number of a given year. # # All values are in USD. # ### Exploration # We will now explore the dataset timeseries to understand its patterns. # # Let's first explore two variables: close price and volume. # + bitcoin.set_index('date')['close'].plot(linewidth=2, figsize=(14, 4), color='#d35400') #plt.plot(bitcoin['date'], bitcoin['close']) # + # # Make a similar plot for the volume variable here. # How different is the volume data compared to # the closing prices every day? # # - # Now let's explore the range from 2017 to 2018. These are the years where the prices of bitcoin were high initially and then started declining and then gained back again! bitcoin[(bitcoin['date'] >= '2017-01-01') & (bitcoin['date'] <= '2018-12-31') ].set_index('date')['close'].plot( linewidth=2, figsize=(14, 4), color='#d35400') # + # # Again, make a similar plot for the volume variable. # # - # ### Preparing Dataset for Model # Neural networks typically work with either [matrices](https://en.wikipedia.org/wiki/Matrix_(mathematics)) or [tensors](https://en.wikipedia.org/wiki/Tensor). Our data needs to fit that structure before it can be used by either `keras` (or `tensorflow`). # # Also, it is common practice to normalize data before using it to train a neural network. We will be using a normalization technique the evaluates each observation into a range between 0 and 1 in relation to the first observation in each week. bitcoin.head() # First, let's remove data from older periods. We will keep only data from 2016 until the latest observation of 2020. Older observations may be useful to understand current prices. However, Bitcoin has gained so much popularity in recent years that including older data would require a more laborious treatment. We will leave that for a future exploration. bitcoin_recent = bitcoin[bitcoin['date'] >= '2016-01-04'] # Let's keep only the close and volume variables. We can use the other variables in another time. bitcoin_recent = bitcoin_recent[['date', 'iso_week', 'close', 'volume']] # Now, let's normalize our data for both the `close` and `volume` variables. bitcoin_recent['close_point_relative_normalization'] = bitcoin_recent.groupby('iso_week')['close'].apply( lambda x: normalizations.point_relative_normalization(x)) # + # # Now, apply the same normalization on the volume variable. # Name that variable using the same convention # from the previous example. Use the name: # # `volume_point_relative_normalization` # # - # After the normalization procedure, our variables `close` and `volume` are now relative to the first observation of every week. We will be using these variables -- `close_point_relative_normalization` and `volume_point_relative_normalization`, respectivelly -- to train our LSTM model. bitcoin_recent.set_index('date')['close_point_relative_normalization'].plot( linewidth=2, figsize=(14, 4), color='#d35400') # + # # Now, plot he volume variable (`volume_point_relative_normalization`) # in the same way as the plot above. # # - # ### Training and Test Sets # Let's divide the dataset into a training and a test set. In this case, we will use 80% of the dataset to train our LSTM model and 20% to evaluate its performance. # # Given that the data is continuous, we use the last 20% of available weeks as a test set and the first 80% as a training set. boundary = int(0.9 * bitcoin_recent['iso_week'].nunique()) train_set_weeks = bitcoin_recent['iso_week'].unique()[0:boundary] test_set_weeks = bitcoin_recent[~bitcoin_recent['iso_week'].isin(train_set_weeks)]['iso_week'].unique() train_set_weeks test_set_weeks # Now, let's create the separate datasets for each operation. train_dataset = bitcoin_recent[bitcoin_recent['iso_week'].isin(train_set_weeks)] # + # # Perform the same operation as above, but use the # `test_set_weeks` list to create the variable `test_dataset`. # # - # ### Storing Output # Before closing this notebook, let's store the output of this exercise on disk to make sure it is easier to use this data as input to our neural network. bitcoin_recent.to_csv('data/bitcoin_recent.csv', index=False) train_dataset.to_csv('data/train_dataset.csv', index=False) # + # # Perform the same operation as above to save the test file to disk as well # # - # ### Summary # In this section, we explored the Bitcoin dataset. We learned that during year of 2017 the prices of Bitcoin skyrocketed and afterwards it started falling. It recovered back in 2018 to some extent but it is yet to reach what it reached in 2017. This phenomenon takes a long time to take place—and may be influenced by a number of external factors that this data alone doesn't explain (for instance, the emergence of other cryptocurrencies, the ban of cryptocurrencies in some markets). # # Can we predict the price of Bitcoin in the future? What will it be 30 days from now? We will be building a deep learning model to explore that question in our next section.
old/Chapter02/activity_3/Activity_3_Exploring_Bitcoin_Dataset.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 # --- # ### Initialize the environment import theano import numpy as np import matplotlib.pyplot as plt # %matplotlib inline src_dir='../src' # source directory run_dir='../MDBN_run' # directory with the results of previous runs data_dir='../data' # directory with the data files import sys sys.path.insert(0, src_dir) import MDBN import AMLsm2 # ### Load the experiment results # + date_time='2016-12-30_1830' # specify the date and time of the run in the format YYYY-MM-DD_HHMM runfile='Run_'+date_time+'/Exp_'+date_time+'_run_0.npz' # location of the experiment results me_DBN, ge_DBN, sm_DBN, dm_DBN, top_DBN = AMLsm2.load_network(runfile,run_dir) # - # ### Visualize the results graphically datafiles = AMLsm2.prepare_AML_TCGA_datafiles(data_dir) ME_output, _ = me_DBN.MLP_output_from_datafile(datafiles['ME'], datadir=data_dir) GE_output, _ = ge_DBN.MLP_output_from_datafile(datafiles['GE'], datadir=data_dir) SM_output, _ = sm_DBN.MLP_output_from_datafile(datafiles['SM'], datadir=data_dir) joint_layer = np.concatenate([ME_output, GE_output, SM_output],axis=1) plt.imshow(joint_layer, cmap='gray',interpolation='none') plt.axis('tight') top_output = top_DBN.get_output(theano.shared(joint_layer,borrow=True)) plt.imshow((top_output>0.8)*np.ones_like(top_output)-(top_output<0.2)*np.ones_like(top_output),interpolation='none',extent=[0,3,385,0]) plt.colorbar() plt.axis('tight') plt.xticks(np.arange(0.5,3.5,1),('0','1','2')) plt.imshow(top_output, interpolation='none',extent=[0,3,385,0]) plt.axis('tight') plt.colorbar() plt.xticks(np.arange(0.5,3.5,1),('0','1','2')) plt.hist(top_output) code = (top_output[:,0:3] > 0.5) * np.ones_like(top_output[:,0:3]) from utils import find_unique_classes U = find_unique_classes(code) cl = U[0] cl max_cl = np.max(cl) plt.hist(cl,bins=np.arange(-0.5,max_cl + 1.5,1)) # Check Survival curves for the different classes # =============================================== import csv id=[] with open('../data/'+datafiles['ME']) as f: my_csv = csv.reader(f,delimiter='\t') id = my_csv.next() stat={} with open('../data/AML/AML_clinical_data2.csv') as f: reader = csv.reader(f, delimiter=',') for row in reader: patient_id=row[0] stat[patient_id]=(row[4],row[7],row[6]) import re time_list = [] event_list = [] group_list = [] print('The following case IDs were not found in clinical data') for index, key in enumerate(id[1:]): m = re.match('TCGA-\w+-\d+', key) patient_id = m.group(0) if patient_id in stat: patient_stat = stat[patient_id] add_group = True try: time_list.append(float(patient_stat[2])) event_list.append(1) except ValueError: try: time_list.append(float(patient_stat[1])) event_list.append(0) except ValueError: print('No data for %s' % patient_id) add_group = False if add_group: group_list.append(cl[index]) else: print(patient_id) from lifelines import KaplanMeierFitter kmf = KaplanMeierFitter() kmf.fit(time_list,event_observed=event_list) kmf.plot() T=np.array(time_list) E=np.array(event_list) ix = (np.array(group_list) == 0) kmf.fit(T[ix], E[ix], label='group 0') ax=kmf.plot() for i in range(1,5): ix=(np.array(group_list)==i) kmf.fit(T[ix], E[ix], label='group %d' % i) kmf.plot(ax=ax)
notebooks/Display Output Layers (Run 2016-12-30_1830)-AML.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 # --- # # MAC119 / UFRJ - Segunda Prova (08/06/16) # ### Turma B # **Questão 1.** (1.5 ponto) Determine o valor da constante A que torna a função dada $f(x)$ contínua para qualquer valor de x, justificando todos os passos. # (0.5 ponto) Esboce o gráfico da função resultante. # # $$f(x) = \begin{cases} \dfrac{x^2 - 16}{x + 4}, & \mbox{se } x\mbox{ $< 4$} \\ Ax^2 + x - 36, & \mbox{se } x\mbox{ $\geq 4$} \end{cases}$$ # # ### **Solução** # # Primeiramente, identificamos os possíveis pontos de descontinuidade da função: # 1. Em $x = -4$ a função será sempre descontínua, pois a função não está definida neste ponto. # 2. Em $x = 4$, a continuidade da função dependará de valor de $A$. # 3. Para os demais valores de $x$, a função será sempre contínua. # # Logo, não é possível encontrar um valor de $A$ que torne a função contínua para todo $x$. Porém, podemos determinar o valor de $A$ que torna a função contínua em $x = 4$. Para isso, temos que: # $$\lim\limits_{x\rightarrow 4} f(x) = f(4)$$ # # Para que esse limite exista, os limites laterais têm que ser iguais: $\lim\limits_{x\rightarrow 4^+} f(x) = \lim\limits_{x\rightarrow 4^-} f(x)$. # $\lim\limits_{x\rightarrow 4^+} f(x) = \lim\limits_{x\rightarrow 4^+} (Ax^2 + x - 36) = 16A - 32$ # $\lim\limits_{x\rightarrow 4^-} f(x) = \lim\limits_{x\rightarrow 4^-} \dfrac{x^2 - 16}{x + 4} = \lim\limits_{x\rightarrow 4^-} \dfrac{(x - 4)(x + 4)}{x + 4} = \lim\limits_{x\rightarrow 4^-} x - 4 = 0$ # # Logo: # # $16A - 32 = 0 \rightarrow \fbox{A = 2}$. # # Portanto, para $A = 2$, $\lim\limits_{x\rightarrow 4} f(x) = f(4)$. # # O gráfico da função fica: # # ![MAC119_P2B_1b](https://drive.google.com/uc?id=0B2hurzTPk6MGUjZLMlVLX0I4SW8) # **Questão 2.** (3 pontos) Determine a derivada das seguintes funções: # # (a) $f(x) = (3x^5 + 7)(x^2 + 2)$ # # (b) $h(t) = \dfrac{5t - 1}{t^2 - 4}$ # # (c) $g(x) = (3x^3 + x - 3)^{11}$ # # (d) $f(x) = x^3\,e^{x}$ # # (e) $y = x^3\,\ln{x}$ # # (f) $f(x) = \ln{\left(\dfrac{3}{x^2 + 1}\right)}$ # # ### **Solução** # # **(a)** Utilizando a regra do produto e simplificando: # $f'(x) = (3x^5 + 7)(2x) + (x^2 + 2)(15x^4) = 6x^6 + 14x + 15x^6 + 30x^4$ # $f'(x) = 21x^6 + 30x^4 + 14x = x\,(21x^5 + 30x^3 + 14)$ # $\fbox{$f'(x) = x\,(21x^5 + 30x^3 + 14)$}$ # # **(b)** Utilizando a regra do quociente e simplificando: # $h'(t) = \dfrac{(t^2 - 4)(5) - (5t - 1)(2t)}{(t^2 - 4)^2}$ # $h'(t) = \dfrac{5t^2 - 20 - 10t^2 + 2t}{(t^2 - 4)^2}$ # $\fbox{$h'(t) = \dfrac{-5t^2 + 2t - 20}{(t^2 - 4)^2}$}$ # # **(c)** Utilizando a regra da cadeia e simplificando: # # $g'(x) = 11\,(3x^3 + x - 3)^{10}(9x^2 + 1) = 11\,(9x^2 + 1)(3x^3 + x - 3)^{10}$ # $\fbox{$g'(x) = 11\,(9x^2 + 1)(3x^3 + x - 3)^{10}$}$ # # **(d)** Utilizando a regra do produto e simplificando: # $f'(x) = x^3\,e^{x} + e^{x}\,3x^2 = x^2\,e^{x}(x + 3)$ # $\fbox{$f'(x) = x^2\,e^{x}(x + 3)$}$ # # **(e)** Utilizando a regra do produto e simplificando: # $y' = x^3\,\dfrac{1}{x} + \ln{x}\,3x^2 = x^2 + 3x^2\,\ln{x}$ # $\fbox{$y' = x^2(1 + 3\ln{x})$}$ # # **(f)** Utilizando a regra da cadeia e simplificando: # # $f'(x) = \dfrac{1}{\dfrac{3}{x^2 + 1}} \cdot \left(\dfrac{3}{x^2 + 1}\right)' = \dfrac{x^2 + 1}{3} \cdot \dfrac{-3\,(2x)}{(x^2 + 1)^2}$ # # $\fbox{$f'(x) = -\dfrac{2x}{x^2 + 1}$}$ # **Questão 3.** O gerente de uma fábrica de eletrodomésticos observa que o número de cafeteiras vendidas por mês por $p$ reais cada uma pode ser modelado pela função: # $$N(p) = \dfrac{8000}{p}$$ # O gerente estima que daqui a $t$ meses o preço de uma cafeteira será $p(t) = 0.06t^{3/2} + 22.5$ reais. # # (a) (1.5 ponto) A que taxa a demanda mensal de cafeteiras $N(p)$ estará variando daqui a 25 meses? # (b) (0.5 ponto) Interprete o resultado. # # ### **Solução** # # **(a)** A taxa é dada pela regra da cadeia: # # $\dfrac{dN}{dt} = \dfrac{dN}{dp} \cdot \dfrac{dp}{dt}$ # # As derivadas dos termos à direita da igualdade anterior são: # $\dfrac{dN}{dp} = -\dfrac{8000}{p^2}$ e $\dfrac{dp}{dt} = 0.09\,t^{1/2}$ # # Logo: # $\dfrac{dN}{dt} = -\dfrac{8000}{p^2}\,0.09\,t^{1/2} = -\dfrac{720\,\sqrt{t}}{p^2}$ # # No enunciado é pedido a taxa para $t = 25$ meses. Para encontramos a população correspondente, basta substituir o tempo $t = 25$ na expressão de $p(t)$: # $p(25) = 0.06(25^{3/2}) + 22.5 = 30$ # # Logo, substituindo os valores de $t = 25$ e $p = 30$ na expressão da derivada: # # $\dfrac{dN}{dt}\bigg|\,^{t = 25}_{p = 30} = -\dfrac{720\,\sqrt{(25)}}{(30)^2} = -4$ # $\fbox{$\dfrac{dN}{dt}\bigg|\,^{t = 25}_{p = 30} = -4$ cafeteiras/mês}$ # # **(b)** # # O resultado anterior indica que daqui a 25 meses a demanda mensal de cafeteiras estará diminuindo à taxa de $4$ cafeteiras/mês. # **Questão 4.** (3 pontos) Use derivação implícita para determinar a inclinação da reta tangente à curva dada no ponto especificado: # # (a) $xy^3 = 6;\,(6, 1)$ # # (b) $1 - xy^4 = 3x^2 + 6y;\,(0, 1/6)$ # # (c) $3x^2 + 2y^3 = x^2y;\,(3, -3)$ # # (d) $3x - y^2 = 2e^{x} + 4y;\,(0, 1)$ # # ### **Solução** # # **(a)** Derivado implicitamente: # # $\dfrac{d}{dx}(xy^3) = \dfrac{d}{dx}(6)$ # $y^3 + 3xy^2\dfrac{dy}{dx} = 0$ # $\dfrac{dy}{dx} = -\dfrac{y}{3x}$ # # Em $(6, 1)$: # $\dfrac{dy}{dx} = -\dfrac{1}{3(6)} = -\dfrac{1}{18}$ # # Portanto: # $\fbox{$\dfrac{dy}{dx}\bigg|_{(6, 1)} = -\dfrac{1}{18}$}$ # # **(b)** Derivado implicitamente: # # $\dfrac{dy}{dx} = -\dfrac{6x + y^4}{4xy^3 + 6}$ # # Portanto: # $\fbox{$\dfrac{dy}{dx}\bigg|_{(0, 1/6)} = -\dfrac{1}{7776}$}$ # # **(c)** Derivado implicitamente: # # $\dfrac{dy}{dx} = -\dfrac{2xy - 6x}{x^2 - 6y^2}$ # # Portanto: # $\fbox{$\dfrac{dy}{dx}\bigg|_{(3, -3)} = -\dfrac{4}{5}$}$ # # **(d)** Derivado implicitamente: # # $\dfrac{dy}{dx} = \dfrac{3 - 2e^x}{2y + 4}$ # # Portanto: # $\fbox{$\dfrac{dy}{dx}\bigg|_{(0, 1)} = \dfrac{1}{6}$}$
MAC119_P2B_2016-1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Neural Networks and Deep Learning for Life Sciences and Health Applications - An introductory course about theoretical fundamentals, case studies and implementations in python and tensorflow # (C) <NAME> 2018 - <EMAIL> # # github repository: https://github.com/michelucci/dlcourse2018_students # # Fall Semester 2018 # # Error Analysis Diagram Code (EAD) import numpy as np import matplotlib.pyplot as plt eps = [1,3,9,5] # + colors = [()] fig, ax = plt.subplots() bar = ax.bar(x = [1,2,3,4], height = eps, width = 1.0, color = (0.9,0.9,0.9), edgecolor = 'Black') bar[0].set_hatch('/') bar[0].set_color((0.9,0.9,0.9)) bar[0].set_edgecolor('Black') bar[1].set_color((0.8,0.8,0.8)) bar[1].set_hatch('/') bar[1].set_edgecolor('Black') bar[2].set_hatch('/') bar[2].set_color((0.7,0.7,0.7)) bar[2].set_edgecolor('Black') bar[3].set_hatch('/') bar[3].set_color((0.6,0.6,0.6)) bar[3].set_edgecolor('Black') plt.xticks([1,2,3,4], ['Avoidable Bias','Variance','Data Mismatch\nProblem','Overfitting\non Dev'], rotation = 'vertical', fontsize = 14) plt.yticks([0,2,4,6,8,10],['','2','4','6','8','10'], fontsize = 14) plt.ylim(0,11) plt.xlim(0.5,4.5) for i,v in enumerate(eps): ax.text(i+0.9, v+0.4, str(v)+'%', color = 'Black', fontsize = 14) #plt.axhline(y=2, color = 'Black') #plt.axhline(y=4, color = 'Black') #plt.axhline(y=6, color = 'Black') #plt.axhline(y=8, color = 'Black') plt.axvline(x=0.5, color = 'Black') plt.axvline(x=1.5, color = 'Black') plt.axvline(x=2.5, color = 'Black') plt.axvline(x=3.5, color = 'Black') plt.axvline(x=4.5, color = 'Black') # - # # Figure 6-4 eps = [9] # + fig, ax = plt.subplots(figsize = (8,5)) bar = ax.barh([1,2,3,4], eps, height= 1.0, color = (0.9,0.9,0.9), edgecolor = 'Black') bar[0].set_hatch('/') bar[0].set_color((0.9,0.9,0.9)) bar[0].set_edgecolor('Black') #bar[1].set_color((0.75,0.75,0.75)) #bar[1].set_hatch('/') #bar[1].set_edgecolor('Black') #bar[2].set_hatch('/') #bar[2].set_color((0.6,0.6,0.6)) #bar[2].set_edgecolor('Black') #bar[3].set_hatch('/') #bar[3].set_color((0.45,0.45,0.45)) #bar[3].set_edgecolor('Black') plt.yticks([1], ['Bias / $\Delta \epsilon_{Bias}$'], fontsize = 14) plt.xlim(0,11) plt.ylim(0.5,1.5) for i,v in enumerate(eps): ax.text(v+0.4, i+0.88, str(v)+'%', color = 'Black', fontsize = 14) plt.xticks([0,2,4,6,8,10],['0','2','4','6','8','10'], fontsize = 14) plt.axhline(y=0.5, color = 'Black') #plt.axhline(y=1.5, color = 'Black') #plt.axhline(y=2.5, color = 'Black') #plt.axhline(y=3.5, color = 'Black') #plt.axhline(y=4.5, color = 'Black') plt.title ('Metric Analysis Diagram (MAD)', fontsize = 14) plt.show() fig.savefig('Figure_6-4'+'.png', format='png', dpi=300,bbox_inches='tight') # - # # Figure 6-5 eps = [4,6] # + fig, ax = plt.subplots(figsize = (8,5)) bar = ax.barh([1,2], eps, height= 1.0, color = (0.9,0.9,0.9), edgecolor = 'Black') bar[0].set_hatch('/') bar[0].set_color((0.9,0.9,0.9)) bar[0].set_edgecolor('Black') bar[1].set_color((0.75,0.75,0.75)) bar[1].set_hatch('/') bar[1].set_edgecolor('Black') #bar[2].set_hatch('/') #bar[2].set_color((0.6,0.6,0.6)) #bar[2].set_edgecolor('Black') #bar[3].set_hatch('/') #bar[3].set_color((0.45,0.45,0.45)) #bar[3].set_edgecolor('Black') plt.yticks([1,2], ['Overfitting of training dataset / $\Delta \epsilon_{overfitting\ train}$', 'Bias / $\Delta \epsilon_{Bias}$'], fontsize = 14) plt.xlim(0,11) plt.ylim(0.5,2.5) for i,v in enumerate(eps): ax.text(v+0.4, i+0.88, str(v)+'%', color = 'Black', fontsize = 14) plt.xticks([0,2,4,6,8,10],['0','2','4','6','8','10'], fontsize = 14) plt.axhline(y=0.5, color = 'Black') plt.axhline(y=1.5, color = 'Black') #plt.axhline(y=2.5, color = 'Black') #plt.axhline(y=3.5, color = 'Black') #plt.axhline(y=4.5, color = 'Black') plt.title ('Metric Analysis Diagram (MAD)', fontsize = 14) plt.show() fig.savefig('Figure_6-5'+'.png', format='png', dpi=300,bbox_inches='tight') # - # # Figure 6-6 eps = [8,4,6] # + fig, ax = plt.subplots(figsize = (8,5)) bar = ax.barh([1,2,3], eps, height= 1.0, color = (0.9,0.9,0.9), edgecolor = 'Black') bar[0].set_hatch('/') bar[0].set_color((0.9,0.9,0.9)) bar[0].set_edgecolor('Black') bar[1].set_color((0.75,0.75,0.75)) bar[1].set_hatch('/') bar[1].set_edgecolor('Black') bar[2].set_hatch('/') bar[2].set_color((0.6,0.6,0.6)) bar[2].set_edgecolor('Black') #bar[3].set_hatch('/') #bar[3].set_color((0.45,0.45,0.45)) #bar[3].set_edgecolor('Black') plt.yticks([1,2,3], ['Overfitting of dev dataset / $\Delta \epsilon_{overfitting\ dev}$', 'Overfitting of training dataset / $\Delta \epsilon_{overfitting\ train}$', 'Bias / $\Delta \epsilon_{Bias}$'], fontsize = 14) plt.xlim(0,11) plt.ylim(0.5,3.5) for i,v in enumerate(eps): ax.text(v+0.4, i+0.88, str(v)+'%', color = 'Black', fontsize = 14) plt.xticks([0,2,4,6,8,10],['0','2','4','6','8','10'], fontsize = 14) plt.axhline(y=0.5, color = 'Black') plt.axhline(y=1.5, color = 'Black') plt.axhline(y=2.5, color = 'Black') #plt.axhline(y=3.5, color = 'Black') #plt.axhline(y=4.5, color = 'Black') plt.title ('Metric Analysis Diagram (MAD)', fontsize = 14) plt.show() fig.savefig('Figure_6-6'+'.png', format='png', dpi=300,bbox_inches='tight') # + fig, ax = plt.subplots(figsize = (8,5)) bar = ax.barh([1,2,3,4], eps, height= 1.0, color = (0.9,0.9,0.9), edgecolor = 'Black') bar[0].set_hatch('/') bar[0].set_color((0.9,0.9,0.9)) bar[0].set_edgecolor('Black') bar[1].set_color((0.75,0.75,0.75)) bar[1].set_hatch('/') bar[1].set_edgecolor('Black') bar[2].set_hatch('/') bar[2].set_color((0.6,0.6,0.6)) bar[2].set_edgecolor('Black') bar[3].set_hatch('/') bar[3].set_color((0.45,0.45,0.45)) bar[3].set_edgecolor('Black') plt.yticks([1,2,3,4], ['Overfitting of dev dataset / $\Delta \epsilon_{overfitting\ dev}$', 'Data mismatch (between train and dev) / $\Delta \epsilon_{train-dev}$', 'Overfitting of training dataset / $\Delta \epsilon_{overfitting\ train}$', 'Bias / $\Delta \epsilon_{Bias}$'], fontsize = 14) plt.xlim(0,11) plt.ylim(0.5,4.5) for i,v in enumerate(eps): ax.text(v+0.4, i+0.88, str(v)+'%', color = 'Black', fontsize = 14) plt.xticks([0,2,4,6,8,10],['0','2','4','6','8','10'], fontsize = 14) plt.axhline(y=0.5, color = 'Black') plt.axhline(y=1.5, color = 'Black') plt.axhline(y=2.5, color = 'Black') plt.axhline(y=3.5, color = 'Black') plt.axhline(y=4.5, color = 'Black') plt.title ('Error Analysis Diagram (EAD)', fontsize = 14) plt.show() fig.savefig('Figure_6-X'+'.png', format='png', dpi=300,bbox_inches='tight') # - # # Figure 6-8 eps = [3,12,7,2] # + fig, ax = plt.subplots(figsize = (8,5)) bar = ax.barh([1,2,3,4], eps, height= 1.0, color = (0.9,0.9,0.9), edgecolor = 'Black') bar[0].set_hatch('/') bar[0].set_color((0.9,0.9,0.9)) bar[0].set_edgecolor('Black') bar[1].set_color((0.75,0.75,0.75)) bar[1].set_hatch('/') bar[1].set_edgecolor('Black') bar[2].set_hatch('/') bar[2].set_color((0.6,0.6,0.6)) bar[2].set_edgecolor('Black') bar[3].set_hatch('/') bar[3].set_color((0.45,0.45,0.45)) bar[3].set_edgecolor('Black') plt.yticks([1,2,3,4], ['Overfitting of dev dataset / $\Delta \epsilon_{overfitting\ dev}$', 'Data mismatch (between train and dev) / $\Delta \epsilon_{train-dev}$', 'Overfitting of training dataset / $\Delta \epsilon_{overfitting\ train}$', 'Bias / $\Delta \epsilon_{Bias}$'], fontsize = 14) plt.xlim(0,15) plt.ylim(0.5,4.5) for i,v in enumerate(eps): ax.text(v+0.4, i+0.88, str(v)+'%', color = 'Black', fontsize = 14) plt.xticks([0,2,4,6,8,10,12,14],['0','2','4','6','8','10','12','14'], fontsize = 14) plt.axhline(y=0.5, color = 'Black') plt.axhline(y=1.5, color = 'Black') plt.axhline(y=2.5, color = 'Black') plt.axhline(y=3.5, color = 'Black') plt.axhline(y=4.5, color = 'Black') plt.title ('Error Analysis Diagram (EAD)', fontsize = 14) plt.show() fig.savefig('Figure_6-8'+'.png', format='png', dpi=300,bbox_inches='tight') # - # # Figure 6-1 x = np.arange(0,1000,10) y = 90-95*np.exp(-x/70)+(x/200-2)*(x>500) # + plt.rc('font', family='arial') plt.rc('xtick', labelsize='x-small') plt.rc('ytick', labelsize='x-small') plt.tight_layout() fig = plt.figure(figsize=(3.9, 3.1)) ax = fig.add_subplot(1, 1, 1) ax.axhline(y = 95, color = 'Black', ls = '-') ax.axhline(y = 85, color = 'Black', ls = '--') ax.plot(x, y, lw = 2.0, ls = '-.', color = 'black', label = 'MSE Train') #ax.plot(lambd_x, mse_dev_y, lw = 2.0, ls = '--', color = 'black', label = 'MSE Dev') ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) plt.xticks([]) ax.set_xlabel('Time invested in Research') ax.set_ylabel('Accuracy') ax.set_xlim(0,1000) ax.set_ylim(0,100) ax.text(400, 100, r'100 - $\epsilon_{Bayes}$', fontsize = 13) ax.text(400, 75, r'100 - $\epsilon_{hlp}$', fontsize = 13) #ax.text(12.5, 10, 'More\nregularization', fontsize = 13) #plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) fig.savefig('Figure_6-1'+'.png', format='png', dpi=300,bbox_inches='tight') # - # # MNIST Shifted # + import numpy as np from sklearn.datasets import fetch_mldata # %matplotlib inline import matplotlib import matplotlib.pyplot as plt from random import * # - mnist = fetch_mldata('MNIST original') mnist Xinput,yinput = mnist["data"], mnist["target"] # + def plot_digit(some_digit): some_digit_image = some_digit.reshape(28,28) plt.imshow(some_digit_image, cmap = matplotlib.cm.binary, interpolation = "nearest") #plt.axis("off") plt.show() plot_digit(Xinput[36003]) # - Xtrain = X_train_tr ytrain = y_train_shifted plot_digit(Xtrain[:,1005]) # ## Let's shift the images Xtrain_shifted = np.zeros_like(Xtrain) for i in range(Xtrain.shape[1]): tmp = Xtrain[:,i].reshape(28,28) tmp_shifted = np.zeros_like(tmp) tmp_shifted[:,10:28] = tmp[:,0:18] Xtrain_shifted[:,i] = tmp_shifted.reshape(784) plot_digit(Xtrain[:,7000]) plot_digit(Xtrain_shifted[:,7000]) # ## Figure 6-7 f = plt.figure(figsize=(12,6)); plt.subplot(1,2,1) plt.imshow(Xtrain[:,1345].reshape(28,28), cmap = matplotlib.cm.binary, interpolation = "nearest") plt.subplot(1,2,2) plt.imshow(Xtrain_shifted[:,1345].reshape(28,28), cmap = matplotlib.cm.binary, interpolation = "nearest") f.savefig('Figure_6-7'+'.png', format='png', dpi=300,bbox_inches='tight') # # Model # ## Let's create a train, a train-dev and a dev dataset X_ = Xinput[np.any([y == 1,y == 2], axis = 0)] y_ = yinput[np.any([y == 1,y == 2], axis = 0)] print(X_.shape) # + np.random.seed(42) rnd_train = np.random.rand(len(y_)) < 0.8 X_train = X_[rnd_train,:] y_train = y_[rnd_train] X_dev = X_[~rnd_train,:] y_dev = y_[~rnd_train] # - X_train_normalised = X_train/255.0 X_dev_normalised = X_dev/255.0 # + X_train_tr = X_train_normalised.transpose() y_train_tr = y_train.reshape(1,y_train.shape[0]) n_dim = X_train_tr.shape[0] dim_train = X_train_tr.shape[1] X_dev_tr = X_dev_normalised.transpose() y_dev_tr = y_dev.reshape(1,y_dev.shape[0]) # - y_train_shifted = y_train_tr - 1 y_dev_shifted = y_dev_tr - 1 # + Xtrain = X_train_tr ytrain = y_train_shifted Xdev = X_dev_tr ydev = y_dev_shifted # - print(Xtrain.shape) print(Xdev.shape) # ## Let's create the train-dev dataset shifted # + Xtraindev = np.zeros_like(Xdev) for i in range(Xdev.shape[1]): tmp = Xdev[:,i].reshape(28,28) tmp_shifted = np.zeros_like(tmp) tmp_shifted[:,10:28] = tmp[:,0:18] Xtraindev[:,i] = tmp_shifted.reshape(784) ytraindev = ydev # - print(Xtraindev.shape) n_dim import tensorflow as tf # + tf.reset_default_graph() X = tf.placeholder(tf.float32, [n_dim, None]) Y = tf.placeholder(tf.float32, [1, None]) learning_rate = tf.placeholder(tf.float32, shape=()) W = tf.Variable(tf.zeros([1, n_dim])) b = tf.Variable(tf.zeros(1)) init = tf.global_variables_initializer() # - y_ = tf.sigmoid(tf.matmul(W,X)+b) cost = - tf.reduce_mean(Y * tf.log(y_)+(1-Y) * tf.log(1-y_)) training_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) def run_logistic_model(learning_r, training_epochs, train_obs, train_labels, debug = False): sess = tf.Session() sess.run(init) cost_history = np.empty(shape=[0], dtype = float) for epoch in range(training_epochs+1): sess.run(training_step, feed_dict = {X: train_obs, Y: train_labels, learning_rate: learning_r}) cost_ = sess.run(cost, feed_dict={ X:train_obs, Y: train_labels, learning_rate: learning_r}) cost_history = np.append(cost_history, cost_) if (epoch % 10 == 0) & debug: print("Reached epoch",epoch,"cost J =", str.format('{0:.6f}', cost_)) return sess, cost_history sess, cost_history = run_logistic_model(learning_r = 0.01, training_epochs = 100, train_obs = Xtrain, train_labels = ytrain, debug = True) correct_prediction1=tf.equal(tf.greater(y_, 0.5), tf.equal(Y,1)) accuracy1 = tf.reduce_mean(tf.cast(correct_prediction1, tf.float32)) print(sess.run(accuracy1, feed_dict={X:Xtrain, Y: ytrain, learning_rate: 0.05})) correct_prediction1=tf.equal(tf.greater(y_, 0.5), tf.equal(Y,1)) accuracy1 = tf.reduce_mean(tf.cast(correct_prediction1, tf.float32)) print(sess.run(accuracy1, feed_dict={X:Xdev, Y: ydev, learning_rate: 0.05})) correct_prediction1=tf.equal(tf.greater(y_, 0.5), tf.equal(Y,1)) accuracy1 = tf.reduce_mean(tf.cast(correct_prediction1, tf.float32)) print(sess.run(accuracy1, feed_dict={X:Xtraindev, Y: ytraindev, learning_rate: 0.05}))
Week 8 - Metric Analysis/Week 8 - Metric Analysis - REFERENCE.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 # --- # # Exploring the interactive widgets of ipython # Learn how to play with them. # + import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Plot inline # %matplotlib inline # Add the proper path import sys sys.path.append("../") # Local libraries from signals.aux_functions import gaussian_bump, combine_gaussian_bumps from inputs.sensors import Sensor, PerceptualSpace from inputs.lag_structure import LagStructure # Widgets library from ipywidgets import interact, interactive, fixed from IPython.display import display # - Tmax = 1000 dt = 1.0 time = np.arange(0, Tmax, dt) # First we define the parameters for the gaussian bumpbs # + max_rate = 100 base = 10 value = 30 attenuation = 2 center1 = 200 center2 = 500 center3 = 750 # - # ### One gaussian bump # We define a function that passes all the parameters in order to build a slider. Then we plot it. def plot_gaussian_bump(mu, Max, base, value, a): plt.plot(time, gaussian_bump(time, mu, Max, base, value, a)) plt.ylim([0, 120]) interact(plot_gaussian_bump2, mu=(100, 1000), Max=(60, 100), base=(0, 25), value=(10, 100), a=(2.0, 3.0, 0.1)) # ### A train of gaussian bumps def plot_gaussian_train(mu1, mu2, mu3, Max, base, value): # Create the gaussian bumpbs gb1 = gaussian_bump(time, mu1, Max, base, value, attenuation) gb2 = gaussian_bump(time, mu2, Max, base, value, attenuation) gb3 = gaussian_bump(time, mu3, Max, base, value, attenuation) # Combine them aux = [gb1, gb2, gb3] # A list of functions gaussian_train = combine_gaussian_bumps(aux, base) plt.plot(time, gaussian_train) plt.ylim([0, 200]) interact(plot_gaussian_train, mu1=(100, 1000), mu2=(100, 1000), mu3=(100, 1000), Max=(60, 100), base=(0, 25), value=(10, 100))
presentations/2015-10-13(Sliders 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 # name: python3 # --- # + id="mE5vky3QfIXk" import pandas as pd import os import json import argparse import numpy as np from keras.models import Sequential, load_model from keras.layers import LSTM, Dropout, TimeDistributed, Dense, Activation, Embedding #DATA_DIR = pd.read_csv("input.txt" , sep="\t" ) DATA_DIR = '/content/drive/MyDrive' MODEL_DIR = 'C:/Users/hp/Downloads/char-rnn-keras-master/model' BATCH_SIZE = 16 SEQ_LENGTH = 64 # + id="RvKL2I9MtNhb" def save_weights(epoch, model): if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) model.save_weights(os.path.join(MODEL_DIR, 'weights.{}.h5'.format(epoch))) def load_weights(epoch, model): model.load_weights(os.path.join(MODEL_DIR, 'weights.{}.h5'.format(epoch))) # + colab={"base_uri": "https://localhost:8080/"} id="2kwax8uWfIlJ" outputId="42b3a8d3-1c50-4588-f574-1b947054f279" def build_model(batch_size, seq_len, vocab_size): model = Sequential() model.add(Embedding(vocab_size, 512, batch_input_shape=(batch_size, seq_len))) for i in range(3): model.add(LSTM(256, return_sequences=True, stateful=True)) model.add(Dropout(0.2)) model.add(TimeDistributed(Dense(vocab_size))) model.add(Activation('softmax')) return model if __name__ == '__main__': model = build_model(16, 64, 50) model.summary() # + id="0aS2i0AVwLIZ" def read_batches(T, vocab_size): length = T.shape[0]; #129,665 batch_chars = int(length / BATCH_SIZE); # 8,104 for start in range(0, batch_chars - SEQ_LENGTH, SEQ_LENGTH): # (0, 8040, 64) X = np.zeros((BATCH_SIZE, SEQ_LENGTH)) # 16X64 Y = np.zeros((BATCH_SIZE, SEQ_LENGTH, vocab_size)) # 16X64X86 for batch_idx in range(0, BATCH_SIZE): # (0,16) for i in range(0, SEQ_LENGTH): #(0,64) X[batch_idx, i] = T[batch_chars * batch_idx + start + i] # Y[batch_idx, i, T[batch_chars * batch_idx + start + i + 1]] = 1 yield X, Y # + id="2EdXccZpnl3N" class TrainLogger(object): def __init__(self, file): self.file = os.path.join(LOG_DIR, file) self.epochs = 0 with open(self.file, 'w') as f: f.write('epoch,loss,acc\n') def add_entry(self, loss, acc): self.epochs += 1 s = '{},{},{}\n'.format(self.epochs, loss, acc) with open(self.file, 'a') as f: f.write(s) # + colab={"base_uri": "https://localhost:8080/"} id="rKphwTmPwRZH" outputId="ad433e31-a9fb-4f7c-c7f1-4585d8b077de" import sys sys.argv=[''] del sys LOG_DIR = 'C:/Users/hp/Downloads/char-rnn-keras-master/logs' def train(text, epochs=100, save_freq=10): # character to index and vice-versa mappings char_to_idx = { ch: i for (i, ch) in enumerate(sorted(list(set(text)))) } print("Number of unique characters: " + str(len(char_to_idx))) #86 with open(os.path.join(DATA_DIR, 'char_to_idx.json'), 'w') as f: json.dump(char_to_idx, f) idx_to_char = { i: ch for (ch, i) in char_to_idx.items() } vocab_size = len(char_to_idx) #model_architecture model = build_model(BATCH_SIZE, SEQ_LENGTH, vocab_size) model.summary() model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) #Train data generation T = np.asarray([char_to_idx[c] for c in text], dtype=np.int32) #convert complete text into numerical indices print("Length of text:" + str(T.size)) #129,665 steps_per_epoch = (len(text) / BATCH_SIZE - 1) / SEQ_LENGTH log = TrainLogger('training_log.csv') for epoch in range(epochs): print('\nEpoch {}/{}'.format(epoch + 1, epochs)) losses, accs = [], [] for i, (X, Y) in enumerate(read_batches(T, vocab_size)): print(X); loss, acc = model.train_on_batch(X, Y) print('Batch {}: loss = {}, acc = {}'.format(i + 1, loss, acc)) losses.append(loss) accs.append(acc) log.add_entry(np.average(losses), np.average(accs)) if (epoch + 1) % save_freq == 0: save_weights(epoch + 1, model) print('Saved checkpoint to', 'weights.{}.h5'.format(epoch + 1)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Train the model on some text.') parser.add_argument('--input', default='input.txt', help='name of the text file to train from') parser.add_argument('--epochs', type=int, default=100, help='number of epochs to train for') parser.add_argument('--freq', type=int, default=10, help='checkpoint save frequency') args = parser.parse_args() if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) train(open(os.path.join(DATA_DIR, args.input)).read(), args.epochs, args.freq)
Music_Gen.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.3.1 # language: julia # name: julia-1.3 # --- # # <center>SMI ADCG routine</center> # ### Code Dependencies # ##### Get unzip for data download ; sudo apt-get install -y unzip # ##### Necessary Julia Packages include("Packages.jl"); include("../examples/smi/run.jl")
src/.ipynb_checkpoints/SMI ADCG Julia-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: rtc_analysis # language: python # name: rtc_analysis # --- # + [markdown] hide_input=false # <img src="NotebookAddons/blackboard-banner.png" width="100%" /> # <font face="Calibri"> # <br> # <font size="5"><b>Exploring SAR Data and SAR Time Series Analysis using Jupyter Notebooks</b></font> # # <br> # <font size="4"><b> <NAME>; University of Alaska Fairbanks & <NAME>, <a href="http://earthbigdata.com/" target="_blank">Earth Big Data, LLC</a> </b> <br> # <img src="NotebookAddons/UAFLogo_A_647.png" width="170" align="right" /> # </font> # # <font size="3"> This notebook will introduce you to the analysis of deep multi-temporal SAR image data stacks in the framework of *Jupyter Notebooks*. The Jupyter Notebook environment is easy to launch in any web browser for interactive data exploration with provided or new training data. Notebooks are comprised of text written in a combination of executable python code and markdown formatting including latex style mathematical equations. Another advantage of Jupyter Notebooks is that they can easily be expanded, changed, and shared with new data sets or newly available time series steps. Therefore, they provide an excellent basis for collaborative and repeatable data analysis. <br> # # <b>We introduce the following data analysis concepts:</b> # # - How to load your own SAR data into Jupyter Notebooks and create a time series stack # - How to apply calibration constants to covert initial digital number (DN) data into calibrated radar cross section information. # - How to subset images and create a time series of your subset data. # - How to explore the time-series information in SAR data stacks for environmental analysis. # # </font> # - # <hr> # <font face="Calibri" size="5" color="darkred"> <b>Important Note about JupyterHub</b> </font> # <br><br> # <font face="Calibri" size="3"> <b>Your JupyterHub server will automatically shutdown when left idle for more than 1 hour. Your notebooks will not be lost but you will have to restart their kernels and re-run them from the beginning. You will not be able to seamlessly continue running a partially run notebook.</b> </font> # # + # %%javascript var kernel = Jupyter.notebook.kernel; var command = ["notebookUrl = ", "'", window.location, "'" ].join('') kernel.execute(command) # + pycharm={"name": "#%%\n"} from IPython.display import Markdown from IPython.display import display # user = !echo $JUPYTERHUB_USER # env = !echo $CONDA_PREFIX if env[0] == '': env[0] = 'Python 3 (base)' if env[0] != '/home/jovyan/.local/envs/rtc_analysis': display(Markdown(f'<text style=color:red><strong>WARNING:</strong></text>')) display(Markdown(f'<text style=color:red>This notebook should be run using the "rtc_analysis" conda environment.</text>')) display(Markdown(f'<text style=color:red>It is currently using the "{env[0].split("/")[-1]}" environment.</text>')) display(Markdown(f'<text style=color:red>Select the "rtc_analysis" from the "Change Kernel" submenu of the "Kernel" menu.</text>')) display(Markdown(f'<text style=color:red>If the "rtc_analysis" environment is not present, use <a href="{notebookUrl.split("/user")[0]}/user/{user[0]}/notebooks/conda_environments/Create_OSL_Conda_Environments.ipynb"> Create_OSL_Conda_Environments.ipynb </a> to create it.</text>')) display(Markdown(f'<text style=color:red>Note that you must restart your server after creating a new environment before it is usable by notebooks.</text>')) # - # <hr> # <font face="Calibri"> # # <font size="5"> <b> 0. Importing Relevant Python Packages </b> </font> # # <font size="3">In this notebook we will use the following scientific libraries: # <ol type="1"> # <li> <b><a href="https://pandas.pydata.org/" target="_blank">Pandas</a></b> is a Python library that provides high-level data structures and a vast variety of tools for analysis. The great feature of this package is the ability to translate rather complex operations with data into one or two commands. Pandas contains many built-in methods for filtering and combining data, as well as the time-series functionality. </li> # <li> <b><a href="https://www.gdal.org/" target="_blank">GDAL</a></b> is a software library for reading and writing raster and vector geospatial data formats. It includes a collection of programs tailored for geospatial data processing. Most modern GIS systems (such as ArcGIS or QGIS) use GDAL in the background.</li> # <li> <b><a href="http://www.numpy.org/" target="_blank">NumPy</a></b> is one of the principal packages for scientific applications of Python. It is intended for processing large multidimensional arrays and matrices, and an extensive collection of high-level mathematical functions and implemented methods makes it possible to perform various operations with these objects. </li> # <li> <b><a href="https://matplotlib.org/index.html" target="_blank">Matplotlib</a></b> is a low-level library for creating two-dimensional diagrams and graphs. With its help, you can build diverse charts, from histograms and scatterplots to non-Cartesian coordinates graphs. Moreover, many popular plotting libraries are designed to work in conjunction with matplotlib. </li> # <li> The <b><a href="https://www.pydoc.io/pypi/asf-hyp3-1.1.1/index.html" target="_blank">asf-hyp3 API</a></b> provides useful functions and scripts for accessing and processing SAR data via the Alaska Satellite Facility's Hybrid Pluggable Processing Pipeline, or HyP3 (pronounced "hype"). </li> # <li><b><a href="https://www.scipy.org/about.html" target="_blank">SciPY</a></b> is a library that provides functions for numerical integration, interpolation, optimization, linear algebra and statistics. </li> # # </font> # # <font face="Calibri" size="3"> Our first step is to <b>import them:</b> </font> # + # %%capture import os # for chdir, getcwd, path.exists import glob # for glob import re # for match import json # for loads import math # for ceil import shutil import copy import pyproj import pandas as pd # for DatetimeIndex from osgeo import gdal # for Info import numpy as np # for copy, isnan, log10, ma.masked_where, max, mean, min, percentile, power, unique, var, where import matplotlib.pylab as plb # for figure, grid, rcParams, savefig import matplotlib.pyplot as plt from matplotlib import animation from matplotlib import rc import scipy.signal from IPython.display import HTML import asf_notebook as asfn asfn.jupytertheme_matplotlib_format() # - # <hr> # <font face="Calibri"> # # <font size="5"> <b> 1. Load Your Own Data Stack Into the Notebook </b> </font> # # <font size="3"> This notebook assumes that you've created your own data stack over your personal area of interest using the <a href="https://www.asf.alaska.edu/" target="_blank">Alaska Satellite Facility's</a> value-added product system <a href="http://hyp3.asf.alaska.edu/" target="_blank">HyP3</a>. HyP3 is an environment that is used by ASF to prototype value added products and provide them to users to collect feedback. # # This notebook expects <a href="https://media.asf.alaska.edu/uploads/RTC/rtc_atbd_v1.2_final.pdf" target="_blank">Radiometric Terrain Corrected</a> (RTC) image products as input, so be sure to select an RTC process when creating the subscription for your input data within HyP. Prefer a **unique orbit geometry** (ascending or descending) to keep geometric differences between images low. # # We will retrieve HyP3 data via the HyP3 API. As both HyP3 and the Notebook environment sit in the <a href="https://aws.amazon.com/" target="_blank">Amazon Web Services (AWS)</a> cloud, data transfer is quick and cost effective.</font> # </font> # <hr> # <font face="Calibri" size="3"> To download data from ASF, you need to provide your <a href="https://www.asf.alaska.edu/get-data/get-started/free-earthdata-account/" target="_blank">NASA Earth Data</a> username to the system. Setup an EarthData account if you do not yet have one. <font color='rgba(200,0,0,0.2)'><b>Note that EarthData's End User License Agreement (EULA) applies when accessing the Hyp3 API from this notebook. If you have not acknowleged the EULA in EarthData, you will need to navigate to <a href="https://earthdata.nasa.gov/" target="_blank">EarthData's home page</a> and complete that process.</b></font> # <br><br> # <b>Login to Earthdata:</b> </font> login = asfn.EarthdataLogin() # <hr> # <font face="Calibri" size="3"> Before we download anything, create a working directory for this analysis and change into it. # <br><br> # <b>Select or create a working directory for the analysis:</b></font> while True: data_dir = asfn.input_path(f"\nPlease enter the name of a directory in which to store your data for this analysis.") if os.path.exists(data_dir): contents = glob.glob(f'{data_dir}/*') if len(contents) > 0: choice = asfn.handle_old_data(data_dir, contents) if choice == 1: shutil.rmtree(data_dir) os.mkdir(data_dir) break elif choice == 2: break else: clear_output() continue else: break else: os.mkdir(data_dir) break # <font face="Calibri" size="3"><b>Change into the analysis directory:</b></font> analysis_directory = f"{os.getcwd()}/{data_dir}" os.chdir(analysis_directory) print(f"Current working directory: {os.getcwd()}") # <font face="Calibri" size="3"><b>Create a folder in which to download your RTC products.</b> </font> rtc_path = "rtc_products" asfn.new_directory(rtc_path) products_path = f"{analysis_directory}/{rtc_path}" # <font face="Calibri" size="3"><b>List subscriptions and select one:</b> </font> subscriptions = asfn.get_hyp3_subscriptions(login) if len(subscriptions) > 1: display(Markdown("<text style='color:darkred;'>Note: After selecting a subscription, you must select the next cell before hitting the 'Run' button or typing Shift/Enter.</text>")) display(Markdown("<text style='color:darkred;'>Otherwise, you will simply rerun this code cell.</text>")) print('\nSelect a Subscription:') subscription_id = asfn.select_parameter(subscriptions, '') subscription_id # <font face="Calibri" size="3"><b>Save the selected subscription ID:</b> </font> subscription_id = subscription_id.value.split(':')[0] print(subscription_id) # <font face="Calibri" size="3"><b>Select a date range of products to download:</b> </font> display(Markdown("<text style='color:darkred;'>Note: After selecting a date range, you should select the next cell before hitting the 'Run' button or typing Shift/Enter.</text>")) display(Markdown("<text style='color:darkred;'>Otherwise, you may simply rerun this code cell.</text>")) print('\nSelect a Date Range:') products_info = asfn.get_subscription_products_info(subscription_id, login) dates = asfn.get_products_dates(products_info) date_picker = asfn.gui_date_picker(dates) date_picker # <font face="Calibri" size="3"><b>Save the selected date range:</b> </font> date_range = asfn.get_slider_vals(date_picker) date_range[0] = date_range[0].date() date_range[1] = date_range[1].date() print(f"Date Range: {str(date_range[0])} to {str(date_range[1])}") # <font face="Calibri" size="3"><b>Gather the names and ids for all products in the subscription:</b></font> granule_names = asfn.get_subscription_granule_names_ids(subscription_id, login) # <font face="Calibri" size="3"><b>Gather the available paths, flight directions, and download_urls for the subscription, inside the selected date range:</b></font> display(Markdown("<text style='color:darkred;'><text style='font-size:150%;'>This may take some time for large subscriptions...</text></text>")) product_info = asfn.get_product_info(granule_names, products_info, date_range) display(Markdown(f"<text style=color:blue><text style='font-size:175%;'>Done.</text></text>")) paths = set(product_info['paths']) paths.add('All Paths') # <font face="Calibri" size="3"><b>Select a path or paths (use shift or ctrl to select multiple paths):</b></font> display(Markdown("<text style='color:darkred;'>Note: After selecting a path, you must select the next cell before hitting the 'Run' button or typing Shift/Enter.</text>")) display(Markdown("<text style='color:darkred;'>Otherwise, you will simply rerun this code cell.</text>")) print('\nSelect a Path:') path_choice = asfn.select_mult_parameters(paths, '') path_choice # <font face="Calibri" size="3"><b>Save the selected flight path/s:</b></font> fp = path_choice.value if fp: if 'All Paths' in fp: fp = None if fp: print(f"Flight Path: {fp}") else: print('Flight Path: All Paths') else: print("WARNING: You must select a flight path in the previous cell, then rerun this cell.") # <font face="Calibri" size="3"><b>Select an orbit Direction:</b></font> valid_directions = set() for i, path in enumerate(product_info['paths']): if not fp or path in fp: valid_directions.add(product_info['directions'][i]) if len(valid_directions) > 1: display(Markdown("<text style='color:red;'>Note: After selecting a flight direction, you must select the next cell before hitting the 'Run' button or typing Shift/Enter.</text>")) display(Markdown("<text style='color:red;'>Otherwise, you will simply rerun this code cell.</text>")) print('\nSelect a Flight Direction:') direction_choice = asfn.select_parameter(valid_directions, 'Direction:') direction_choice # <font face="Calibri" size="3"><b>Save the selected orbit direction:</b></font> direction = direction_choice.value print(f"Orbit Direction: {direction}") # <font face="Calibri" size="3"><b>Create a list of download_urls within the date range, filtered by orbit direction and flight path:</b> </font> download_urls = [] for i, orbit_dir in enumerate(product_info['directions']): if orbit_dir == direction: if fp == None or product_info['paths'][i] in fp: download_urls.append(product_info['urls'][i]) download_urls.sort() print(f"There are {len(download_urls)} products to download.") # <font face="Calibri" size="3"><b>Download the products, unzip them into the rtc_products directory, and delete the zip files:</b> </font> if asfn.path_exists(products_path): product_count = 1 print(f"\nSubscription ID: {subscription_id}") for url in download_urls: print(f"\nProduct Number {product_count} of {len(download_urls)}:") product_count += 1 product = url.split('/')[5] filename = f"{products_path}/{product}" # if not already present, we need to download and unzip products if not os.path.exists(filename.split('.zip')[0]): print( f"\n{product} is not present.\nDownloading from {url}") cmd = asfn.get_wget_cmd(url, login) # !$cmd print(f"\n") asfn.asf_unzip(products_path, product) print(f"product: {product}") try: os.remove(product) except OSError: pass print(f"\nDone.") else: print(f"{filename} already exists.") display(Markdown(f"<text style=color:blue><text style='font-size:150%;'>ALL PRODUCTS DOWNLOADED</text></text>")) # <hr> # <font face="Calibri" size="3"><b>Determine the subscription's process type</b>, which we need in order to determine the file paths to the tiffs.</font> # + while True: subscription_info = login.api.get_subscription(subscription_id) try: if subscription_info['status'] == 'ERROR' and \ subscription_info['message'] == 'You must have a valid API key': creds = login.api.reset_api_key() login.api.api = creds['api_key'] except (KeyError, TypeError): break process_type = subscription_info['process_id'] # - # <font face="Calibri" size="3"><b>Determine the available polarizations:</b></font> polarizations = asfn.get_RTC_polarizations(rtc_path) polarization_power_set = asfn.get_power_set(polarizations, 2) # <font face="Calibri" size="3"><b>Select a polarization:</b></font> polarization_choice = asfn.select_parameter(sorted(polarization_power_set), 'Polarizations:') polarization_choice # <font face="Calibri" size="3"><b>Create a paths variable, holding the relative path to the tiffs in the selected polarization/s:</b></font> polarization = polarization_choice.value print(polarization) if len(polarization) == 2: regex = "\w[\--~]{{5,300}}(_|-){}.(tif|tiff)$".format(polarization) dbl_polar = False else: regex = "\w[\--~]{{5,300}}(_|-){}(v|V|h|H).(tif|tiff)$".format(polarization[0]) dbl_polar = True # <hr> # <font face="Calibri" size="3"> You may notice duplicates in your acquisition dates. As HyP3 processes SAR data on a frame-by-frame basis, duplicates may occur if your area of interest is covered by two consecutive image frames. In this case, two separate images are generated that need to be merged together before time series processing can commence. # <br><br> # <b>Write functions to collect and print the paths of the tiffs:</b></font> # + def get_tiff_paths(regex, polarization, pths): tiff_paths = [] for pth in glob.glob(pths): tiff_path = re.search(regex, pth) if tiff_path: tiff_paths.append(pth) return tiff_paths def print_tiff_paths(tiff_paths): print("Tiff paths:") for p in tiff_paths: print(f"{p}\n") # - # <font face="Calibri" size="3"><b>Write a function to collect the product acquisition dates:</b></font> def get_dates(product_list): dates = [] for product in product_list: dates.append(asfn.date_from_product_name(product).split('T')[0]) return dates # <font face="Calibri" size="3"><b>Collect and print the paths of the tiffs:</b></font> tiff_pth = f"{rtc_path}/*/*{polarization[0]}*.tif*" tiff_paths = get_tiff_paths(regex, polarization, tiff_pth) print_tiff_paths(tiff_paths) # <hr> # <font face="Calibri" size="4"> <b>1.2 Fix multiple UTM Zone-related issues</b> <br> # <br> # <font face="Calibri" size="3">Fix multiple UTM Zone-related issues should they exist in your data set. If multiple UTM zones are found, the following code cells will identify the predominant UTM zone and reproject the rest into that zone. This step must be completed prior to merging frames or performing any analysis.</font> # <br><br> # <font face="Calibri" size="3"><b>Use gdal.Info to determine the UTM definition types and zones in each product:</b></font> coord_choice = asfn.select_parameter(["UTM", "Lat/Long"], 'Coord Systems:') coord_choice utm_zones = [] utm_types = [] print('Checking UTM Zones in the data stack ...\n') for k in range(0, len(tiff_paths)): info = (gdal.Info(tiff_paths[k], options = ['-json'])) info = json.dumps(info) info = (json.loads(info))['coordinateSystem']['wkt'] zone = info.split('ID')[-1].split(',')[1][0:-2] utm_zones.append(zone) typ = info.split('ID')[-1].split('"')[1] utm_types.append(typ) print(f"UTM Zones:\n {utm_zones}\n") print(f"UTM Types:\n {utm_types}") # <font face="Calibri" size="3"><b>Identify the most commonly used UTM Zone in the data:</b></font> if coord_choice.value == 'UTM': utm_unique, counts = np.unique(utm_zones, return_counts=True) a = np.where(counts == np.max(counts)) predominant_utm = utm_unique[a][0] print(f"Predominant UTM Zone: {predominant_utm}") else: predominant_utm = '4326' # <font face="Calibri" size="3"><b>Reproject images with errant UTMs to the predominant UTM:</b></font> if coord_choice.value == 'UTM': reproject_indicies = [i for i, j in enumerate(utm_zones) if j != predominant_utm] #makes list of indicies in utm_zones that need to be reprojected #elif coord_choice.value == 'Lat/Long': # reproject_indicies = [i for i, j in enumerate(utm_zones)] print('--------------------------------------------') print('Reprojecting %4.1f files' %(len(reproject_indicies))) print('--------------------------------------------') for k in reproject_indicies: temppath = tiff_paths[k].strip() _, product_name, tiff_name = temppath.split('/') if coord_choice.value == 'UTM': cmd = f"gdalwarp -overwrite rtc_products/{product_name}/{tiff_name} rtc_products/{product_name}/r{tiff_name} -s_srs {utm_types[k]}:{utm_zones[k]} -t_srs EPSG:{predominant_utm}" elif coord_choice.value == 'Lat/Long': cmd = f"gdalwarp -overwrite rtc_products/{product_name}/{tiff_name} rtc_products/{product_name}/r{tiff_name} -s_srs {utm_types[k]}:{utm_zones[k]} -t_srs EPSG:4326" predominant_utm = '4326' #print(f"Calling the command: {cmd}") # !{cmd} rm_command = f"rm {tiff_paths[k].strip()}" #print(f"Calling the command: {rm_command}") # !{rm_command} # <font face="Calibri" size="3"><b>Update tiff_paths with any new filenames created during reprojection:</b></font> tiff_paths = get_tiff_paths(regex, polarization, tiff_pth) print_tiff_paths(tiff_paths) # <hr> # <font face="Calibri" size="4"> <b>1.3 Merge multiple frames from the same date.</b></font> # <br><br> # <font face="Calibri" size="3"><b>Create a list aquisition dates:</b></font> dates = get_dates(tiff_paths) print(dates) # <font face="Calibri" size="3"><b>Create a set containing each represented date:</b></font> unique_dates = set(dates) print(unique_dates) # <font face="Calibri" size="3"><b>Determine which dates have multiple frames. Create a dictionary with each date as a key linked to a value set as an empty string:</b></font> dup_date_batches = [{}] for date in unique_dates: count = 0 for d in dates: if date == d: count +=1 if count > 1: dup_date_batches[0].update({date : ""}) if dbl_polar: dup_date_batches.append(copy.deepcopy(dup_date_batches[0])) print(dup_date_batches) # <font face="Calibri" size="3"><b>Update the key values in dup_paths with the string paths to all the tiffs for each date:</b></font> # + if dbl_polar: polar_list = [polarization.split(' ')[0], polarization.split(' ')[2]] else: polar_list = [polarization] for i, polar in enumerate(polar_list): polar_regex = f"(\w|/)*_{polar}.(tif|tiff)$" polar_paths = get_tiff_paths(polar_regex, polar, tiff_pth) for pth in polar_paths: date = asfn.date_from_product_name(pth).split('T')[0] if date in dup_date_batches[i]: dup_date_batches[i][date] = f"{dup_date_batches[i][date]} {pth}" for d in dup_date_batches: print(d) print("\n") # - # <font face="Calibri" size="3"><b>Merge all the frames for each date.</b></font> for i, dup_dates in enumerate(dup_date_batches): for dup_date in dup_dates: output = f"{dup_dates[dup_date].split('/')[0]}/{dup_dates[dup_date].split('/')[1]}/new{dup_dates[dup_date].split('/')[2].split(' ')[0]}" gdal_command = f"gdal_merge.py -o {output} {dup_dates[dup_date]}" print(f"\n\nCalling the command: {gdal_command}\n") # !{gdal_command} for pth in dup_dates[dup_date].split(' '): if pth and asfn.path_exists(pth): os.remove(pth) print(f"Deleting: {pth}") # <hr> # <font face="Calibri" size="3"> <b>Verify that all duplicate dates were resolved:</b> </font> tiff_paths = get_tiff_paths(regex, polarization, tiff_pth) for polar in polar_list: dates = get_dates(tiff_paths) if len(dates) != len(set(dates)): print(f"Duplicate dates still present!") else: print(f"No duplicate dates are associated with {polar} polarization.") # <font face="Calibri" size="3"><b>Print the updated paths of the tiffs:</b></font> # + #print_tiff_paths(tiff_paths) # uncomment to view paths # - # <hr> # <font face="Calibri"> # # <font size="5"> <b> 2. Create Subset and Stack Up Your Data </b> </font> # # <font size="3"> Now you are ready to work with your data. The next cells allow you to select an area of interest (AOI; via bounding-box corner coordinates) for your data analysis. Once selected, the AOI is being extracted and a data stack is formed. # # <b>Create a string containing paths to one image for each area represented in the stack:</b> # </font> # </font> # + to_merge = {} for pth in tiff_paths: info = (gdal.Info(pth, options = ['-json'])) info = json.dumps(info) info = (json.loads(info))['wgs84Extent']['coordinates'] coords = [info[0][0], info[0][3]] for i in range(0, 2): for j in range(0, 2): coords[i][j] = round(coords[i][j]) str_coords = f"{str(coords[0])}{str(coords[1])}" if str_coords not in to_merge: to_merge.update({str_coords: pth}) print(to_merge) print() merge_paths = "" for pth in to_merge: merge_paths = f"{merge_paths} {to_merge[pth]}" print(merge_paths) # - # <font face="Calibri" size="3"><b>Merge the images, creating a full scene for display in the Area-Of-Interest selector:</b></font> full_scene = f"{analysis_directory}/full_scene.tif" if os.path.exists(full_scene): os.remove(full_scene) gdal_command = f"gdal_merge.py -o {full_scene} {merge_paths}" # !{gdal_command} # <font face="Calibri" size="3"><b>Create a VRT of the full scene:</b></font> image_file = f"{analysis_directory}/raster_stack.vrt" # !gdalbuildvrt -separate $image_file -overwrite $full_scene # <font face="Calibri" size="3"><b>Convert the VRT into an array:</b> </font> img = gdal.Open(image_file) rasterstack = img.ReadAsArray() # <font face="Calibri" size="3"><b>Print the number of bands, pixels, and lines:</b> </font> print(img.RasterCount) # Number of Bands print(img.RasterXSize) # Number of Pixels print(img.RasterYSize) # Number of Lines # <font face="Calibri" size="3"><b>Create an AOI selector from an image in your raster stack:</b> </font> # %matplotlib notebook fig_xsize = 7.5 fig_ysize = 7.5 aoi = asfn.AOI_Selector(rasterstack, fig_xsize, fig_ysize) # <font face="Calibri" size="3"><b>Gather and define projection details:</b> </font> geotrans = img.GetGeoTransform() projlatlon = pyproj.Proj('EPSG:4326') # WGS84 projimg = pyproj.Proj(f'EPSG:{predominant_utm}') # <font face="Calibri" size="3"><b>Write a function to convert the pixel, line coordinates from the AOI selector into geographic coordinates in the stack's EPSG projection:</b> </font> def geolocation(x, y, geotrans,latlon=True): ref_x = geotrans[0]+x*geotrans[1] ref_y = geotrans[3]+y*geotrans[5] if latlon: ref_y, ref_x = pyproj.transform(projimg, projlatlon, ref_x, ref_y) return [ref_x, ref_y] # <font face="Calibri" size="3"><b>Call geolocation to gather the aoi_coords:</b> </font> aoi_coords = [geolocation(aoi.x1, aoi.y1, geotrans, latlon=False), geolocation(aoi.x2, aoi.y2, geotrans, latlon=False)] print(f"aoi_coords in EPSG {predominant_utm}: {aoi_coords}") # <font face="Calibri" size="3"><b>Collect the paths to the tiffs:</b> </font> tiff_paths = get_tiff_paths(regex, polarization, tiff_pth) print_tiff_paths(tiff_paths) # <font face="Calibri" size="3"><b>Create a subdirectory in which to store the subset tiffs:</b> </font> print("Choose a directory name in which to store the subset geotiffs.") print("Note: this will sit alongside the directory containing your pre-subset geotiffs.") while True: sub_name = input() if sub_name == "": print("Please enter a valid directory name") continue else: break # <font size="3"><b>Subset the tiffs and move them from the individual product directories into their own directory, /tiffs:</b></font> subset_dir = f"{analysis_directory}/{sub_name}/" asfn.new_directory(subset_dir) for i, tiff_path in enumerate(tiff_paths): for name_chunk in tiff_path.split('/')[-1].split('_'): nums = list(range(48, 58)) if len(name_chunk) == 15 and ord(name_chunk[0]) in nums: date = name_chunk.split('T')[0] break elif len(name_chunk) == 8 and ord(name_chunk[0]) in nums: date = name_chunk break polar = tiff_path.split('/')[-1].split('.')[0][-2:] print(f"\nProduct #{i+1}:") gdal_command = f"gdal_translate -projwin {aoi_coords[0][0]} {aoi_coords[0][1]} {aoi_coords[1][0]} {aoi_coords[1][1]} -projwin_srs 'EPSG:{predominant_utm}' -co \"COMPRESS=DEFLATE\" -a_nodata 0 {tiff_path} {subset_dir}{date}_{polar}.tiff" print(f"Calling the command: {gdal_command}") # !{gdal_command} # <font size="3"><b>Grab the updated paths of the images:</b></font> sub_pth = f"{subset_dir}/*.tif*" subset_regex = "\w[\--~]{2,200}.(tif|tiff)$" tiff_paths = get_tiff_paths(subset_regex, polarization, sub_pth) print_tiff_paths(tiff_paths) # <font size="3"><b>Delete any subset tifs that are filled with NaNs and contain no data.</b></font> asfn.remove_nan_filled_tifs(subset_dir, tiff_paths) print(f"\nThere are {len(tiff_paths)} tiffs remaining in the image stack.") # <font size="3"><b>Update the list of dates and tiff_paths after removing NaN filled images:</b></font> # + dates = [] pth = glob.glob(f"{subset_dir}/*.tif*") pth.sort() for p in pth: date = os.path.basename(p)[0:8] dates.append(date) print(date) tiff_paths = get_tiff_paths(subset_regex, polarization, sub_pth) # print_tiff_paths(tiff_paths) # uncomment to print tiff paths # - # <hr> # <font face="Calibri" size="3"> Now we stack up the data by creating a virtual raster table with links to all subset data files: </font> # <br><br> # <font size="3"><b>Create the virtual raster table for the subset GeoTiffs:</b></font> # !gdalbuildvrt -separate raster_stack.vrt $subset_dir/*.tif* # <hr> # <font face="Calibri"> # # <font size="5"> <b> 3. Now You Can Work With Your Data </b> </font> # # <font size="3"> Now you are ready to perform time series analysis on your data stack # </font> # </font> # <br> # <font face="Calibri" size="4"> <b> 3.1 Define Data Directory and Path to VRT </b> </font> # <br><br> # <font face="Calibri" size="3"><b>Create a variable containing the VRT filename:</b></font> image_file = "raster_stack.vrt" # <font face="Calibri" size="3"><b>Create an index of timedelta64 data with Pandas:</b></font> time_index = pd.DatetimeIndex(dates) # <font face="Calibri" size="3"><b>Print the bands and dates for all images in the virtual raster table (VRT):</b></font> j = 1 print(f"Bands and dates for {image_file}") for i in time_index: print("{:4d} {}".format(j, i.date()), end=' ') j += 1 if j%5 == 1: print() # <hr> # <br> # <font face="Calibri" size="4"> <b> 3.2 Open Your Data Stack and Visualize Some Layers </b> </font> # # <font face="Calibri" size="3"> We will <b>open your VRT</b> and visualize some layers using Matplotlib. </font> img = gdal.Open(image_file) # <font face="Calibri" size="3"><b>Print the bands, pixels, and lines:</b></font> print(f"Number of bands: {img.RasterCount}") print(f"Number of pixels: {img.RasterXSize}") print(f"Number of lines: {img.RasterYSize}") # <font face="Calibri" size="3"><b>Read in raster data for the first two bands:</b></font> # + raster_1 = img.GetRasterBand(1).ReadAsArray() # change the number passed to GetRasterBand() to where_are_NaNs = np.isnan(raster_1) # read rasters from different bands raster_1[where_are_NaNs] = 0 raster_2 = img.GetRasterBand(2).ReadAsArray() #must pass a valid band number to GetRasterBand() where_are_NaNs = np.isnan(raster_2) raster_2[where_are_NaNs] = 0 # - # <font face="Calibri" size="3"><b>Plot images and histograms for bands 1 and 2:</b></font> # %matplotlib inline # + # Setup the pyplot plots fig = plb.figure(figsize=(18,10)) # Initialize figure with a size ax1 = fig.add_subplot(221) # 221 determines: 2 rows, 2 plots, first plot ax2 = fig.add_subplot(222) # 222 determines: 2 rows, 2 plots, second plot ax3 = fig.add_subplot(223) # 223 determines: 2 rows, 2 plots, third plot ax4 = fig.add_subplot(224) # 224 determines: 2 rows, 2 plots, fourth plot # Plot the band 1 image band_number = 1 ax1.imshow(raster_1,cmap='gray', vmin=0, vmax=0.2) #,vmin=2000,vmax=10000) ax1.set_title('Image Band {} {}'.format(band_number, time_index[band_number-1].date())) # Flatten the band 1 image into a 1 dimensional vector and plot the histogram: h = ax2.hist(raster_1.flatten(), bins=200, range=(0, 0.3)) ax2.xaxis.set_label_text('Amplitude? (Uncalibrated DN Values)') ax2.set_title('Histogram Band {} {}'.format(band_number, time_index[band_number-1].date())) # Plot the band 2 image band_number = 2 ax3.imshow(raster_2,cmap='gray', vmin=0, vmax=0.2) #,vmin=2000,vmax=10000) ax3.set_title('Image Band {} {}'.format(band_number, time_index[band_number-1].date())) # Flatten the band 2 image into a 1 dimensional vector and plot the histogram: h = ax4.hist(raster_2.flatten(),bins=200,range=(0,0.3)) ax4.xaxis.set_label_text('Amplitude? (Uncalibrated DN Values)') ax4.set_title('Histogram Band {} {}'.format(band_number, time_index[band_number-1].date())) # - # <hr> # <br> # <font face="Calibri" size="4"> <b> 3.3 Calibration and Data Conversion between dB and Power Scales </b> </font> # # <font face="Calibri" size="3"> <font color='rgba(200,0,0,0.2)'> <b>Note, that if your data were generated by HyP3, this step is not necessary!</b> HyP3 performs the full data calibration and provides you with calibrated data in power scale. </font> # # If, your data is from a different source, however, calibration may be necessary to ensure that image gray values correspond to proper radar cross section information. # # Calibration coefficients for SAR data are often defined in the decibel (dB) scale due to the high dynamic range of the imaging system. For the L-band ALOS PALSAR data at hand, the conversion from uncalibrated DN values to calibrated radar cross section values in dB scale is performed by applying a standard **calibration factor of -83 dB**. # <br> <br> # $\gamma^0_{dB} = 20 \cdot log10(DN) -83$ # # The data at hand are radiometrically terrain corrected images, which are often expressed as terrain flattened $\gamma^0$ backscattering coefficients. For forest and land cover monitoring applications $\gamma^o$ is the preferred metric. # # <b>To apply the calibration constant for your data and export in *dB* scale, uncomment the following code cell</b>: </font> #caldB=20*np.log10(rasterstack)-83 # <font face="Calibri" size="3"> While **dB**-scaled images are often "visually pleasing", they are often not a good basis for mathematical operations on data. For instance, when we compute the mean of observations, it makes a difference whether we do that in power or dB scale. Since dB scale is a logarithmic scale, we cannot simply average data in that scale. # # Please note that the **correct scale** in which operations need to be performed **is the power scale.** This is critical, e.g. when speckle filters are applied, spatial operations like block averaging are performed, or time series are analyzed. # # To **convert from dB to power**, apply: $\gamma^o_{pwr} = 10^{\frac{\gamma^o_{dB}}{10}}$ </font> # + #calPwr=np.power(10.,caldB/10.) # - # <hr> # <br> # <font face="Calibri" size="4"> <b> 3.4 Create a Time Series Animation </b> </font> # # <font face="Calibri" size="3">Now we are ready to create a time series animation from the calibrated SAR data. # <br><br> # <b>Create a directory in which to store our plots and animations:</b> # </font> output_path = 'plots_animations' asfn.new_directory(output_path) # <font face="Calibri" size="3"> Now we are ready to <b>create a time series animation</b> from the calibrated SAR data. </font> band = img.GetRasterBand(1) raster0 = band.ReadAsArray() band_number = 0 # Needed for updates raster_stack = img.ReadAsArray() img = None # <font face="Calibri" size="3"><b>Create a masked raster stack:</b></font> raster_stack_masked = np.ma.masked_where(raster_stack==0, raster_stack) # <font face="Calibri" size="3"><b>Generate a matplotlib time-series animation:</b></font> # + # %%capture fig = plt.figure(figsize=(14, 8)) ax = fig.add_subplot(111) ax.axis('off') vmin = np.percentile(raster_stack.flatten(), 5) vmax = np.percentile(raster_stack.flatten(), 95) r0dB = 20 * np.ma.log10(raster0) - 83 im = ax.imshow(raster0, cmap='gray', vmin=vmin, vmax=vmax) ax.set_title("{}".format(time_index[0].date())) def animate(i): ax.set_title("{}".format(time_index[i].date())) im.set_data(raster_stack[i]) # Interval is given in milliseconds ani = animation.FuncAnimation(fig, animate, frames=raster_stack.shape[0], interval=400) # - # <font face="Calibri" size="3"><b>Configure matplotlib's RC settings for the animation:</b></font> rc('animation', embed_limit=40971520.0) # <font face="Calibri" size="3"><b>Create a javascript animation of the time-series running inline in the notebook:</b></font> HTML(ani.to_jshtml()) # <font face="Calibri" size="3"><b>Delete the dummy png</b> that was saved to the current working directory while generating the javascript animation in the last code cell.</font> # + hide_input=false try: os.remove('None0000000.png') except FileNotFoundError: pass # - # <font face="Calibri" size="3"><b>Save the animation (animation.gif):</b> </font> ani.save(f"{output_path}/animation.gif", writer='pillow', fps=2) # <br> # <hr> # <font face="Calibri" size="4"> <b> 3.5 Plot the Time Series of Means Calculated Across the Subset </b> </font> # # <font face="Calibri" size="3"> To create the time series of means, we will go through the following steps: # 1. Ensure that you use the data in **power scale** ($\gamma^o_{pwr}$) for your mean calculations. # 2. compute means. # 3. convert the resulting mean values into dB scale for visualization. # 4. plot time series of means. </font> # <br><br> # <font face="Calibri" size="3"> <b>Compute the means:</b> </font> rs_means_pwr = np.mean(raster_stack_masked, axis=(1, 2)) # <font face="Calibri" size="3"><b>Convert resulting mean value time-series to dB scale for visualization:</b></font> rs_means_dB = 10.*np.ma.log10(rs_means_pwr) # <font face="Calibri" size="3"><b>Plot and save the time series of means (RCSoverTime.png):</b></font> plt.rcParams.update({'font.size': 14}) fig = plt.figure(figsize=(16, 4)) ax1 = fig.subplots() window_length = len(rs_means_pwr)-1 if window_length % 2 == 0: window_length -= 1 polyorder = math.ceil(window_length*0.1) yhat = scipy.signal.savgol_filter(rs_means_pwr, window_length, polyorder) ax1.plot(time_index, yhat, color='red', marker='o', markerfacecolor='white', linewidth=3, markersize=6) ax1.plot(time_index, rs_means_pwr, color='gray', linewidth=0.5) plt.grid() ax1.set_xlabel('Date') ax1.set_ylabel('$\overline{\gamma^o}$ [power]') plt.savefig(f'{output_path}/RCSoverTime.png', dpi=72, transparent='true') # <br> # <hr> # <font face="Calibri" size="4"> <b> 3.6 Calculate Coefficient of Variance </b> </font> # # <font face="Calibri" size="3"> The coefficient of variance describes how much the $\sigma_{0}$ or $\gamma_{0}$ measurements in a pixel vary over time. Hence, the coefficient of variance can indicate different vegetation cover and soil moisture regimes in your area.</font> # <br><br> # <font face="Calibri" size="3"><b>Write a function to convert our plots into GeoTiffs:</b></font> def geotiff_from_plot(source_image, out_filename, extent, cmap=None, vmin=None, vmax=None, interpolation=None, dpi=300): assert "." not in out_filename, 'Error: Do not include the file extension in out_filename' assert type(extent) == list and len(extent) == 2 and len(extent[0]) == 2 and len( extent[1]) == 2, 'Error: extent must be a list in the form [[upper_left_x, upper_left_y], [lower_right_x, lower_right_y]]' plt.figure() plt.axis('off') plt.imshow(source_image, cmap=cmap, vmin=vmin, vmax=vmax, interpolation=interpolation) temp = f"{out_filename}_temp.png" plt.savefig(temp, dpi=dpi, transparent='true', bbox_inches='tight', pad_inches=0) cmd = f"gdal_translate -of Gtiff -a_ullr {extent[0][0]} {extent[0][1]} {extent[1][0]} {extent[1][1]} -a_srs EPSG:{predominant_utm} {temp} {out_filename}.tiff" # !{cmd} try: os.remove(temp) except FileNotFoundError: pass # <font face="Calibri" size="3"><b>Plot the Coefficient of Variance Map and save it as a png (Coeffvar.png):</b> </font> # + test = np.var(raster_stack,0) mtest = np.mean(raster_stack[raster_stack.nonzero()],0) coeffvar = test/(mtest+0.001) plt.rcParams.update({'font.size': 14}) fig = plt.figure(figsize=(13, 10)) ax = fig.subplots() ax.axis('off') vmin = np.percentile(coeffvar.flatten(), 5) vmax = np.percentile(coeffvar.flatten(), 95) ax.set_title('Coefficient of Variance Map') im = ax.imshow(coeffvar, cmap='jet', vmin=vmin, vmax=vmax) fig.colorbar(im, ax=ax) plt.savefig(f'{output_path}/Coeffvar.png', dpi=300, transparent='true') # - # <font face="Calibri" size="3"><b>Save the coefficient of variance map as a GeoTiff (Coeffvar.tiff):</b></font> # %%capture geotiff_from_plot(coeffvar, f'{output_path}/Coeffvar', aoi_coords, cmap='jet', vmin=vmin, vmax=vmax) # <br> # <hr> # <font face="Calibri" size="4"> <b> 3.7 Threshold Coefficient of Variance Map </b> </font> # # <font face="Calibri" size="3"> This is an example how to threshold the derived coefficient of variance map. This can be useful, e.g., to detect areas of active agriculture.</font> # <br><br> # # <font face="Calibri" size="3"><b>Plot and save the coefficient of variance histogram and CDF (thresh_coeff_var_histogram.png):</b></font> plt.rcParams.update({'font.size': 14}) fig = plt.figure(figsize=(14, 6)) # Initialize figure with a size ax1 = fig.add_subplot(121) # 121 determines: 2 rows, 2 plots, first plot ax2 = fig.add_subplot(122) # Second plot: Histogram # IMPORTANT: To get a histogram, we first need to *flatten* # the two-dimensional image into a one-dimensional vector. h = ax1.hist(coeffvar.flatten(), bins=200, range=(0, 0.03)) ax1.xaxis.set_label_text('Coefficient of Variation') ax1.set_title('Coeffvar Histogram') plt.grid() n, bins, patches = ax2.hist(coeffvar.flatten(), bins=200, range=(0, 0.03), cumulative='True', density='True', histtype='step', label='Empirical') ax2.xaxis.set_label_text('Coefficient of Variation') ax2.set_title('Coeffvar CDF') plt.grid() plt.savefig(f'{output_path}/thresh_coeff_var_histogram.png', dpi=72, transparent='true') # <font face="Calibri" size="3"><b>Plot the Threshold Coefficient of Variance Map and save it as a png (Coeffvarthresh.png):</b> </font> plt.rcParams.update({'font.size': 14}) outind = np.where(n > 0.80) threshind = np.min(outind) thresh = bins[threshind] coeffvarthresh = np.copy(coeffvar) coeffvarthresh[coeffvarthresh < thresh] = 0 coeffvarthresh[coeffvarthresh > 0.1] = 0 fig = plt.figure(figsize=(13, 10)) ax = fig.subplots() ax.axis('off') vmin = np.percentile(coeffvar.flatten(), 5) vmax = np.percentile(coeffvar.flatten(), 95) ax.set_title(r'Thresholded Coeffvar Map [$\alpha=95%$]') im = ax.imshow(coeffvarthresh, cmap='jet', vmin=vmin, vmax=vmax) bar = fig.colorbar(im, ax=ax) plt.savefig(f'{output_path}/Coeffvarthresh.png', dpi=300, transparent='true') # <font face="Calibri" size="3"><b>Save the Threshold Coefficient of Variance Map as a GeoTiff (Coeffvarthresh.tiff):</b> </font> # %%capture geotiff_from_plot(coeffvarthresh, f'{output_path}/Coeffvarthresh', aoi_coords, cmap='jet', vmin=vmin, vmax=vmax) # <font face="Calibri" size="2"> <i>Time_Series_Hyp3.ipynb - Version 3.4.0- October 2021 </i> # <br> # <b>Version Changes:</b> # <ul> # <li>from osgeo import gdal</li> # <li>namespace asf_notebook</li> # </ul> # </font>
SAR_Training/English/Master/Time_Series_Hyp3.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 # + w = tf.constant(3) x = w + 2 y = x + 5 z = x * 3 with tf.Session() as sess: print(y.eval()) #1. y -> x,w print(z.eval()) #3. z -> x,w print(x.eval()) #2. x -> w # it calculates DAG, note, in 1&3 x,w are calculated twice. 3, does not use value from 1. # + # to compute y,z optimally, we have to ask tf, to do so # TODO - check if Keras does this by defalut. with tf.Session() as sess: y_val,z_val = sess.run([y,z]) # Here y,z are calculated in one graph. print(y_val) print(z_val) # + #NOTE: In single-process, every session gets y,z # In Distributed mode, variable state is stored in server not session, so every session shares same variable.
3. lifecycle of Node Value.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 # + s = pd.Series( np.random.randint(0, 100, size=(100, )), index=np.arange(100), ) display(s) # + ax = s.plot.bar(figsize=(18, 4)) ax.xaxis.set_ticks(s.index[::10]); ax.xaxis.set_ticklabels(map(str, s.index[::10])); # - dates = pd.date_range("2021-01-01", "2021-12-31", freq="D")[:100] dates # + s = pd.Series( np.random.randint(0, 100, size=(len(dates), )), index=dates ) display(s) # + ax = s.plot.bar(figsize=(18, 4)) ax.xaxis.set_ticks(np.arange(100)[::10]); ax.xaxis.set_ticklabels(dates[::10]); # - # See https://stackoverflow.com/a/19387765 for extracting all info from the ticks themselves.
2021-05-27/pandas_bar_plots_skip_ticks.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib notebook import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # + import sys sys.path.insert(0, '../src') from aspire.source.star import Starfile from aspire.basis.fb_3d import FBBasis3D from aspire.estimation.mean import MeanEstimator # - L = 16 source = Starfile('E:\\yan_wu\\All_class001_r1_ct1_data.star', pixel_size=1.338, max_rows=10000) source.set_max_resolution(L) source.cache() # + source.whiten() images = source.images(0, 5) n_images = images.shape[-1] plt.figure(figsize=(10,3)) for i in range(n_images): plt.subplot(1, n_images, i+1) plt.imshow(images[:,:,i]) # - basis = FBBasis3D((L, L, L)) mean_estimator = MeanEstimator(source, basis, batch_size=8192) mean_est = mean_estimator.estimate() # + vol = mean_est # Visualize volume L = vol.shape[0] x, y, z = np.meshgrid(np.arange(L), np.arange(L), np.arange(L)) ax = plt.axes(projection='3d') vol = (vol - np.min(vol))/(np.max(vol)-np.min(vol)) cmap = plt.get_cmap("Greys_r") ax.scatter3D(x, y, z, c=vol.flatten(), cmap=cmap) plt.show()
notebooks/01_starfile.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.3 64-bit (''base'': conda)' # name: python3 # --- import numpy as np from pathlib import Path trans_table = np.zeros((33,32)) first_noteArray = np.zeros(33) #trans_table = transition_table_valueAdder(notes_values, trans_table) def transition_table_valueAdder(note_array, trans_table=trans_table): """ Function to update the first note table and the transition probability table Function will remove zeros for the note_array to simplify sorting Changes the open note (218) to 32 so that the table range is from 0-32 INPUTS: note_array of the song, trans_table OUTPUTS: trans_table """ # Remove zeros from song note array note_array = note_array[note_array != 0] note_array[note_array == 218] = 32 # update first_noteArray trans_table[32][int(note_array[0])-1] += 1 # adding first note to transition table # loop through note array and update trans_table - start with index 1 for i in range(1, len(note_array)): trans_table[int(note_array[i-1]-1)][int(note_array[i])-1] += 1 return trans_table trans_table = np.zeros((33,32)) test = transition_table_valueAdder(notes, trans_table) test.sum() trans_table[0] test[32] def prob_calc(array): new_array = np.nan_to_num(array/array.sum(axis=0)) return (new_array) training_path = Path.home() training_path track_pack_path = Path('/Users/forrestbrandt/Documents/Berkeley/Fall_2021/TensorHero/Condensed Notes') notes_path = Path('/Users/forrestbrandt/Documents/Berkeley/Fall_2021/TensorHero/Condensed Notes/Anti Hero 2/Trivium - Demon (Miscellany)') notes = np.load(notes_path / 'notes_simplified.npy') np.unique(notes) print(notes.shape) # + def create_trans_table(track_pack_path, trans_table): """ Function that takes in a file path (in this case starting at Condensed Notes Folder - Track Pack) and an empty table that navigates through the files and pulls data only from the note_simplified.npy file Function calls transition_table_valueAdder INPUTS: File path, empty table (needs to be generated before) OUTPUTS: returns transition table """ for album in track_pack_path.iterdir(): album_path = track_pack_path / album.name if album.is_file(): if album.name == 'notes_simplified.npy': notes = np.load(album_path / 'notes_simplified.npy') trans_table = transition_table_valueAdder(notes, trans_table) if album.is_dir(): for song in album.iterdir(): notes_path = album_path / song.name if song.is_file(): if song.name == 'notes_simplified.npy': notes = np.load(notes_path / 'notes_simplified.npy') trans_table = transition_table_valueAdder(notes, trans_table) if song.is_dir(): for piece in song.iterdir(): piece_path = notes_path / piece.name if piece.is_file(): if piece.name == 'notes_simplified.npy': notes = np.load(notes_path / 'notes_simplified.npy') trans_table = transition_table_valueAdder(notes, trans_table) return trans_table # - track_pack_path = Path('/Users/forrestbrandt/Documents/Berkeley/Fall_2021/TensorHero/Condensed Notes') trans_table = np.zeros((33,32)) trans_table = create_trans_table(track_pack_path,trans_table) prob_table = prob_calc(trans_table) prob_table.sum(axis=0) trans_table.sum(axis=1)[0] trans_table[2][0] # + import matplotlib.pyplot as plt plt.imshow(prob_table) # - prob_table.shape # returns T/F on whether file exists # could be used for checking if need to go further into subdirectories print(notes_path.exists()) # returns T/F if the subdirectory is a file print(notes_path.is_file()) notes = np.load(notes_path / 'notes_simplified.npy') # + first_note = {} def find_first_note(note_array, dict=first_note): """ Function to find the first note in the note array INPUTS: Note array, dictionary consisting of first note counts OUTPUTS: Updated dictionary """ if note_array[0] not in dict: dict[note_array[0]] = 1 else: dict[note_array[0]] += 1 return dict # + first_note = {} def find_first_note(note_array, dict=first_note): """ Function to find the first note in the note array INPUTS: Note array, dictionary consisting of first note counts OUTPUTS: Updated dictionary """ for i in range(len(note_array)): if note_array[i] > 0: if note_array[i] not in dict: dict[note_array[i]] = 1 else: dict[note_array[i]] += 1 break return dict # - def transition_table_valueAdder(note_array, first_note=first_noteArray, trans_table=trans_table): """ Function to update the first note table and the transition probability table Function will remove zeros for the note_array to simplify sorting INPUTS: note_array of the song, first_noteArray, trans_table OUTPUTS: first_noteArray, trans_table """ # Remove zeros from song note array note_array = note_array[note_array != 0] note_array[note_array == 218] = 32 # update first_noteArray first_note[int(note_array[0])-1] += 1 trans_table[0][int(note_array[0])] += 1 # adding first note to transition table print(trans_table[0][int(note_array[0])]) print(int(note_array[0])) # loop through note array and update trans_table - start with index 1 for i in range(1, len(note_array)): trans_table[int(note_array[i-1])][int(note_array[i])] += 1 return first_note, trans_table trans_table = np.zeros((33,33)) first_noteArray = np.zeros(33) first_noteArray, trans_table = transition_table_valueAdder(notes_values,first_noteArray, trans_table) prob_table = prob_calc(trans_table) prob_table.sum(axis=0) def probability_calc(array): """ Function that takes as input an array and calculates the probability of that event happening for each column INPUTS: numpy array - transition table OUTPUTS: numpy array - transition probability table """ # create empty table dim = len(array) prob_table = np.zeros((dim,dim)) # loop for i in range(dim): total = array[:][i].sum() if total > 0: for j in range(dim): prob_table[j][i] = (array[j][i])/(total) else: prob_table[:][i] = 0 return prob_table def prob_calc(array): new_array = np.nan_to_num(array/array.sum(axis=0)) return (new_array) table_prob = np.load('trans_prob_table.npy') table_trans = np.load('transition_table_rawNums.npy') # + plt.imshow(table_prob) # - plt.imshow(table_trans)
Model_3/Archive/trans_prob_table.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] slideshow={"slide_type": "slide"} # # Gateway Exploration # # In this final segment you can take what you have learned and try it yourself. This segment is displayed in "Notebook Mode" rather than "Presentation Mode." So you will need to scroll down as you explore more content. Notebook mode will allow you to see more content at once. It also allows you to compare and contrast cells and visualizations. # # Here you are free to explore as much as you want. There are lots of suggestions in the text and in comments in the code cells. Feel free to change attributes, code pieces, etc. If a code cell breaks (e.g., you see an error), then use a search engine to look up the error to see if you can try to solve it yourself. Another way to fix problems is to compare your code to the original code, which you can see here: # # https://github.com/hourofci/lessons-dev/blob/master/gateway-lesson/gateway/gateway-exploration.ipynb # # Enjoy two explorations to apply what you learned at a deeper level # 1. Data Wrangling - View, Clean, Extract, and Merge Data # 2. Data Visualization - Making Maps # # So start scrolling down. Explore and try it yourself! # + hide_input=true init_cell=true slideshow={"slide_type": "skip"} tags=["Hide"] # This code cell starts the necessary setup for Hour of CI lesson notebooks. # First, it enables users to hide and unhide code by producing a 'Toggle raw code' button below. # Second, it imports the hourofci package, which is necessary for lessons and interactive Jupyter Widgets. # Third, it helps hide/control other aspects of Jupyter Notebooks to improve the user experience # This is an initialization cell # It is not displayed because the Slide Type is 'Skip' from IPython.display import HTML, IFrame, Javascript, display from ipywidgets import interactive import ipywidgets as widgets from ipywidgets import Layout import getpass # This library allows us to get the username (User agent string) # import package for hourofci project import sys sys.path.append('../../supplementary') # relative path (may change depending on the location of the lesson notebook) import hourofci # Retreive the user agent string, it will be passed to the hourofci submit button agent_js = """ IPython.notebook.kernel.execute("user_agent = " + "'" + navigator.userAgent + "'"); """ Javascript(agent_js) # load javascript to initialize/hide cells, get user agent string, and hide output indicator # hide code by introducing a toggle button "Toggle raw code" HTML(''' <script type="text/javascript" src=\"../../supplementary/js/custom.js\"></script> <input id="toggle_code" type="button" value="Toggle raw code"> ''') # + [markdown] slideshow={"slide_type": "slide"} # ## Setup # As always, you have to import the specific Python packages you'll need. You'll learn more about these in the other lessons, so for now let's import all of the packages that we will use for the Gateway Exploration component. If you want to dig deeper, feel free to search each package to understand what it does and what it can do for you. # # As before, run this code by clicking the Run button left of the code cell. # # Wait for the code to run. This is shown by the asterisk inside the brackets of <pre>In [ ]:</pre>. When it changes to a number and the print output shows up, you're good to go. # + slideshow={"slide_type": "fragment"} tags=["init"] # Run this code by clicking the Run button on the left to import all of the packages from matplotlib import pyplot import pandas import geopandas import os import pprint import IPython from shapely.geometry import Polygon import numpy as np from datetime import datetime print("Modules imported") # + [markdown] slideshow={"slide_type": "slide"} # ## Download COVID-19 Data # This optional code cell will download the US county level data released by the New York Times that we demonstrated earlier. It's found here: https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv. # # The code below gets the data from the URL and puts it into a local file called "us-counties.csv" # # Skip this step if you already downloaded this data in an earlier segment. You can always come back and re-run it if you need to. # + slideshow={"slide_type": "fragment"} # Run this code cell if you have not yet downloaded the Covid-19 data from the New York Times # !wget https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv -O us-counties.csv # - # ## Exploration 1: View, Clean, Extract, and Merge Data # + [markdown] slideshow={"slide_type": "slide"} # ### View the data # Once you have downloaded the data file, you should look at it to make sure it is what you want. # # To do that, we'll convert the downloaded file into a format that our Python program can use. Here we're going to use the dataframe format provided by the Pandas package. # # Recall that dataframes can be though of as two dimensional arrays or spreadsheets. # + slideshow={"slide_type": "fragment"} #Read the data that we downloaded from the NYT into a dataframe covid_counties = pandas.read_csv('./us-counties.csv') # And let's see what it looks like! print(covid_counties) # - # ### Clean the Data # # In large data like this, there are often a few cells scattered around that may cause you problems. Cleaning data is an important and often complex step, it is one part of **data wrangling.** For now, let's just look for the most common problem - empty cells where a value is expected. These are known as null cells and if a number is expected it will show up as NaN (not a number) in your dataframe. # # Let's see if we can find if we have any of these in our data. # # Since we're going to use the "fips" column to group our data, we need to know that there no null cells in that column. (The "FIPS" code is a unique identifier for geographic places. Google it if you want to know more!) # + #Are there NaN cells in the fips column? covid_counties['fips'].isnull().values.any() # + #How many null cells are in the fips column? count_nan = covid_counties['fips'].isnull().sum() print ('Count of rows with null fips codes: ' + str(count_nan)) # - # Ah ha, we found lots of problems in our data! # # Let's see what these rows containing null cells look like. Here we'll make a temporary dataframe that contains the rows with null fips codes. # + covid_counties_clean = covid_counties[covid_counties['fips'].notnull()] print(covid_counties_clean) # + [markdown] slideshow={"slide_type": "slide"} # ### Extract Data # # Since we have a row for each day in the dataset, we will use the **groupby** function to group _daily cases_ by _county_. Since some county names are found in more than one state, we have to group by _county_ and _state_ (as well as the fips code, to be sure). We will add them all up using the **sum** function. # # + slideshow={"slide_type": "fragment"} # In our earlier segment we only looked at cases. # What if we also wanted to look at deaths? # Here we replaced ['cases'] with ['cases', 'deaths'] below. # This will group both cases and deaths by fips, county, and state values. covid_grouped = covid_counties.groupby(['fips','county','state'])['cases', 'deaths'] # Second, add up all the Covid-19 cases using sum covid_total = covid_grouped.sum() #View the result, which should include the columns "fips, county, state, cases, deaths" covid_total # - # Now we could apply some basic arithmetic for the rows using Pandas. # # Let's get the number of deaths per case for each county. This is called the Case Fatality Rather (CFR). We multiply by 100.0 to get the percentage at the end. # # Before you run the code, make sure you understand that we are dividing deaths by cases for each row. # + covid_total['deathpercase']=covid_total['deaths']/covid_total['cases']*100.0 # Print out the new 'covid_total' dataframe with a new 'deathpercase' column covid_total # - # Now that we have our data we can try some basic visualizations. Let's try making a scatter plot of cases on the x-axis and deaths on the y-axis. covid_total.plot.scatter(x='cases', y='deaths') # Here are a few things you can try adding to the scatter function as parameters (remember to use commas to separate each of them). # # ```python # # Change the size of the dots # # s=covid_total['deathpercase'] # # s=covid_total['deathpercase']*2 # ``` # # And, try a hex-bin plot. covid_total.plot.hexbin(x='cases', y='deaths', gridsize=5) # + [markdown] slideshow={"slide_type": "slide"} # ### Merge data # Now we'll load "supplementary/counties_geometry.geojson" into a geodataframe. You loaded this same file in an earlier segment on mapping Covid-19. We will (again) use **merge** to merge these two datasets into a **merged** geodataframe. # + slideshow={"slide_type": "fragment"} counties_geojson = geopandas.read_file("./supplementary/counties_geometry.geojson") # Merge geography (counties_geojson) and covid cases and deaths (covid_total) merged = pandas.merge(counties_geojson, covid_total, how='left', left_on=['NAME','state_name'], right_on = ['county','state']) # Let's take a quick look at our new merged geodataframe merged # + [markdown] slideshow={"slide_type": "slide"} # ## 2. More Mapping # # Now that we have a merged dataset. We can try to create a few different maps. In this Exploration you can try to improve your first map. # # Here is the code from your first map. Run this code and then scroll down. # + slideshow={"slide_type": "fragment"} merged.plot(figsize=(15, 15), column='cases', cmap='OrRd', scheme='fisher_jenks', legend="true", legend_kwds={'loc': 'lower left', 'title':'Number of Confirmed Cases'}) pyplot.title("Number of Confirmed Cases") # - # Below is that code chunk again. Now you can try changing the code to improve the look of your map. There are a lot of options to change. # # <u>If you break something, then just copy and paste the original code above to "reset".</u> # # - *column* represents the column that is being mapped. Change what you are mapping by replacing 'cases' with 'deaths' or 'deathpercase' # # - *cmap* represents the colormap. You can try any number of these by replacing 'OrRd' with: 'Purples' or 'Greens' or 'gist_gray'. There are lot of choices that you can see here: https://matplotlib.org/tutorials/colors/colormaps.html. If you want to learn more about color schemes check out: https://colorbrewer2.org # # - *scheme* represents the scheme for creating classes. Try a few other options by replacing 'fisher_jenks' with: 'natural_breaks' or 'quantiles' # # - *loc* represents the location of your legend. Move your legend by replacing 'lower left' with 'upper right' or 'upper left' # # - *title* represents the text in the legend box. If you changed the column that you are mapping, make sure to change the title too. # # Want to try more? Check out here for even more options # https://geopandas.org/mapping.html#choropleth-maps merged.plot(figsize=(15, 15), column='cases', cmap='OrRd', scheme='fisher_jenks', legend="true", legend_kwds={'loc': 'lower left', 'title':'Number of Confirmed Cases'}) pyplot.title("Number of Confirmed Cases") # # Congratulations! # # # **You have finished an Hour of CI!** # # # But, before you go ... # # 1. Please fill out a very brief questionnaire to provide feedback and help us improve the Hour of CI lessons. It is fast and your feedback is very important to let us know what you learned and how we can improve the lessons in the future. # 2. If you would like a certificate, then please type your name below and click "Create Certificate" and you will be presented with a PDF certificate. # # <font size="+1"><a style="background-color:blue;color:white;padding:12px;margin:10px;font-weight:bold;" href="https://forms.gle/JUUBm76rLB8iYppN7">Take the questionnaire and provide feedback</a></font> # # + hide_input=true slideshow={"slide_type": "-"} tags=["Hide", "Init"] # This code cell has a tag "Hide" (Setting by going to Toolbar > View > Cell Toolbar > Tags) # Code input is hidden when the notebook is loaded and can be hide/show using the toggle button "Toggle raw code" at the top # This code cell loads the Interact Textbox that will ask users for their name # Once they click "Create Certificate" then it will add their name to the certificate template # And present them a PDF certificate from PIL import Image from PIL import ImageFont from PIL import ImageDraw from ipywidgets import interact def make_cert(learner_name): cert_filename = 'hourofci_certificate.pdf' img = Image.open("../../supplementary/hci-certificate-template.jpg") draw = ImageDraw.Draw(img) cert_font = ImageFont.truetype('../../supplementary/cruft.ttf', 150) w,h = cert_font.getsize(learner_name) draw.text( xy = (1650-w/2,1100-h/2), text = learner_name, fill=(0,0,0),font=cert_font) img.save(cert_filename, "PDF", resolution=100.0) return cert_filename interact_cert=interact.options(manual=True, manual_name="Create Certificate") @interact_cert(name="Your Name") def f(name): print("Congratulations",name) filename = make_cert(name) print("Download your certificate by clicking the link below.") # - # <font size="+1"><a style="background-color:blue;color:white;padding:12px;margin:10px;font-weight:bold;" href="hourofci_certificate.pdf?download=1" download="hourofci_certificate.pdf">Download your certificate</a></font>
gateway-lesson/gateway/gateway-exploration.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="EEdE1SZcmHNq" # ## Import usefull packages # + id="0PFD1RXvO2v0" import numpy as np from my_utils import load_data, plot_data, split_humanly, split_humanly_v2, get_cross_validated_subjects from sklearn.model_selection import train_test_split import random from tensorflow import keras import pandas as pd import os # + [markdown] id="_0ItnRarfFws" # ## Fetching the dataset # + id="wnQbyU4TO38S" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607972137394, "user_tz": -210, "elapsed": 99113, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="d3aabac8-f233-4007-d308-443b1f4f9b07" print("It may take 2-3 minutes to load the entire dataset...\n") x, y, names = load_data(path="data/10/", function="difference" , normalization=True) print("Shape of the X:", x.shape) print("Shape of the Y:", y.shape) # + [markdown] id="8Z90r0FCo07l" # ## Splitting humans # # Two ways to split the (patient and control) subjects is implemented: # 1. Split in a balanced way.(approximately the same distribution for patients and control subjects) # 2. unbalanced distribution. # # Obviously the first method is recommended in order to achieve higher accuracy. But it reduces the samples of patient subjects at all.(The dataset which was used for this study is not balanced initially.) # + id="qEsl-nBGonzN" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607972159780, "user_tz": -210, "elapsed": 118558, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="1f5f0441-3594-4002-d955-0f62873dc8e6" print("It may take about 1 minute ...\n") train_x, train_y, valid_x, valid_y, test_x, test_y = split_humanly(x, y, names) print("Shape of the train_x:", train_x.shape, ", shape of the train_y:", train_y.shape) print("Shape of the valid_x:", valid_x.shape, ", shape of the valid_y:", valid_y.shape) print("Shape of the test_x:", test_x.shape, ", shape of the test_y:", test_y.shape) print("number of the training examples: ", train_x.shape[0]) print("length of the sequence: ", train_x.shape[1]) print("number of unique valuese: ", train_x.shape[2]) # + id="PyjtFZ6aPCON" colab={"base_uri": "https://localhost:8080/", "height": 119} executionInfo={"status": "ok", "timestamp": 1603553456761, "user_tz": -210, "elapsed": 3050, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="14732bca-6063-4709-f479-f48a9755776f" train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.40, random_state=42) valid_x, test_x, valid_y, test_y = train_test_split(test_x, test_y, test_size=0.66, random_state=42) # train60 valid14 test26 print("Shape of the train_x:", train_x.shape, ", shape of the train_y:", train_y.shape) print("Shape of the valid_x:", valid_x.shape, ", shape of the valid_y:", valid_y.shape) print("Shape of the test_x:", test_x.shape, ", shape of the test_y:", test_y.shape) print("number of the training examples: ", train_x.shape[0]) print("length of the sequence: ", train_x.shape[1]) print("number of unique valuese: ", train_x.shape[2]) # + [markdown] id="WDRuMrkK-Wcr" # ##Cross validation # # Due to the manuall splitting method which is used for this project, the cross validation is also implemented manually to achive balanced distribution for train and test examples. # + id="nVNOOz0AVEUn" patients, controls = get_cross_validated_subjects(x, y, names, n_folds=10) # + id="BBRLR26M-Z6T" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1605378179552, "user_tz": -210, "elapsed": 30438, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="2ab02ce6-1d16-44fc-a88c-537cf2b4268b" fold = 9 #fold's number subjects_pt_train_all = patients[0] subjects_pt_train_idx_all = patients[1] subjects_pt_test_all = patients[2] subjects_pt_test_idx_all = patients[3] n_fold_train_samples = patients[4] n_fold_test_samples = patients[5] pt_name_train_x = np.asarray(subjects_pt_train_all[n_fold_train_samples[fold] : ]) pt_name_train_y = np.asarray(subjects_pt_train_idx_all[n_fold_train_samples[fold] :], dtype=int) pt_name_test_x = np.asarray(subjects_pt_test_all[n_fold_test_samples[fold]: ]) pt_name_test_y = np.asarray(subjects_pt_test_idx_all[n_fold_test_samples[fold]: ], dtype=int) #n_fold_test_samples[fold + 1] #n_fold_train_samples[fold + 1] subjects_co_train_all = controls[0] subjects_co_train_idx_all = controls[1] subjects_co_test_all = controls[2] subjects_co_test_idx_all = controls[3] n_fold_train_samples = controls[4] n_fold_test_samples = controls[5] co_name_train_x = np.asarray(subjects_co_train_all[n_fold_train_samples[fold]: ]) co_name_train_y = np.asarray(subjects_co_train_idx_all[n_fold_train_samples[fold]: ], dtype=int) co_name_test_x = np.asarray(subjects_co_test_all[n_fold_test_samples[fold]:]) co_name_test_y = np.asarray(subjects_co_test_idx_all[n_fold_test_samples[fold]: ], dtype=int) train_x, train_y, test_x, test_y = split_humanly_v2(x, y, names, pt_name_train_x, pt_name_test_x, pt_name_train_y, pt_name_test_y, co_name_train_x, co_name_test_x, co_name_train_y, co_name_test_y) print("Shape of the train_x:", train_x.shape, ", shape of the train_y:", train_y.shape) print("Shape of the test_x:", test_x.shape, ", shape of the test_y:", test_y.shape) print("number of the training examples: ", train_x.shape[0]) print("length of the sequence: ", train_x.shape[1]) print("number of unique valuese: ", train_x.shape[2]) # + [markdown] id="EC0O217mopnd" # ## Plot a random sample # # A PDF file will be generated in project directory after running this cell. # + id="vcuQCObxQeuR" colab={"base_uri": "https://localhost:8080/", "height": 700} executionInfo={"status": "ok", "timestamp": 1607972487979, "user_tz": -210, "elapsed": 3050, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="9431457f-f5a5-4cef-dadc-ab6840eb815e" rand_ith_sample = random.randint(0, train_x.shape[0]) plot_data(train_x[rand_ith_sample,:,:], train_y[rand_ith_sample,:], save_type='.pdf') # + [markdown] id="GMGJje1INNQ_" # ## Unidirectional LSTM # + id="y_S3OA3IRP8v" model = keras.models.Sequential([ keras.layers.LSTM(64, dropout=0.25, return_sequences=True), keras.layers.LSTM(32, dropout=0.25), keras.layers.Dense(16,activation="relu"), keras.layers.Dense(8,activation="relu"), keras.layers.Dense(4,activation="relu"), keras.layers.Dense(1,activation="sigmoid") ]) # + [markdown] id="72UyP5ZrNPJU" # ## Bidirectional LSTM # + id="4R4WIsQcNYoi" model = keras.models.Sequential([ keras.layers.Bidirectional(keras.layers.LSTM(64, dropout=0.25, return_sequences=True)), keras.layers.Bidirectional(keras.layers.LSTM(32, dropout=0.25)), keras.layers.Dense(16, activation="relu"), keras.layers.Dense(8, activation="relu"), keras.layers.Dense(4,activation="relu"), keras.layers.Dense(1,activation="sigmoid") ]) # + [markdown] id="FLl9T_9aQ9uX" # ## GRU # + id="X12CeFMfRH9a" model = keras.models.Sequential([ keras.layers.GRU(32, dropout=0.25), keras.layers.Dense(16, activation="relu"), keras.layers.Dense(8, activation="relu"), keras.layers.Dense(4,activation="relu"), keras.layers.Dense(1,activation="sigmoid") ]) # + id="XaGeyN41TCdu" model.compile(loss="binary_crossentropy",optimizer="adam",metrics=(["accuracy"])) # binary_crossentropy is a suitable loss for binary classification # + id="PGgq-RERTGlE" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1605379167109, "user_tz": -210, "elapsed": 987535, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="8d6e543e-77ed-4a7d-f95c-9601eb8eb4d3" history = model.fit(train_x,train_y,epochs=150,validation_data=(test_x,test_y)) # training based on X_tr and y_tr using X_val and y_val to stop the learning procedure # + id="I3sMG83LWNIG" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1605379429546, "user_tz": -210, "elapsed": 1106, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="21272bc1-4f40-4384-cea6-ddd6a7db7237" model.summary() exp = "exp84-bidirectional-time_slice:15-all_sensors-fold09/" os.mkdir('weights/' + exp) model.save_weights('weights/' + exp + exp.split("/")[0]) from contextlib import redirect_stdout with open('weights/'+ exp + 'modelsummary.txt', 'w') as f: with redirect_stdout(f): model.summary() # + id="BMq8lvXKTUeG" colab={"base_uri": "https://localhost:8080/", "height": 364} executionInfo={"status": "ok", "timestamp": 1605379432181, "user_tz": -210, "elapsed": 1562, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="d385e6dc-a211-4776-f8be-442db54c195a" pd.DataFrame(history.history).plot() # to plot changing error in respect to iteration number # + [markdown] id="L3yvYvmWmbsQ" # ## Evaluation # + id="n-ozhv9pVzoC" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1605379452692, "user_tz": -210, "elapsed": 1508, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="8e5bddc6-4d01-4942-b6c4-c5dd795fff93" exp = "exp84-bidirectional-time_slice:15-all_sensors-fold09/" model.load_weights('weights/' + exp + exp.split("/")[0]) r = model.evaluate(test_x,test_y) # + id="5I7Gx2CIFI2Y" from keras import backend as K def recall_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def f1_m(y_true, y_pred): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon())) def accuracy_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) true_negatives = K.sum(K.round(K.clip((1-y_true) * (1-y_pred), 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) acc = (true_positives+true_negatives) / (len(y_true) + K.epsilon()) return acc # + id="iS4InwSsW6-Z" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1605379461907, "user_tz": -210, "elapsed": 6408, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgLAI7Z9KOqdQ2WNfnjME1NXe3Ce4d8DfF93c3P=s64", "userId": "07899218751603326409"}} outputId="212d339a-6156-4078-c47a-1a9c3994dd9a" results = model.predict(train_x) print("train recall:", recall_m(train_y, results)) print("train precision:", precision_m(train_y.astype(np.float32), results.astype(np.float32))) print("train accuracy:", accuracy_m(train_y.astype(np.float32), results.astype(np.float32))) results = model.predict(test_x) print("\ntest recall", recall_m(test_y, results)) print("test precision", precision_m(test_y.astype(np.float32), results.astype(np.float32))) print("test accuracy", accuracy_m(test_y.astype(np.float32), results.astype(np.float32))) # + id="hJno0yBCRGmu"
Parkinson.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 from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report, confusion_matrix from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import MinMaxScaler import scikitplot.metrics as skplt import joblib d = {'NAG':0, 'CAG':1, 'OAG':2} eng_train = pd.read_csv("w2v.csv") whole_data = pd.read_csv("Data/cleaned english.csv") target = np.array([d[i] for i in whole_data["Sub-task A"]]) X = eng_train.values from collections import Counter Counter(target) eng_train.head() X_train,X_test,Y_train,Y_test = train_test_split(X, target,test_size=0.25,random_state=0) clf = GaussianNB(var_smoothing=0.2) clf.fit(X_train, Y_train) Y_pred = clf.predict(X_test) print(classification_report(Y_test,Y_pred)) print(confusion_matrix(Y_test,Y_pred)) clf = SVC(C=1, gamma='auto', kernel='rbf', probability=True) clf.fit(X_train, Y_train) Y_pred = clf.predict(X_test) print(classification_report(Y_test,Y_pred)) print(confusion_matrix(Y_test,Y_pred)) clf = LogisticRegression() clf.fit(X_train, Y_train) Y_pred = clf.predict(X_test) print(classification_report(Y_test,Y_pred)) print(confusion_matrix(Y_test,Y_pred)) clf = MultinomialNB() scaler = MinMaxScaler() X_transformed = scaler.fit_transform(X) X_train_tf,X_test_tf,Y_train_tf,Y_test_tf = train_test_split(X_transformed, target,test_size=0.25,random_state=0) clf.fit(X_train_tf, Y_train_tf) Y_pred = clf.predict(X_test_tf) print(classification_report(Y_test_tf,Y_pred)) print(confusion_matrix(Y_test_tf,Y_pred)) def run_the_mn_models(model, X_train, X_test, Y_tr, Y_te): X_train_text_df, X_test_text_df, y_train, y_test = X_train, X_test, Y_tr, Y_te if model == 'mnb1': mn_params = { 'fit_prior': [True], 'alpha': [0, 0.5, 1]} M = GridSearchCV(MultinomialNB(), mn_params, cv = 5, verbose = 1, n_jobs = -1) elif model == 'mnb2': mn_params = { 'fit_prior': [False], 'alpha': [0, 0.5, 1]} M = GridSearchCV(MultinomialNB(), mn_params, cv = 5, verbose = 1, n_jobs = -1) else: print('There is an error.') M.fit(X_train_text_df, y_train) print(f'Train score = {M.score(X_train_text_df, y_train)}') print(f'Test score = {M.score(X_test_text_df, y_test)}') predictions = M.predict(X_test_text_df) predictions_train = M.predict(X_train_text_df) print('--------') print(skplt.plot_confusion_matrix(y_test, predictions)) print(f'Best params = {M.best_params_}') print('----F1 Score, Recall, Precision----') # print precision, recall, F1-score per each class/tag print(classification_report(y_test, predictions)) run_the_mn_models("mnb1", X_train_tf, X_test_tf, Y_train_tf, Y_test_tf) # + def run_the_lr_models(model, X_train, X_test, Y_tr, Y_te): X_train_text_df, X_test_text_df, y_train, y_test = X_train, X_test, Y_tr, Y_te if model == 'lr1': lr_1_params = { 'penalty': ['l1'], 'C': [1, 1.5, 2, 2.5], 'class_weight': ['balanced'], 'warm_start': [True, False], 'random_state': [42], 'solver': ['liblinear']} M = GridSearchCV(LogisticRegression(), lr_1_params, cv = 5, verbose = 1, n_jobs = -1) elif model == 'lr2': lr_2_params = { 'penalty': ['l2'], 'C': [1, 1.5, 2, 2.5], 'class_weight': ['balanced'], 'warm_start': [True, False], 'random_state': [42], 'solver': ['lbfgs', 'liblinear']} M = GridSearchCV(LogisticRegression(), lr_2_params, cv = 5, verbose = 1, n_jobs = -1) else: print('There is an error.') M.fit(X_train_text_df, y_train) print(f'Train score = {M.score(X_train_text_df, y_train)}') print(f'Test score = {M.score(X_test_text_df, y_test)}') predictions = M.predict(X_test_text_df) predictions_train = M.predict(X_train_text_df) print('--------') print(skplt.plot_confusion_matrix(y_test, predictions)) print(f'Best params = {M.best_params_}') print('----F1 Score, Recall, Precision----') # print precision, recall, F1-score per each class/tag print(classification_report(y_test, predictions)) # - run_the_lr_models("lr2", X_train, X_test, Y_train, Y_test) # + def run_the_sv_models(model, X_train, X_test, Y_tr, Y_te): X_train_text_df, X_test_text_df, y_train, y_test = X_train, X_test, Y_tr, Y_te if model == 'sv1': sv_params = { 'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000] } M = GridSearchCV(SVC(probability=True), sv_params, cv = 5, verbose = 1, n_jobs = -1) elif model == 'sv2': sv_params = { 'kernel': ['rbf'], 'gamma': [0.01, 1, 10, 100], 'C': [1, 10, 100, 1000] } M = GridSearchCV(SVC(probability=True), sv_params, cv = 5, verbose = 1, n_jobs = -1) M.fit(X_train_text_df, y_train) #save in picle file joblib.dump(M, "SVM_TFIDF.pkl") print(f'Train score = {M.score(X_train_text_df, y_train)}') print(f'Test score = {M.score(X_test_text_df, y_test)}') predictions = M.predict(X_test_text_df) predictions_train = M.predict(X_train_text_df) print('--------') print(skplt.plot_confusion_matrix(y_test, predictions)) print(f'Best params = {M.best_params_}') print('----F1 Score, Recall, Precision----') # print precision, recall, F1-score per each class/tag print(classification_report(y_test, predictions)) # print('----ROC AUC CURVE SCORE----') # print("ROC AUC CURVE SCORE FOR TEST: ",roc_auc_score(y_test, predictions)) # print("ROC AUC CURVE SCORE FOR TRAIN: ",roc_auc_score(y_train, predictions_train)) # - run_the_sv_models("sv1", X_train, X_test, Y_train, Y_test)
Data Models/w2v.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] slideshow={"slide_type": "slide"} # # Introdução ao Firedrake # # &nbsp; # # ## Parte 2: Elasticidade Linear # # &nbsp; # # Ministrante: **<NAME> (LNCC/ESSS)** # &nbsp; # # Encontro Acadêmico de Modelagem Computacional - XV EAMC (2022) # - # <tr> # <td> <img src="../img/logo_eamc.png" alt="Drawing" style="width: 200px;"/> </td> # <td> <img src="../img/banner.png" alt="Drawing" style="width: 550px;"/> </td> # </tr> # + [markdown] slideshow={"slide_type": "subslide"} # ## Sumário # # * Solucionar com FEM o problema da Elasticidade Linear para os deslocamentos (primal) # * Novas dicas e funcionalidades # + [markdown] slideshow={"slide_type": "slide"} # # Elasticidade Linear # + [markdown] slideshow={"slide_type": "subslide"} # ## Problema-modelo # # A elasticidade linear é um modelo que descreve algumas situações de pequenas deformações. O objetivo aqui é demonstrar como solucionar um problema em que a incógnita é um vetor (e.g., campo de deslocamento). # # ### Forma forte # # Vamos considerar o caso de pequenas deformações elásticas isotrópicas para fins didáticos. Dessa forma, a equação do momento linear de Cauchy se resume a: # # \begin{equation} # \begin{aligned} # -\nabla \cdot \sigma &=f \text { em } \Omega \\[0.5em] # \sigma(u) &:=\lambda \operatorname{tr}(\varepsilon(u)) I+2 \mu \varepsilon(u) \\[0.5em] # \varepsilon(u) &:=\frac{1}{2}\left(\nabla u+(\nabla u)^{\top}\right) # \end{aligned} # \end{equation} # # Note que a equação é também vetorial, $f: \Omega \to \mathbb{R}^n$. # + [markdown] slideshow={"slide_type": "subslide"} # ### Forma fraca # # Após algumas manipulações (em especial, o produto interno de um tensor simétrico com um antissimétrico é nulo), temos as formas: # # \begin{equation} # \begin{aligned} # a(u, v) &:=\int_{\Omega} \sigma(u): \varepsilon(u) \mathrm{~d} x \\ # L(v) &:=\int_{\Omega} f \cdot v \mathrm{~d} x+\int_{\Gamma_{T}} T \cdot v \mathrm{~d} s # \end{aligned} # \end{equation} # # E o problema variacional é dado por: # # \begin{equation} # a(u, v) = L(v) # \end{equation} # # **Note** que $u$ e $v$ são campos vetoriais! Portanto e naturalmente, pertecem a espaços de funções vetoriais. # + [markdown] slideshow={"slide_type": "subslide"} # ## Implementação # # Temos agora todos os requisitos para a implementação. # # ### Considerações do modelo # # * Vamos considerar o domínio 2D alongado (barra): $\Omega = [0, L_x] \times [0, L_y]$, com $L_x = 1$ e $L_y = 0.1$ em metros. # # * Condições de contorno: barra fixada nas duas extremidades. Portanto, $u_x = u_y = 0$ nas duas extremidades. # # * Densidade do material $\rho = 0.01$ (kg / m$^3$) e gravidade $g = 9.8$ (m / s$^2$) # # * Parâmetros do material: $\lambda = 0.4$ e $\mu = 1$. # + [markdown] slideshow={"slide_type": "subslide"} # ### Importando o Firedrake # # Como de costume: # + import os os.environ["OMP_NUM_THREADS"] = "1" # necessário para o Firedrake from firedrake import * import matplotlib.pyplot as plt # + [markdown] slideshow={"slide_type": "subslide"} # ### Definindo a malha # # Parece esse problema, podemos usar uma função built-in do Firedrake. # - Lx, Ly = 1.0, 0.1 num_elements_x, num_elements_y = 20, 20 mesh = RectangleMesh(num_elements_x, num_elements_y, Lx, Ly, quadrilateral=True) # + [markdown] slideshow={"slide_type": "subslide"} # ### Funções e seu Espaço # # Neste caso, o espaço de função é **vetorial**. Não há muitas diferenças, agora os graus de liberdade são para cada componente do vetor, e esses, por sua vez, pertecem ao espaço de função escalar relacionado. # + degree = 1 family = "Lagrange" V = VectorFunctionSpace(mesh, family, degree) u = TrialFunction(V) v = TestFunction(V) # + [markdown] slideshow={"slide_type": "subslide"} # ### Parâmetros do material # # Apenas atribuindo os valores que adotamos para esse problema: # - rho = Constant(0.01) g = Constant(9.8) f = as_vector([0, -rho * g]) # poderia ser Constant([0, -rho * g]) mu = Constant(1) lambda_ = Constant(0.4) # + [markdown] slideshow={"slide_type": "subslide"} # ### Equações constitutivas # # Vamos agora definir $\varepsilon(u)$ e $\sigma(u)$, de forma que não precisamos abrir suas contas na formulação variacional: # + [markdown] cell_style="split" # \begin{equation} # \begin{aligned} # \varepsilon(u) &:=\frac{1}{2}\left(\nabla u+(\nabla u)^{\top}\right) \\[0.5em] # \sigma(u) &:=\lambda \operatorname{tr}(\varepsilon(u)) I+2 \mu \varepsilon(u) # \end{aligned} # \end{equation} # + cell_style="split" Id = Identity(mesh.geometric_dimension()) # tensor identidade def epsilon(u): return (1. / 2.) * (grad(u) + grad(u).T) def sigma(u): return lambda_ * div(u) * Id + 2 * mu * epsilon(u) # - # Note que poderíamos fazer: def epsilon(u): return sym(grad(u)) # + [markdown] slideshow={"slide_type": "subslide"} # ### Formulação Variacional # # Agora, podemos escrever a formulação variacional sem dificuldades: # + [markdown] cell_style="split" # \begin{equation} # \begin{aligned} # a(u, v) &:=\int_{\Omega} \sigma(u): \varepsilon(u) \mathrm{~d} x \\ # L(v) &:=\int_{\Omega} f \cdot v \mathrm{~d} x+\int_{\Gamma_{T}} T \cdot v \mathrm{~d} s # \end{aligned} # \end{equation} # + cell_style="split" a = inner(sigma(u), epsilon(v)) * dx L = dot(f, v) * dx # note o produto interno # - # Por enquanto, vamos desconsiderar qualquer tração, temos apenas o efeito da força de corpo (gravidade). # + [markdown] slideshow={"slide_type": "subslide"} # ### Condições de contorno # # Temos a condição de contorno como barra fixa nas extremidades: # - ux_bc, uy_bc = 0.0, 0.0 bcs = DirichletBC(V, as_vector([ux_bc, uy_bc]), [1, 2]) # + [markdown] slideshow={"slide_type": "subslide"} # ### Montando o Problema Variacional e seu solver # # Sem grandes diferenças para outras casos, definimos o problema variacional: # - u_h = Function(V) # solve(a == L, u_h, bcs=bcs) # não é boa prática, tem overhead elasticity_problem = LinearVariationalProblem(a, L, u_h, bcs=bcs) # E seu solver associado (agora com exemplo usando o MUMPS ou GMRES): # + cell_style="split" solver_parameters = { "ksp_monitor": None, "ksp_converged_reason": None, "ksp_view": None, "mat_type": "aij", "ksp_type": "gmres", "pc_type": "ilu", 'ksp_rtol': 1e-8, 'ksp_max_it': 2000 } # + cell_style="split" solver_parameters = { "ksp_monitor": None, "ksp_type": "preonly", "pc_type": "lu", "pc_factor_mat_solver_type": "mumps", } # - elasticity_solver = LinearVariationalSolver(elasticity_problem, solver_parameters=solver_parameters) # + [markdown] slideshow={"slide_type": "subslide"} # ### Solucionado # # Executando o solver: # - elasticity_solver.solve() # + [markdown] slideshow={"slide_type": "subslide"} # ### Visualizando alguns resultados # # Primeiro de tudo, vamos verificar o campo de deslocamento e seus componentes: # + fig, axes = plt.subplots(figsize=(20, 2)) collection = quiver(u_h, axes=axes) fig.colorbar(collection) axes.set_aspect("equal") plt.xlabel('x [L]') plt.ylabel('y [L]') plt.show() # + cell_style="split" fig, axes = plt.subplots(figsize=(10, 2)) # Componente x collection = tripcolor(u_h.sub(0), axes=axes) fig.colorbar(collection) axes.set_aspect("equal") plt.xlabel('x [L]') plt.ylabel('y [L]') axes.set_xlim([0, 1]) plt.show() # + cell_style="split" fig, axes = plt.subplots(figsize=(10, 2)) # Componente y collection = tripcolor(u_h.sub(1), axes=axes) fig.colorbar(collection) axes.set_aspect("equal") plt.xlabel('x [L]') plt.ylabel('y [L]') axes.set_xlim([0, 1]) plt.show() # + [markdown] slideshow={"slide_type": "subslide"} # Agora podemos ver a deformação na barra vendo a malha antes e depois. # # Vamos deslocar a malha com o campo de deslocamento obtido: # - original_mesh = interpolate(SpatialCoordinate(mesh), V) displaced_coordinates = interpolate(original_mesh + u_h, V) displaced_mesh = Mesh(displaced_coordinates) # + [markdown] cell_style="split" # Antes: # + [markdown] cell_style="split" # Depois: # + cell_style="split" fig, axes = plt.subplots(figsize=(8, 6)) triplot(mesh, axes=axes) axes.set_aspect("equal") # Setting the xy-labels plt.xlabel('x [L]') plt.ylabel('y [L]') # Displaying in the screen plt.tight_layout() plt.show() # + cell_style="split" fig, axes = plt.subplots(figsize=(8, 6)) triplot(displaced_mesh, axes=axes) axes.set_aspect("equal") # Setting the xy-labels plt.xlabel('x [L]') plt.ylabel('y [L]') # Displaying in the screen plt.tight_layout() plt.show()
notebooks/Parte 2 - Elasticidade 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 # --- # # **Bayesian regression** # # Notebook version: 1.0 (Oct 01, 2015) # # Author: <NAME> (<EMAIL>) # # Changes: v.1.0 - First version # # Pending changes: * Include regression on the stock data # + # Import some libraries that will be necessary for working with data and displaying plots # To visualize plots in the notebook # %matplotlib inline import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy.io # To read matlab files import pylab # - # # 3. Bayesian regression # # In the previous session we tackled the problem of fitting the following model using a LS criterion: # # $${\hat s}({\bf x}) = f({\bf x}) = {\bf w}^\top {\bf z}$$ # # where ${\bf z}$ is a vector with components which can be computed directly from the observed variables. Such model is includes a linear regression problem, where ${\bf z} = [1; {\bf x}]$, as well as any other non-linear model as long as it can be expressed as a <i>"linear in the parameters"</i> model. # # The LS solution was defined as the one minimizing the square of the residuals over the training set $\{{\bf x}^{(k)}, s^{(k)}\}_{k=1}^K$. As a result, a single parameter vector ${\bf w}^*$ was obtained, and correspondingly a single regression curve. # # In this session, rather than trying to obtain the best single model, we will work with a family of models or functions, and model the problem probabilistically, so that we can assign a probability value to each of the possible functions. # ## 3.1 Maximum Likelihood estimation of the weights # # ### 3.1.1 Limitations of the LS approach. The need for assumptions # # Consider the same regression task of the previous session. We have a training dataset consisting of 15 points which are given, and depict the regression curves that would be obtained if adding an additional point at a fixed location, depending on the target value of that point: # # (You can run this code fragment several times, to check also the changes in the regression curves between executions, and depending also on the location of the training points) # + n_points = 15 n_grid = 200 frec = 3 std_n = 0.2 n_val_16 = 5 degree = 12 X_tr = 3 * np.random.random((n_points,1)) - 0.5 S_tr = - np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1) X_grid = np.linspace(-.5,2.5,n_grid) S_grid = - np.cos(frec*X_grid) #Noise free for the true model X_16 = .3 * np.ones((n_val_16,)) S_16 = np.linspace(np.min(S_tr),np.max(S_tr),n_val_16) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(X_tr,S_tr,'b.',markersize=10) ax.plot(X_16,S_16,'ro',markersize=6) ax.plot(X_grid,S_grid,'r-',label='True model') for el in zip(X_16,S_16): #Add point to the training set X_tr_iter = np.append(X_tr,el[0]) S_tr_iter = np.append(S_tr,el[1]) #Obtain LS regression coefficients and evaluate it at X_grid w_LS = np.polyfit(X_tr_iter, S_tr_iter, degree) S_grid_iter = np.polyval(w_LS,X_grid) ax.plot(X_grid,S_grid_iter,'g-') ax.set_xlim(-.5,2.5) ax.set_ylim(S_16[0]-2,S_16[-1]+2) ax.legend(loc='best') # - # - You can control the degree of the polynomia, and check that when the degree is set to 15 (16 weights) all points will be fitted perfectly # - It seems obvious that we have not solved the problem ... # * The regression curves overfit the training data # * The regression curves change a lot when varying the label of just one pattern # # The key missing ingredient is assumptions !! # ### Open questions # # - Do we think that all models are equally probable... before we see any data? What does the term <i>model probability</i> mean? # # - Do we need to choose a single "best" model or can we consider several simultaneously? # # - Perhaps our training targets are contaminated with noise. What to do? # # We will start postulating a <i>generative model</i> for the training data that includes the presence of noise contaminating the targets, and work on this model to partly answer the other two questions. # ### 3.1.2 Generative model # # Denoting by $f({\bf x}) = {{\bf w}}^\top {\bf z}$ the true function that we would like to obtain, we could assume that the observations in the training set are obtained as noisy values of the output of such function, i.e., # # $$s^{(k)} = f({\bf x}^{(k)}) + \varepsilon^{(k)}$$ # # We will further characterize the noise values as i.i.d. and normally distributed, with mean zero, and variance $\sigma_\varepsilon^2$, i.e., # # $$\varepsilon \sim {\cal N}\left(0, \sigma_\varepsilon^2\right)$$ # ### 3.1.3 The maximum likelihood solution # # - Joint distribution of the noise samples, ${\pmb \varepsilon} = \left[\varepsilon^{(1)}, \dots, \varepsilon^{(K)}\right]^\top$: # # $${\pmb \varepsilon} \sim \left( {\bf 0}, \sigma_{\varepsilon}^2 {\bf I}\right) \;\;\; p({\pmb \varepsilon}) = \left(\frac{1}{\sqrt{2\pi \sigma_{\varepsilon}^2}}\right)^K \exp\left(- \frac{{\pmb \varepsilon}^\top {\pmb \varepsilon}}{2 \sigma_{\varepsilon}^2}\right)$$ # # # - Denoting ${\bf s} = \left[s^{(1)}, \dots, s^{(K)} \right]^\top$ and ${\bf f} = \left[ f({\bf x}^{(1)}), \dots,f({\bf x}^{(K)})\right]^\top$, we have # # $${\bf s} = {\bf f} + {\pmb \varepsilon}$$ # # - Conditioning on the values of the target function, ${\bf f}$, the pdf of the available targets is obtained as a shifted version of the distribution of the noise. More precisely: # # \begin{align}p({\bf s}|{\bf f}) & = \left(\frac{1}{\sqrt{2\pi \sigma_{\varepsilon}^2}}\right)^K \exp\left(- \frac{\|{\bf s} - {\bf f}\|^2}{2 \sigma_{\varepsilon}^2}\right) \end{align} # # # - For the particular parametric selection of $f({\bf x})$, ${\bf f} = {\bf Z} {\bf w}$, conditioning on ${\bf f}$ is equivalent to conditioning on ${\bf w}$, so that: # # $$p({\bf s}|{\bf f}) = p({\bf s}|{\bf w}) = \left(\frac{1}{\sqrt{2\pi \sigma_{\varepsilon}^2}}\right)^K \exp\left(- \frac{\|{\bf s} - {\bf Z}{\bf w}\|^2}{2 \sigma_{\varepsilon}^2}\right)$$ # # # - The previous expression represents the probability of the observed targets given the weights, and is also known as the likelihood of the weights for a particular training set. # # # The <b>maximum likelihood</b> solution is then given by: # # $${\bf w}_{ML} = \arg \max_{\bf w} p({\bf s}|{\bf w}) = \arg \min_{\bf w} \|{\bf s} - {\bf Z}{\bf w}\|^2$$ # # ### 3.1.4 Multiple explanations of the data # # With an additive Gaussian independent noise model, the maximum likelihood and the least squares solutions are the same. We have not improved much ... # # However, we have already formulated the problem in a probabilistic way. This opens the door to reasoning in terms of a set of possible explanations, not just one. We believe more than one of our models could have generated the data. # # - We do not believe all models are equally likely to have generated the data # - We may <b>believe</b> that a simpler model is more likely than a complex one # ## 3.2 Bayesian Inference # # ### 3.2.1 Posterior distribution of weights # # - If we express our <i>a priori</i> belief of models using a prior distribution $p({\bf f})$, then we can infer the <i>a posteriori</i> distribution using Bayes' rule: # # $$p({\bf f}|{\bf s}) = \frac{p({\bf s}|{\bf f})~p({\bf f})}{p({\bf s})}$$ # # In the previous expression: # * $p({\bf s}|{\bf f})$: is the likelihood function # * $p({\bf f})$: is the <i>prior</i> distribution of the models (assumptions are needed here) # * $p({\bf s})$: is the <i>marginal</i> distribution of the observed data, which could be obtained integrating the numerator over all possible models. However, we normally do not need to explicitly compute $p({\bf s})$ # # # - For the parametric model ${\bf f} = {\bf Z} {\bf w}$, the previous expressions become: # # $$p({\bf w}|{\bf s}) = \frac{p({\bf s}|{\bf w})~p({\bf w})}{p({\bf s})}$$ # # Where: # * $p({\bf s}|{\bf w})$: is the likelihood function # * $p({\bf w})$: is the <i>prior</i> distribution of the weights (assumptions are needed here) # * $p({\bf s})$: is the <i>marginal</i> distribution of the observed data, which could be obtained integrating # ### 3.2.2 Maximum likelihood vs Bayesian Inference. Making predictions # # - Following a <b>ML approach</b>, we retain a single model, ${\bf w}_{ML} = \arg \max_{\bf w} p({\bf s}|{\bf w})$. Then, the predictive distribution of the target value for a new point would be obtained as: # # $$p({s^*}|{\bf w}_{ML},{\bf x}^*) $$ # # For the generative model of Section 3.1.2 (additive i.i.d. Gaussian noise), this distribution is: # # $$p({s^*}|{\bf w}_{ML},{\bf x}^*) = \frac{1}{\sqrt{2\pi\sigma_\varepsilon^2}} \exp \left(-\frac{\left(s^* - {\bf w}_{ML}^\top {\bf z}^*\right)^2}{2 \sigma_\varepsilon^2} \right)$$ # # * The mean of $s^*$ is just the same as the prediction of the LS model, and the same uncertainty is assumed independently of the observation vector (i.e., the variance of the noise of the model). # # * If a single value is to be kept, we would probably keep the mean of the distribution, which is equivalent to the LS prediction. # # # - Using <b>Bayesian inference</b>, we retain all models. Then, the inference of the value $s^* = s({\bf x}^*)$ is carried out by mixing all models, according to the weights given by the posterior distribution. # # \begin{align}p({s^*}|{\bf x}^*,{\bf s}) & = \int p({s^*},{\bf w}~|~{\bf x}^*,{\bf s}) d{\bf w} \\ # & = \int p({s^*}~|~{\bf w},{\bf x}^*,{\bf s}) p({\bf w}~|~{\bf x}^*,{\bf s}) d{\bf w} \\ # & = \int p({s^*}~|~{\bf w},{\bf x}^*) p({\bf w}~|~{\bf s}) d{\bf w}\end{align} # # where: # # * $p({s^*}|{\bf w},{\bf x}^*) = \displaystyle\frac{1}{\sqrt{2\pi\sigma_\varepsilon^2}} \exp \left(-\frac{\left(s^* - {\bf w}^\top {\bf z}^*\right)^2}{2 \sigma_\varepsilon^2} \right)$ # * $p({\bf w}~|~{\bf s})$: Is the posterior distribution of the weights, that can be computed using Bayes' Theorem. # ### 3.2.3 Example: Selecting a Gaussian prior for the weights # # #### Prior distribution of the weights # # In this section, we consider a particular example in which we assume the following prior for the weights: # # $${\bf w} \sim {\cal N}\left({\bf 0},{\pmb \Sigma}_{p} \right)$$ # # The following figure shows functions which are generated by drawing points from this distribution # + n_points = 15 n_grid = 200 frec = 3 std_n = 0.2 degree = 12 nplots = 6 #Prior distribution parameters sigma_eps = 0.1 mean_w = np.zeros((degree+1,)) sigma_w = 0.3 var_w = sigma_w * np.eye(degree+1) X_tr = 3 * np.random.random((n_points,1)) - 0.5 S_tr = - np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1) X_grid = np.linspace(-.5,2.5,n_grid) S_grid = - np.cos(frec*X_grid) #Noise free for the true model fig = plt.figure() ax = fig.add_subplot(111) ax.plot(X_tr,S_tr,'b.',markersize=10) for k in range(nplots): #Draw weigths fromt the prior distribution w_iter = np.random.multivariate_normal(mean_w,var_w) S_grid_iter = np.polyval(w_iter,X_grid) ax.plot(X_grid,S_grid_iter,'g-') ax.set_xlim(-.5,2.5) ax.set_ylim(S_16[0]-2,S_16[-1]+2) # - # #### Likelihood of the weights # # According to the generative model, ${\bf s} = {\bf Z}{\bf w} + {\pmb \varepsilon}$ # # $${\bf s}~|~{\bf w} \sim {\cal N}\left({\bf Z}{\bf w},\sigma_\varepsilon^2 {\bf I} \right)$$ # # #### Posterior distribution of the weights # # $$p({\bf w}|{\bf s}) = \frac{p({\bf s}|{\bf w})~p({\bf w})}{p({\bf s})}$$ # # Since both $p({\bf s}|{\bf w})$ and $p({\bf w})$ follow a Gaussian distribution, we know also that the joint distribution and the posterior distribution of ${\bf w}$ given ${\bf s}$ are also Gaussian. Therefore, # # $${\bf w}~|~{\bf s} \sim {\cal N}\left({\bar{\bf w}} , {\pmb\Sigma}_{\bf w}\right)$$ # # where the mean and the covariance matrix of the distribution are to be determined. # <b>Exercise:</b> # # Show that the posterior mean and posterior covariance matrix of ${\bf w}$ given ${\bf s}$ are: # # # $${\pmb\Sigma}_{\bf w} = \left[\frac{1}{\sigma_\varepsilon^2} {\bf Z}^{\top}{\bf Z} + {\pmb \Sigma}_p^{-1}\right]^{-1}$$ # # # $${\bar{\bf w}} = {\sigma_\varepsilon^{-2}} {\pmb\Sigma}_{\bf w} {\bf Z}^\top {\bf s}$$ # The following fragment of code draws random vectors from $p({\bf w}|{\bf s})$, and plots the corresponding regression curve along with the training points. Compare these curves with those extracted from the prior distribution of ${\bf w}$. # + n_points = 15 n_grid = 200 frec = 3 std_n = 0.2 degree = 12 nplots = 6 #Prior distribution parameters sigma_eps = 0.1 mean_w = np.zeros((degree+1,)) sigma_p = .3 * np.eye(degree+1) X_tr = 3 * np.random.random((n_points,1)) - 0.5 S_tr = - np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1) X_grid = np.linspace(-.5,2.5,n_grid) S_grid = - np.cos(frec*X_grid) #Noise free for the true model fig = plt.figure() ax = fig.add_subplot(111) ax.plot(X_tr,S_tr,'b.',markersize=10) #Compute matrix with training input data for the polynomial model Z = [] for x_val in X_tr.tolist(): Z.append([x_val[0]**k for k in range(degree+1)]) Z=np.asmatrix(Z) #Compute posterior distribution parameters Sigma_w = np.linalg.inv(np.dot(Z.T,Z)/(sigma_eps**2) + np.linalg.inv(sigma_p)) posterior_mean = Sigma_w.dot(Z.T).dot(S_tr)/(sigma_eps**2) posterior_mean = np.array(posterior_mean).flatten() for k in range(nplots): #Draw weights from the posterior distribution w_iter = np.random.multivariate_normal(posterior_mean,Sigma_w) #Note that polyval assumes the first element of weight vector is the coefficient of #the highest degree term. Thus, we need to reverse w_iter S_grid_iter = np.polyval(w_iter[::-1],X_grid) ax.plot(X_grid,S_grid_iter,'g-') #We plot also the least square solution w_LS = np.polyfit(X_tr.flatten(), S_tr.flatten(), degree) S_grid_iter = np.polyval(w_LS,X_grid) ax.plot(X_grid,S_grid_iter,'m-',label='LS regression') ax.set_xlim(-.5,2.5) ax.set_ylim(S_16[0]-2,S_16[-1]+2) ax.legend(loc='best') # - # #### Posterior distribution of the target # # - Since $f^* = f({\bf x}^*) = [{\bf x}^*]^\top {bf w}$, $f^*$ is also a Gaussian variable whose posterior mean and variance can be calculated as follows: # # $$\mathbb{E}\{{{\bf x}^*}^\top {\bf w}~|~{\bf s}, {\bf x}^*\} = {{\bf x}^*}^\top \mathbb{E}\{{\bf w}|{\bf s}\} = {\sigma_\varepsilon^{-2}} {{\bf x}^*}^\top {\pmb\Sigma}_{\bf w} {\bf Z}^\top {\bf s}$$ # # $$\text{Cov}\left[{{\bf x}^*}^\top {\bf w}~|~{\bf s}, {\bf x}^*\right] = {{\bf x}^*}^\top \text{Cov}\left[{\bf w}~|~{\bf s}\right] {{\bf x}^*} = {{\bf x}^*}^\top {\pmb \Sigma}_{\bf w} {{\bf x}^*}$$ # # # - Therefore, $f^*~|~{\bf s}, {\bf x}^* \sim {\cal N}\left({\sigma_\varepsilon^{-2}} {{\bf x}^*}^\top {\pmb\Sigma}_{\bf w} {\bf Z}^\top {\bf s}, {{\bf x}^*}^\top {\pmb \Sigma}_{\bf w} {{\bf x}^*} \right)$ # # - Finally, for $s^* = f^* + \varepsilon^*$, the posterior distribution is $s^*~|~{\bf s}, {\bf x}^* \sim {\cal N}\left({\sigma_\varepsilon^{-2}} {{\bf x}^*}^\top {\pmb\Sigma}_{\bf w} {\bf Z}^\top {\bf s}, {{\bf x}^*}^\top {\pmb \Sigma}_{\bf w} {{\bf x}^*} + \sigma_\varepsilon^2\right)$ # + n_points = 15 n_grid = 200 frec = 3 std_n = 0.2 degree = 12 nplots = 6 #Prior distribution parameters sigma_eps = 0.1 mean_w = np.zeros((degree+1,)) sigma_p = .5 * np.eye(degree+1) X_tr = 3 * np.random.random((n_points,1)) - 0.5 S_tr = - np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1) X_grid = np.linspace(-.5,2.5,n_grid) S_grid = - np.cos(frec*X_grid) #Noise free for the true model fig = plt.figure() ax = fig.add_subplot(111) ax.plot(X_tr,S_tr,'b.',markersize=10) #Compute matrix with training input data for the polynomial model Z = [] for x_val in X_tr.tolist(): Z.append([x_val[0]**k for k in range(degree+1)]) Z=np.asmatrix(Z) #Compute posterior distribution parameters Sigma_w = np.linalg.inv(np.dot(Z.T,Z)/(sigma_eps**2) + np.linalg.inv(sigma_p)) posterior_mean = Sigma_w.dot(Z.T).dot(S_tr)/(sigma_eps**2) posterior_mean = np.array(posterior_mean).flatten() #Plot the posterior mean #Note that polyval assumes the first element of weight vector is the coefficient of #the highest degree term. Thus, we need to reverse w_iter S_grid_iter = np.polyval(posterior_mean[::-1],X_grid) ax.plot(X_grid,S_grid_iter,'g-',label='Predictive mean, BI') #Plot confidence intervals for the Bayesian Inference std_x = [] for el in X_grid: x_ast = np.array([el**k for k in range(degree+1)]) std_x.append(np.sqrt(x_ast.dot(Sigma_w).dot(x_ast)[0,0])) std_x = np.array(std_x) plt.fill_between(X_grid, S_grid_iter-std_x, S_grid_iter+std_x, alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF', linewidth=4, linestyle='dashdot', antialiased=True) #We plot also the least square solution w_LS = np.polyfit(X_tr.flatten(), S_tr.flatten(), degree) S_grid_iter = np.polyval(w_LS,X_grid) ax.plot(X_grid,S_grid_iter,'m-',label='LS regression') ax.set_xlim(-.5,2.5) ax.set_ylim(S_16[0]-2,S_16[-1]+2) ax.legend(loc='best') # - # Not only do we obtain a better predictive model, but we also have confidence intervals (error bars) for the predictions.
R6.Gaussian_Processes/.ipynb_checkpoints/Bayesian_regression-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.5.0 # language: julia # name: julia-1.5 # --- # # Compare MendelImpute against Minimac4 and Beagle5 on simulated data using Revise using VCFTools using MendelImpute using GeneticVariation using Random using SparseArrays using JLD2, FileIO, JLSO using ProgressMeter using GroupSlices using ThreadPools # using Plots # using ProfileView # + # keep best pair only (8 thread) Random.seed!(2020) d = 1000 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, max_d = d, phase = true); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile, trans=true) # X_complete = convert_gt(Float32, "./compare1/target.vcf.gz", trans=true) n, p = size(X_mendel) # rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # + # keep best pair only (8 thread) Random.seed!(2020) d = 1000 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.jlso" @time ph2 = phase(tgtfile, reffile, outfile = outfile, max_d = d, phase = true); # import imputed result and compare with true # H = convert_ht(Float32, "./compare1/haplo_ref.vcf.gz", trans=true) X1, X2 = convert_compressed(Float32, ph2, H) X_mendel2 = X1 + X2 # X_complete = convert_gt(Float32, "./compare1/target.vcf.gz", trans=true) n, p = size(X_mendel) error_rate = sum(X_mendel2 .!= X_complete) / n / p # - # # Simulate data # # ### Step 0. Install `msprime` # # [msprime download Link](https://msprime.readthedocs.io/en/stable/installation.html). # # Some people might need to activate conda environment via `conda config --set auto_activate_base True`. You can turn it off once simulation is done by executing `conda config --set auto_activate_base False`. # # # ### Step 1. Simulate data in terminal # # ``` # python3 msprime_script.py 4000 10000 5000000 2e-8 2e-8 2019 > full.vcf # ``` # # Arguments: # + Number of haplotypes = 40000 # + Effective population size = 10000 ([source](https://www.the-scientist.com/the-nutshell/ancient-humans-more-diverse-43556)) # + Sequence length = 10 million (same as Beagle 5's choice) # + Rrecombination rate = 2e-8 (default) # + mutation rate = 2e-8 (default) # + seed = 2019 # ### Step 2: Convert simulated haplotypes to reference haplotypes and target genotype files # # + `haplo_ref.vcf.gz`: haplotype reference files # + `target.vcf.gz`: complete genotype information # + `target_masked.vcf.gz`: the same as `target.vcf.gz` except some entries are masked # + records, samples = nrecords("./compare1/full.vcf"), nsamples("./compare1/full.vcf") @show records @show samples; # compute target and reference index tgt_index = falses(samples) tgt_index[samples-999:end] .= true ref_index = .!tgt_index record_index = trues(records) # save all records (SNPs) # create target.vcf.gz and haplo_ref.vcf.gz @time VCFTools.filter("./compare1/full.vcf", record_index, tgt_index, des = "./compare1/target.vcf.gz") @time VCFTools.filter("./compare1/full.vcf", record_index, ref_index, des = "./compare1/haplo_ref.vcf.gz") # import full target matrix. Also transpose so that columns are samples. @time X = convert_gt(Float32, "target.vcf.gz"; as_minorallele=false) X = copy(X') # mask 10% entries p, n = size(X) Random.seed!(123) missingprop = 0.1 X .= ifelse.(rand(Float32, p, n) .< missingprop, missing, X) masks = ismissing.(X) # save X to new VCF file mask_gt("target.vcf.gz", masks, des="target_masked.vcf.gz") # - # # Try compressing haplotype ref panels # compress as jlso d = 1000 reffile = "./compare1/haplo_ref.vcf.gz" tgtfile = "./compare1/target_masked.vcf.gz" outfile = "./compare1/haplo_ref.jlso" @time compress_haplotypes(reffile, tgtfile, outfile, d); # # Haplotype thinning # + # doesn't account for allele freq Random.seed!(2020) width = 512 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming=false, thinning_factor=100, thinning_scale_allelefreq=false, max_haplotypes = 100); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # + # haplopair_thin (scale freq by 1-p), keep = 100 (1 thread) Random.seed!(2020) tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" width = 512 @time hs, ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming=false, thinning_factor=100, thinning_scale_allelefreq=false, max_haplotypes = 100); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) # X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # - # # MendelImpute error # + # keep best pair only (1 thread) Random.seed!(2020) tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" width = 512 @time ph = phase(tgtfile, reffile, outfile = outfile, width = width); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # + # keep best pair only (8 thread) Random.seed!(2020) tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" width = 512 @time ph = phase(tgtfile, reffile, outfile = outfile, width = width); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # - # # Rescreen # + # keep top matching happairs (1 thread) Random.seed!(2020) tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" width = 512 @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming=false, rescreen=true); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # + # Keep a list of top haplotype pairs (1 thread) Random.seed!(2020) tgtfile = "target_masked.vcf.gz" reffile = "haplo_ref.jlso" outfile = "imputed_target.vcf.gz" width = 500 @time ph = phase(tgtfile, reffile, outfile = outfile, width = width); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # + # Keep a list of top haplotype pairs (8 thread) Random.seed!(2020) tgtfile = "target_masked.vcf.gz" reffile = "haplo_ref.jlso" outfile = "imputed_target.vcf.gz" width = 500 @time ph = phase(tgtfile, reffile, outfile = outfile, width = width); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # - # # MendelImpute with intersecting haplotype sets # + # keep best pair only (8 thread) Random.seed!(2020) width = 512 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming = false); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # + # scale by allele freq (8 thread) Random.seed!(2020) width = 512 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming = false, scale_allelefreq=true); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # - # # MendelPhase # + # scale by allele freq (8 thread) Random.seed!(2020) width = 512 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming = false, phase=true); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # - # # Screening flanking windows # + # keep best pair only (8 thread) Random.seed!(2020) width = 512 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming = false); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # - # # Try Lasso # + # keep best pair only (8 thread) Random.seed!(2020) width = 512 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming=false, lasso = 1, max_haplotypes = 100); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # + # keep best pair only (8 thread) Random.seed!(2020) width = 512 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming=false, lasso = 20, max_haplotypes = 100); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # + # scale allele freq Random.seed!(2020) width = 512 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming=false, lasso = 1, max_haplotypes = 100, scale_allelefreq=true); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) # X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # + # scale allele freq Random.seed!(2020) width = 512 tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming=false, lasso = 20, max_haplotypes = 100, scale_allelefreq=true); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) # X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) rm(outfile, force=true) error_rate = sum(X_mendel .!= X_complete) / n / p # - # # Chunking # + # sets num_windows_per_chunks = 10 Random.seed!(2020) tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" width = 512 @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming = false); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # + # default num_windows_per_chunks (i.e. only 1 chunk) Random.seed!(2020) tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" width = 512 @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming = false); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # + # dp and only 1 chunk Random.seed!(2020) tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" width = 512 @time ph = phase(tgtfile, reffile, outfile = outfile, width = width, dynamic_programming = true); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # - # # Beagle 5.1 Error # convert to bref3 (run in terminal) java -jar bref3.18May20.d20.jar haplo_ref.vcf.gz > haplo_ref.bref3 # run beagle 5 (1 thread) run(`java -jar beagle.18May20.d20.jar gt=target_masked.vcf.gz ref=haplo_ref.bref3 out=beagle.result nthreads=1`) # beagle 5.1 error rate X_complete = convert_gt(Float32, "target.vcf.gz") n, p = size(X_complete) X_beagle = convert_gt(Float32, "beagle.result.vcf.gz") error_rate = sum(X_beagle .!= X_complete) / n / p # + # run beagle 5.1 (8 thread) run(`java -jar beagle.18May20.d20.jar gt=./compare1/target_masked.vcf.gz ref=./compare1/haplo_ref.bref3 out=./compare1/beagle.result nthreads=8`) # beagle 5 error rate X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_complete) X_beagle = convert_gt(Float32, "./compare1/beagle.result.vcf.gz") error_rate = sum(X_beagle .!= X_complete) / n / p # - # # Minimac4 error # # Need to first convert reference vcf file to m3vcf using minimac3 (on Hoffman) # # ```Julia # minimac3 = "/u/home/b/biona001/haplotype_comparisons/minimac3/Minimac3/bin/Minimac3" # @time run(`$minimac3 --refHaps haplo_ref.vcf.gz --processReference --prefix haplo_ref`) # ``` # + # run minimac 4 minimac4 = "/Users/biona001/Benjamin_Folder/UCLA/research/softwares/Minimac4/build/minimac4" run(`$minimac4 --refHaps haplo_ref.m3vcf.gz --haps target_masked.vcf.gz --prefix minimac4.result`) X_minimac = convert_gt(Float32, "minimac4.result.dose.vcf.gz", as_minorallele=false) error_rate = sum(X_minimac .!= X_complete) / n / p # - # # BLAS 2 # + # haplopair_thin (doesn't accounts for allele freq), keep = 100 (1 thread) Random.seed!(2020) tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" width = 512 @time hs, ph = phase(tgtfile, reffile, outfile = outfile, width = width, thinning_factor=100, thinning_scale_allelefreq=false); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # - # # BLAS 3 # + # haplopair_thin (doesn't accounts for allele freq), keep = 100 (1 thread) Random.seed!(2020) tgtfile = "./compare1/target_masked.vcf.gz" reffile = "./compare1/haplo_ref.jlso" outfile = "./compare1/imputed_target.vcf.gz" width = 512 @time hs, ph = phase(tgtfile, reffile, outfile = outfile, width = width, thinning_factor=100, thinning_scale_allelefreq=false); # import imputed result and compare with true X_mendel = convert_gt(Float32, outfile) X_complete = convert_gt(Float32, "./compare1/target.vcf.gz") n, p = size(X_mendel) error_rate = sum(X_mendel .!= X_complete) / n / p # -
simulation/compare1.ipynb