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 # language: python # name: python3 # --- import pandas as pd from pandas import DataFrame athlete = pd.read_csv('https://raw.githubusercontent.com/zacharski/ml-class/master/data/athletes.csv', index_col='Name') athletes = athlete[((athlete.Sport == 'Basketball') | (athlete.Sport == 'Gymnastics'))][['Sport', 'Height']] athletes = athletes.sort_index() athlete
labs/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 # --- # <img src="images/usm.jpg" width="480" height="240" align="left"/> # # MAT281 - Laboratorio N°03 # # ## Objetivos de la clase # # * Reforzar los conceptos básicos de pandas. # ## Contenidos # # * [Problema 01](#p1) # # ## Problema 01 # # # <img src="https://imagenes.universia.net/gc/net/images/practicas-empleo/p/pr/pro/profesiones-con-el-avance-de-la-tecnologia.jpg" width="480" height="360" align="center"/> # # # EL conjunto de datos se denomina `ocupation.csv`, el cual contiene información tal como: edad ,sexo, profesión, etc. # # Lo primero es cargar el conjunto de datos y ver las primeras filas que lo componen: import pandas as pd import os # cargar datos df = pd.read_csv(os.path.join("data","ocupation.csv"), sep="|").set_index('user_id') df.head() #limpiamos los datos df1=df[df.notnull().all(axis=1)] print(df1.shape) type(df1['zip_code'][1]) # Se determina que el conjunto de datos no tenía valores nulos. # El objetivo es tratar de obtener la mayor información posible de este conjunto de datos. Para cumplir este objetivo debe resolver las siguientes problemáticas: # 1. ¿Cuál es el número de observaciones en el conjunto de datos? df.shape # Se observa que el número de observaciones del conjunto de datos corresponde a 943 filas. # 2. ¿Cuál es el número de columnas en el conjunto de datos? # Del formato del dataframe vemos que tenemos 4 columnas. # 3. Imprime el nombre de todas las columnas df.columns # 4. Imprima el índice del dataframe df.index # 5. ¿Cuál es el tipo de datos de cada columna? df.dtypes # Observamos que: # - age es de tipo entero # - gender y occupation son de tipo objeto # - zip_code es de tipo objeto por tanto los números en zip_code están definidos como string. # 6. Resumir el conjunto de datos df.describe() # 7. Resume conjunto de datos con todas las columnas df.describe(include='all') # 8. Imprimir solo la columna de **occupation**. df['occupation'] # 9. ¿Cuántas ocupaciones diferentes hay en este conjunto de datos? len(df['occupation'].unique()) # Se determina que hay 21 ocupaciones distintas, donde una categoría es 'otros'. En resumen hay 20 ocupaciones especificas distintas y una categoría 'otros' donde se agrupan todas las ocupaciones distintas a las anteriores 20. # 10. ¿Cuál es la ocupación más frecuente? # De la descripción de los datos se determina que la ocupación más frecuente es la de 'estudiante' con 196 ocurrencias en el conjunto de datos. # 11. ¿Cuál es la edad media de los usuarios? # De la descripcion de la columna edad se determina que la edad media es de 34 años # 12. ¿Cuál es la edad con menos ocurrencia? # + lista_edades=df['age'].unique() #SACAMOS LAS EDADES DISTINTAS DEL CONJUNTO DE DATOS df_age=df['age'] #DEFINIMOS LA COLUMNA DE EDADES DEL CONJUNTO DE DATO edad_menos_frecuente=0 #INICIALIZAMOS LA EDAD MENOS FRECUENTE COMO 0 frecuencia=1000 #DEFINIMOS UNA FRECUENCIA QUE SUPERA EL NÚMERO DE DATOS PARA QUE CAMBIE CON EL PRIMER #CHEQUEO for i in lista_edades: frec=len(df_age[df_age==i]) #PARA CADA EDAD DISTINTA CALCULAMOS EL NÚMERO DE OCURRENCIAS EN EL CONJUNTO DE DATOS if frec<frecuencia: #SE GUARDA EL ELEMENTO CON MENOR FRECUENCIA frecuencia=frec edad_menos_frecuente=i edad_menos_frecuente print("la frecuencia es:", frecuencia) print('la edad menos frecuente es:',edad_menos_frecuente) # - # Del análisis anterior se desprende que la edad menos frecuente es la de 7 años y está tiene solo una ocurrencia el # conjunto de datos.
Lab03/laboratorio_03.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from os.path import join, dirname import datetime import yaml import pandas as pd from scipy.signal import savgol_filter from bokeh.io import curdoc, output_notebook, show from bokeh.themes import Theme from bokeh.layouts import row, column from bokeh.models import (ColumnDataSource, DataRange1d, HoverTool, Slider, Div) from bokeh.palettes import Blues4, brewer from bokeh.plotting import figure, show from content import notes_div, reference_div output_notebook() # + def bkapp(doc): def make_plot(source, title): plot = figure(plot_width=800, tools="", toolbar_location=None, y_range=(0, 1), x_range=(0,N_objects_total)) # plot.title.text = title # plot.line(x='N', y='f', color=Blues4[2], # line_width=4, source=source) names = ['a_part', 'b_part', 'c_part'] labels = ['P(RH)', 'P(G)', 'P(K)'] plot.varea_stack(stackers=names, x='n_prop', color=brewer['Paired'][len(names)], legend_label=labels, source=source) plot.legend.items.reverse() plot.vline_stack( names, x="n_prop", line_width=5, color=brewer['Paired'][len(names)], source=source, alpha=0., ) # add hovertool plot.add_tools(HoverTool(show_arrow=True, line_policy='next', tooltips=[ ('P(K)', '@c_part{0.000}'), ('P(G)', '@b_part{0.000}'), ('P(RH)', '@a_part{0.000}'), ('n/N', '@n_prop{0.000}') ])) # fixed attributes plot.yaxis.axis_label = "f(n) (Expected Recall)" plot.xaxis.axis_label = "Proportion of Recognized Objects [n/N]" plot.axis.axis_label_text_font_style = "bold" plot.x_range = DataRange1d(range_padding=0.0) plot.grid.grid_line_alpha = 0.3 return plot def calculate_recall(N, n, a, b): a_part = 2 * (n / N) * (N - n) / (N - 1) * a b_part = (N - n)/ N * ((N - n - 1)/(N - 1)) / 2 c_part = (n/N) * ((n - 1)/(N - 1)) * b return a_part, b_part, c_part def update_df(N, a, b): df = pd.DataFrame({'N': list(range(int(N + 1)))}) df['n_prop'] = (df['N'] / N) df['a_part'], df['b_part'], df['c_part'] = zip(*df.apply(lambda row: calculate_recall(N, row['N'], a, b), axis=1)) return ColumnDataSource(data=df) def update_plot(attrname, old, new): a = alpha.value b = beta.value title_var_string = f'N={N_objects_total}, α={a:.2f}, β={b:.2f}' plot.title.text = 'Expected Proportion of Correct Inferences ({})'.format(title_var_string) expected_recall = update_df(N_objects_total, a, b) source.data.update(expected_recall.data) N_objects_total = 1000 # n_objects_recognized = Slider(start=10, end=N_objects_total, value=N_objects_total / 2, step=1, title="n Recognized Objects") alpha = Slider(start=0., end=1., value=0.5, step=0.01, title='α (Recognition Validity)') beta = Slider(start=0., end=1., value=0.5, step=0.01, title='β (Knowledge Validity)') source = update_df(N_objects_total, alpha.value, beta.value) title_var_string = f'N={N_objects_total}, α={alpha.value:.2f}, β={beta.value:.2f}' plot = make_plot(source, 'Expected Proportion of Correct Inferences ({})'.format(title_var_string)) alpha.on_change('value', update_plot) beta.on_change('value', update_plot) controls = column(alpha, beta) main_row = row(plot, column(controls, notes_div)) layout = column(main_row, reference_div) # curdoc().add_root(layout) # curdoc().title = "Expected Recall" doc.add_root(layout) doc.theme = Theme(json=yaml.load(""" attrs: Figure: background_fill_color: "#DDDDDD" outline_line_color: white toolbar_location: above height: 500 width: 800 Grid: grid_line_dash: [6, 4] grid_line_color: white """, Loader=yaml.FullLoader)) # - # # The Recognition Heuristic # # ## How Ignorance Makes Us Smart (Goldstein & Gigerenzer, 1999) show(bkapp) # $$f(n) = 2 \left( \frac{n}{N} \right) \left( \frac{N - n}{N-1} \right) \alpha + \left( \frac{N-n}{N} \right) \left( \frac{N - n - 1}{N - 1} \right) \left( \frac{1}{2} \right) + \left( \frac{n}{N} \right) \left( \frac{n - 1}{N-1} \right) \beta$$
Presentation_Notebook.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- #hide from med2nlp.core import * # # med2nlp # # > MED(minimum Effective Dose) to NLP # Tools and tips to make your project a little more MED. # ## Install # `pip install med2nlp` # ## How to use # Every project starts with med, and each topic has its own MED library: 1+1
nbs/index.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 malaya malaya.bump_version text_split = malaya.texts._text_functions.split_into_sentences text_cleaning = malaya.texts._text_functions.summary_textcleaning # + import json files = ['politics.json', 'education.json', 'economy.json', 'business.json'] sentences = [] for file in files: with open(file) as fopen: news = json.load(fopen) for n in news: if len(n['text']) > 50: splitted = text_split(n['text']) sentences.extend(splitted) len(sentences) # - sentences = [text_cleaning(s)[1] for s in sentences] window_size = 4 n_topics = 10 embedding_size = 128 epoch = 5 switch_loss = 2 class LDA2VEC: def __init__( self, num_unique_documents, vocab_size, num_topics, freqs, embedding_size = 128, num_sampled = 40, learning_rate = 1e-3, lmbda = 150.0, alpha = None, power = 0.75, batch_size = 32, clip_gradients = 5.0, **kwargs ): moving_avgs = tf.train.ExponentialMovingAverage(0.9) self.batch_size = batch_size self.freqs = freqs self.sess = tf.InteractiveSession() self.X = tf.placeholder(tf.int32, shape = [None]) self.Y = tf.placeholder(tf.int64, shape = [None]) self.DOC = tf.placeholder(tf.int32, shape = [None]) step = tf.Variable(0, trainable = False, name = 'global_step') self.switch_loss = tf.Variable(0, trainable = False) train_labels = tf.reshape(self.Y, [-1, 1]) sampler = tf.nn.fixed_unigram_candidate_sampler( train_labels, num_true = 1, num_sampled = num_sampled, unique = True, range_max = vocab_size, distortion = power, unigrams = self.freqs, ) self.word_embedding = tf.Variable( tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0) ) self.nce_weights = tf.Variable( tf.truncated_normal( [vocab_size, embedding_size], stddev = tf.sqrt(1 / embedding_size), ) ) self.nce_biases = tf.Variable(tf.zeros([vocab_size])) scalar = 1 / np.sqrt(num_unique_documents + num_topics) self.doc_embedding = tf.Variable( tf.random_normal( [num_unique_documents, num_topics], mean = 0, stddev = 50 * scalar, ) ) self.topic_embedding = tf.get_variable( 'topic_embedding', shape = [num_topics, embedding_size], dtype = tf.float32, initializer = tf.orthogonal_initializer(gain = scalar), ) pivot = tf.nn.embedding_lookup(self.word_embedding, self.X) proportions = tf.nn.embedding_lookup(self.doc_embedding, self.DOC) doc = tf.matmul(proportions, self.topic_embedding) doc_context = doc word_context = pivot context = tf.add(word_context, doc_context) loss_word2vec = tf.reduce_mean( tf.nn.nce_loss( weights = self.nce_weights, biases = self.nce_biases, labels = self.Y, inputs = context, num_sampled = num_sampled, num_classes = vocab_size, num_true = 1, sampled_values = sampler, ) ) self.fraction = tf.Variable(1, trainable = False, dtype = tf.float32) n_topics = self.doc_embedding.get_shape()[1].value log_proportions = tf.nn.log_softmax(self.doc_embedding) if alpha is None: alpha = 1.0 / n_topics loss = -(alpha - 1) * log_proportions prior = tf.reduce_sum(loss) loss_lda = lmbda * self.fraction * prior self.cost = tf.cond( step < self.switch_loss, lambda: loss_word2vec, lambda: loss_word2vec + loss_lda, ) loss_avgs_op = moving_avgs.apply([loss_lda, loss_word2vec, self.cost]) with tf.control_dependencies([loss_avgs_op]): self.optimizer = tf.contrib.layers.optimize_loss( self.cost, tf.train.get_global_step(), learning_rate, 'Adam', clip_gradients = clip_gradients, ) self.sess.run(tf.global_variables_initializer()) def train( self, pivot_words, target_words, doc_ids, num_epochs, switch_loss = 3 ): from tqdm import tqdm temp_fraction = self.batch_size / len(pivot_words) self.sess.run(tf.assign(self.fraction, temp_fraction)) self.sess.run(tf.assign(self.switch_loss, switch_loss)) for e in range(num_epochs): pbar = tqdm( range(0, len(pivot_words), self.batch_size), desc = 'minibatch loop', ) for i in pbar: batch_x = pivot_words[ i : min(i + self.batch_size, len(pivot_words)) ] batch_y = target_words[ i : min(i + self.batch_size, len(pivot_words)) ] batch_doc = doc_ids[ i : min(i + self.batch_size, len(pivot_words)) ] _, cost = self.sess.run( [self.optimizer, self.cost], feed_dict = { self.X: batch_x, self.Y: batch_y, self.DOC: batch_doc, }, ) pbar.set_postfix(cost = cost, epoch = e + 1) # + import random from sklearn.utils import shuffle def skipgrams( sequence, vocabulary_size, window_size = 4, negative_samples = 1.0, shuffle = True, categorical = False, sampling_table = None, seed = None, ): couples = [] labels = [] for i, wi in enumerate(sequence): if not wi: continue if sampling_table is not None: if sampling_table[wi] < random.random(): continue window_start = max(0, i - window_size) window_end = min(len(sequence), i + window_size + 1) for j in range(window_start, window_end): if j != i: wj = sequence[j] if not wj: continue couples.append([wi, wj]) if categorical: labels.append([0, 1]) else: labels.append(1) if negative_samples > 0: num_negative_samples = int(len(labels) * negative_samples) words = [c[0] for c in couples] random.shuffle(words) couples += [ [words[i % len(words)], random.randint(1, vocabulary_size - 1)] for i in range(num_negative_samples) ] if categorical: labels += [[1, 0]] * num_negative_samples else: labels += [0] * num_negative_samples if shuffle: if seed is None: seed = random.randint(0, 10e6) random.seed(seed) random.shuffle(couples) random.seed(seed) random.shuffle(labels) return couples, labels # + import tensorflow as tf from collections import Counter from sklearn.feature_extraction.text import CountVectorizer import numpy as np bow = CountVectorizer().fit(sentences) transformed = bow.transform(sentences) idx_text_clean, len_idx_text_clean = [], [] for text in transformed: splitted = text.nonzero()[1] idx_text_clean.append(splitted) dictionary = { i: no for no, i in enumerate(bow.get_feature_names()) } reversed_dictionary = { no: i for no, i in enumerate(bow.get_feature_names()) } freqs = transformed.toarray().sum(axis = 0).tolist() doc_ids = np.arange(len(idx_text_clean)) num_unique_documents = doc_ids.max() pivot_words, target_words, doc_ids = [], [], [] for i, t in enumerate(idx_text_clean): pairs, _ = skipgrams( t, vocabulary_size = len(dictionary), window_size = window_size, shuffle = True, negative_samples = 0, ) for pair in pairs: temp_data = pair pivot_words.append(temp_data[0]) target_words.append(temp_data[1]) doc_ids.append(i) pivot_words, target_words, doc_ids = shuffle( pivot_words, target_words, doc_ids, random_state = 10 ) num_unique_documents = len(idx_text_clean) # - model = LDA2VEC( num_unique_documents, len(dictionary), n_topics, freqs, embedding_size = embedding_size) model.train( pivot_words, target_words, doc_ids, epoch, switch_loss = switch_loss ) doc_embed = model.sess.run(model.doc_embedding) topic_embed = model.sess.run(model.topic_embedding) word_embed = model.sess.run(model.word_embedding) components = topic_embed.dot(word_embed.T) for no, topic in enumerate(components): topic_string = ' '.join([reversed_dictionary[i] for i in topic.argsort()[: -10 : -1]]) print('topic %d : %s'%(no + 1, topic_string))
topic-modeling/lda2vec.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <img align="left" src="https://ithaka-labs.s3.amazonaws.com/static-files/images/tdm/tdmdocs/CC_BY.png"><br /> # # Created by [<NAME>](http://nkelber.com) and Ted Lawless for [JSTOR Labs](https://labs.jstor.org/) under [Creative Commons CC BY License](https://creativecommons.org/licenses/by/4.0/)<br /> # For questions/comments/improvements, email <EMAIL>.<br /> # ___ # **Creating a Stopwords List** # # **Description:** # This [notebook](https://docs.tdm-pilot.org/key-terms/#jupyter-notebook) explains what a stopwords list is and how to create one. The following processes are described: # # * Loading the NLTK stopwords list # * Modifying the stopwords list in Python # * Saving a stopwords list to a .csv file # * Loading a stopwords list from a .csv file # # **Use Case:** For Learners (Detailed explanation, not ideal for researchers) # # [Take me to **Research Version** of this notebook ->](./creating-stopwords-list-for-research.ipynb) # # **Difficulty:** Intermediate # # **Completion time:** 20 minutes # # **Knowledge Required:** # * Python Basics Series ([Start Python Basics I](./python-basics-1.ipynb)) # # **Knowledge Recommended:** None # # **Data Format:** CSV files # # **Libraries Used:** # * **[nltk](https://docs.tdm-pilot.org/key-terms/#nltk)** to create an initial stopwords list # * **csv** to read and write the stopwords to a file # # **Research Pipeline:** None # ___ # # The Purpose of a Stopwords List # # Many text analytics techniques are based on counting the occurrence of words in a given text or set of texts (called a corpus). The most frequent words can reveal general textual patterns, but the most frequent words for any given text in English tend to look very similar to this: # # # |Word|Frequency| # |---|---| # |the| 1,160,276| # |of|906,898| # |and|682,419| # |in|461,328| # |to|418,017| # |a|334,082| # |is|214,663| # |that|204,277| # |by|181,605| # |as|177,774| # # There are many [function words](https://docs.tdm-pilot.org/key-terms/#function-words), words like "the", "in", and "of" that are grammatically important but do not carry as much semantic meaning in comparison to [content words](https://docs.tdm-pilot.org/key-terms/#content-words), such as nouns and verbs. # # For this reason, many analysts remove common [function words](https://docs.tdm-pilot.org/key-terms/#function-words) using a [stopwords](https://docs.tdm-pilot.org/key-terms/#stop-words) list. There are many sources for stopwords lists. (We'll use the Natural Language Toolkit stopwords list in this lesson.) **There is no official, standardized stopwords list for text analysis.** # # An effective stopwords list depends on: # # * the texts being analyzed # * the purpose of the analysis # # Even if we remove all common function words, there are often formulaic repetitions in texts that may be counter-productive for the research goal.**The researcher is responsible for making educated decisions about whether or not to include any particular stopword given the research context.** # # Here are a few examples where additional stopwords may be necessary: # # * A corpus of law books is likely to have formulaic, archaic repetition, such as, "hereunto this law is enacted..." # * A corpus of dramatic plays is likely to have speech markers for each line, leading to an over-representation of character names (Hamlet, Gertrude, Laertes, etc.) # * A corpus of emails is likely to have header language (to, from, cc, bcc), technical language (attached, copied, thread, chain) and salutations (attached, best, dear, cheers, etc.) # # Because every research project may require unique stopwords, it is important for researchers to learn to create and modify stopwords lists. # # Examining the NLTK Stopwords List # # The Natural Language Toolkit Stopwords list is well-known and a natural starting point for creating your own list. Let's take a look at what it contains before learning to make our own modifications. # # We will store our stopwords in a Python list variable called `stop_words`. # Creating a stop_words list from the NLTK. We could also use the set of stopwords from Spacy or Gensim. from nltk.corpus import stopwords # Import stopwords from nltk.corpus stop_words = stopwords.words('english') # Create a list `stop_words` that contains the English stop words list # If you're curious what is in our stopwords list, we can use the `print()` or `list()` functions to find out. list(stop_words) # Show each string in our stopwords list # # Storing Stopwords in a CSV File # Storing the stopwords list in a variable like `stop_words` is useful for analysis, but we will likely want to keep the list even after the session is over for future changes and analyses. We can store our stop words list in a CSV file. A CSV, or "Comma-Separated Values" file, is a plain-text file with commas separating each entry. The file can be opened and modified with a text editor or spreadsheet software such as Excel or Google Sheets. # # Here's what our NLTK stopwords list will look like as a CSV file opened in a plain text editor. # # ![The csv file as an image](https://ithaka-labs.s3.amazonaws.com/static-files/images/tdm/tdmdocs/stopwordsCSV.png) # # Let's create an example CSV using the `csv` module. # + # Create a CSV file to store a set of stopwords import csv # Import the csv module to work with csv files with open('data/stop_words.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerow(stop_words) # - # We have created a new file called data/stop_words.csv that you can open and modify using a basic text editor. Go ahead and make a change to your data/stop_words.csv (either adding or subtracting words) using a text editor. Remember, there are no spaces between words in the CSV file. If you want to edit the CSV right inside Jupyter Lab, right-click on the file and select "Open With > Editor." # # ![Selecting "Open With > Editor" in Jupyter Lab](https://ithaka-labs.s3.amazonaws.com/static-files/images/tdm/tdmdocs/editCSV.png) # # Now go ahead and add in a new word. Remember a few things: # # * Each word is separated from the next word by a comma. # * There are no spaces between the words. # * You must save changes to the file if you're using a text editor, Excel, or the Jupyter Lab editor. # * You can reopen the file to make sure your changes were saved. # # Now let's read our CSV file back and overwrite our original `stop_words` list variable. # # Reading in a Stopwords CSV # + # Open the CSV file and list the contents with open('data/stop_words.csv', 'r') as f: stop_words = f.read().strip().split(",") stop_words[-10:] # - # Refining a stopwords list for your analysis can take time. It depends on: # # * What you are hoping to discover (for example, are function words important?) # * The material you are analyzing (for example, journal articles may repeat words like "abstract") # # If your results are not satisfactory, you can always come back and adjust the stopwords. You may need to run your analysis many times to refine a good stopword list. #
creating-stopwords-list.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 # --- # # Flow in a nano-porous material # # In this notebook we'll explore flow induced in a nano-porous material. To do this we introduce a force $\mathbf{F}_x$ acting on each particle $i$ in the nano-porous material. # In the case of a gravitational field, we can formulate Darcy's law for flow as # \begin{align} # \mathbf{U} = \frac{k}{\mu}\left( \nabla P - \rho \mathbf{a} \right). # \end{align} # Here $\mathbf{U}$ is the _Darcy velocity_, $k$ the permeabillity, $\mu$ the fluid viscosity, $P$ the externally applied pressure, $\rho$ the density and $\mathbf{a}$ the acceleration from the applied force. In our case $\nabla P = 0$ as we have no externally applied pressure. Looking at Newton's second law for a single particle we have # \begin{align} # \mathbf{F}_x = m_i \mathbf{a}_i. # \end{align} # For all particles of the same mass with the same applied force this yields the total applied for to the system # \begin{align} # N\mathbf{F}_x = N m \mathbf{a}, # \end{align} # where $N$ is the number of particles. Dividng by the volume of the system we find # \begin{gather} # \frac{N}{V}\mathbf{F}_x = \frac{N m}{V} \mathbf{a} # \implies # n \mathbf{F}_x = \rho \mathbf{a}, # \end{gather} # where $n$ is the number density and $\rho$ the density of the system. Thus we see that we can replace $\rho \mathbf{a}$ in Darcy's law with $n\mathbf{F}_x$ and we write # \begin{align} # \mathbf{U} = \frac{k}{\mu}\left( \nabla P - n \mathbf{F}_x \right). # \end{align} # + import os import sys sys.path.append("..") import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from read_lammps_dump import read_dump from read_lammps_log import read_log, get_temp_lognames sns.set(color_codes=True) # + # %%writefile scripts/flow_profile.in # 3d Lennard-Jones gas units lj dimension 3 # Periodic boundiaries boundary p p p atom_style atomic variable seed equal 87287 variable sigma equal 3.405 variable b equal 5.72 variable reduced_density equal 4/((${b}/${sigma})^3) variable temperature equal 1.5 variable num_box equal 20 variable radius_min equal 20/${sigma} variable radius_max equal 30/${sigma} # Set fcc lattice with specified density lattice fcc ${reduced_density} region simbox block 0 ${num_box} 0 ${num_box} 0 ${num_box} create_box 2 simbox create_atoms 1 box variable box_len equal lx mass * 1.0 velocity all create ${temperature} ${seed} pair_style lj/cut 3.0 pair_coeff * * 1.0 1.0 fix 1 all nvt temp ${temperature} ${temperature} 0.5 thermo 100 run 1000 # Use a radius of 2 nm (equal to 20 Å) variable radius equal 20/${sigma} variable centre_x equal lx/2 variable centre_y equal ly/2 variable centre_z equal lz/2 region cylinder_reg cylinder x ${centre_y} ${centre_z} ${radius} EDGE EDGE units box # Delete half of the atoms in the region delete_atoms porosity cylinder_reg 0.5 ${seed} group pore_group region cylinder_reg set group pore_group type 2 # Create another group from all the remaining atoms except for the ones in the cylinder group frozen subtract all pore_group # Set the velocity of the atoms outside the cylinder to zero velocity frozen set 0 0 0 # Avoid integrating all the particles unfix 1 # Run pore_group using NVE fix 1 pore_group nve dump 1 all custom 10 dat/flow_profile.lammpstrj id type x y z vx vy vz # Compute the porosity variable porosity equal count(pore_group)/count(all) print ${porosity} file dat/flow_profile_porosity.dat reset_timestep 0 compute pore_temp pore_group temp compute msd pore_group msd variable time equal dt*step thermo_style custom step v_time c_pore_temp etotal press c_msd[4] fix force pore_group addforce 0.1 0.0 0.0 thermo 10 log dat/flow_profile.log run 2000 # - # !export OMP_NUM_THREADS=4 && mpirun -np 4 lmp -in scripts/flow_profile.in df, num_atoms, bounds = read_dump("dat/flow_profile.lammpstrj") centre_bounds = [np.sum(bound) / 2 for bound in bounds] df.head() df_flowing = df[df.type == 2] df_flowing.head() df_flowing.x -= centre_bounds[0] df_flowing.y -= centre_bounds[1] df_flowing.z -= centre_bounds[2] df_flowing.loc["r"] = np.sqrt(df_flowing["y"] ** 2 + df_flowing["z"] ** 2) df_flowing.head() # + r = df_flowing[df_flowing.timestep == np.max(df_flowing.timestep)].r hist, bins = np.histogram( np.abs(df_flowing[df_flowing.timestep == np.max(df_flowing.timestep)].vx), np.linspace(0, np.max(r), 101) ) # + fig = plt.figure(figsize=(14, 10)) plt.hist(hist, bins) plt.show() # + fig = plt.figure(figsize=(14, 10)) plt.scatter( df_flowing[df_flowing.timestep == np.max(df_flowing.timestep)].r, np.abs(df_flowing[df_flowing.timestep == np.max(df_flowing.timestep)].vx) ) plt.show()
project-2/flow-in-a-nano-porous-material.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 # --- # # Defensive programming (2) # We have seen the basic idea that we can insert # assert statments into code, to check that the # results are what we expect, but how can we test # software more fully? Can doing this help us # avoid bugs in the first place? # # One possible approach is **test driven development**. # Many people think this reduces the number of bugs in # software as it is written, but evidence for this in the # sciences is somewhat limited as it is not always easy # to say what the right answer should be before writing the # software. Having said that, the tests involved in test # driven development are certanly useful even if some of # them are written after the software. # # We will look at a new (and quite difficult) problem, # finding the overlap between ranges of numbers. For # example, these could be the dates that different # sensors were running, and you need to find the # date ranges where all sensors recorded data before # running further analysis. # <img src="python-overlapping-ranges.svg"> # Start off by imagining you have a working function `range_overlap` that takes # a list of tuples. Write some assert statments that would check if the answer from this # function is correct. Put these in a function. Think of different cases and # about edge cases (which may show a subtle bug). def test_range_overlap(): assert range_overlap([(-3.0, 5.0), (0.0, 4.5), (-1.5, 2.0)]) == (0.0, 2.0) assert range_overlap([ (2.0, 3.0), (2.0, 4.0) ]) == (2.0, 3.0) assert range_overlap([ (0.0, 1.0), (0.0, 2.0), (-1.0, 1.0) ]) == (0.0, 1.0) # But what if there is no overlap? What if they just touch? def test_range_overlap_no_overlap(): assert range_overlap([ (0.0, 1.0), (5.0, 6.0) ]) == None assert range_overlap([ (0.0, 1.0), (1.0, 2.0) ]) == None # What about the case of a single range? def test_range_overlap_one_range(): assert range_overlap([ (0.0, 1.0) ]) == (0.0, 1.0) # The write a solution - one possible one is below. def range_overlap(ranges): # Return common overlap among a set of [low, high] ranges. lowest = -1000.0 highest = 1000.0 for (low, high) in ranges: lowest = max(lowest, low) highest = min(highest, high) return (lowest, highest) # And test it... test_range_overlap() test_range_overlap_no_overlap() test_range_overlap_one_range() # Should we add to the tests? # Can you write version with fewer bugs. My attempt is below. # + def pairs_overlap(rangeA, rangeB): # Check if A starts after B ends and # A ends before B starts. If both are # false, there is an overlap. # We are assuming (0.0 1.0) and # (1.0 2.0) do not overlap. If these should # overlap swap >= for > and <= for <. overlap = not ((rangeA[0] >= rangeB[1]) or (rangeA[1] <= rangeB[0])) return overlap def find_overlap(rangeA, rangeB): # Return the overlap between range # A and B if pairs_overlap(rangeA, rangeB): low = max(rangeA[0], rangeB[0]) high = min(rangeA[1], rangeB[1]) return (low, high) else: return None def range_overlap(ranges): # Return common overlap among a set of # [low, high] ranges. if len(ranges) == 1: # Special case of one range - # overlaps with itself return(ranges[0]) elif len(ranges) == 2: # Just return from find_overlap return find_overlap(ranges[0], ranges[1]) else: # Range of A, B, C is the # range of range(B,C) with # A, etc. Do this by recursion... overlap = find_overlap(ranges[-1], ranges[-2]) if overlap is not None: # Chop off the end of ranges and # replace with the overlap ranges = ranges[:-2] ranges.append(overlap) # Now run again, with the smaller list. return range_overlap(ranges) else: return None # - test_range_overlap() test_range_overlap_one_range() test_range_overlap_no_overlap()
DefensiveProgramming_3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import datasets iris=datasets.load_iris() df=pd.DataFrame(iris.data,columns = iris.feature_names) df.head() # + from sklearn.cluster import KMeans x = df.iloc[:, [0, 1, 2, 3]].values wcss=[] for i in range(1, 11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) kmeans.fit(x) wcss.append(kmeans.inertia_) # Plotting the results onto a line graph, # `allowing us to observe 'The elbow' plt.plot(range(1, 11), wcss) plt.title('The elbow method') plt.xlabel('Number of clusters') plt.ylabel('WCSS') # Within cluster sum of squares plt.show() # - # We can observe from elbow method here that the optimum value of clusters is 3. kmeans = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) y_kmeans = kmeans.fit_predict(x) y_kmeans x # + plt.scatter(x[y_kmeans == 0,0], x[y_kmeans == 0,1], s = 100, c = 'purple', label = 'Iris-setosa') plt.scatter(x[y_kmeans == 1, 0], x[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Iris-versicolour') plt.scatter(x[y_kmeans == 2, 0], x[y_kmeans == 2, 1], s = 100, c = 'red', label = 'Iris-virginica') # Plotting the centroids of the clusters plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:,1], s = 100, c = 'yellow', label = 'Centroids',marker='x') plt.legend() # -
unsupervised_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 # --- # ### Loading Data # + import warnings warnings.filterwarnings("ignore") from pyspark import SparkConf, SparkContext, SQLContext conf = SparkConf().setAppName("AirBnB") sc = SparkContext(conf=conf) sql = SQLContext(sc) import pandas as pd import numpy as np pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 200) import pyspark.sql.functions as Fn import pyspark.sql.types as Tp # - ''' Airbnb data for US from https://public.opendatasoft.com/explore/dataset/airbnb-listings/export/ ?disjunctive.host_verifications&disjunctive.amenities&disjunctive.features&refine.country=United+States LOADING THIS DIRECTLY AS A DATAFRAME WAS CAUSING COLUMNS TO SHIFT, SO LOADING THIS FILE AS RDD FIRST ''' air =sc.textFile('/Users/mannu/Desktop/Big Data/Group Project/airbnb-listings.csv') air.take(2) header = air.first() air_split = air.filter(lambda r: r!=header).map(lambda r: r.lower().split(';')) cols = [c.replace(' ', '_') for c in header.lower().split(';')] cols print("Initial file has",air_split.count(),"rows and",len(cols),"columns") # ### Creating DataFrame # + air_actual = air_split.filter(lambda l: len(l)==len(cols)) print("After splitting all rows into 89 columns and filtering out rows which had more than 89 columns,") print("we now have",air_actual.count(), "rows and",len(cols),"columns") #only 32% rows remain # - air_df = sql.createDataFrame(air_actual,cols) air_df.show(1,False) # + #creating a function for shape of df def shape(df): print("Shape of dataframe is {0} x {1}".format(df.count(),len(df.columns))) shape(air_df) # - #Since 'Price' is our Target variable dropping rows with no price air_df = air_df.dropna(subset=['price']) shape(air_df) # + import string d = string.digits + '.' def extract_number(v): z = '' for ch in v: if ch in d: z+=ch try: return float(z) except: return 0 numPrice = Fn.udf(lambda v: extract_number(v), Tp.FloatType()) air_df = air_df.withColumn("price", numPrice(air_df.price)) shape(air_df) # - #Also, no negative price air_df = air_df.where(Fn.col('price')>0) shape(air_df) # ### Selecting Columns # + #Dropping ID and Url columns id_url = [k for k in air_df.columns if 'id' in k or 'url' in k] print(id_url) air_select = air_df.drop(*[k for k in air_df.columns if 'id' in k or 'url' in k]) shape(air_select) # + #Since the dataframe was converted from an RDD after splitting the string, #there wont be any null values but empty '' values #Creating a function to see number of empty cells per column def empty(df): return df.select([Fn.count(Fn.when(Fn.col(c)=="", c)).alias(c) for c in df.columns]) \ .toPandas().to_dict('records')[0] empty(air_select) # - #Dropping columns with more than 50% None values. d = empty(air_select) thresh = air_select.count()/2 #43276 air_select = air_select.drop(*[k for k in d.keys() if d[k]>thresh]) shape(air_select) #10 columns dropped air_select.printSchema() #all strings except price #Lets see distinct values for each column air_select.agg(*(Fn.countDistinct(Fn.col(c)).alias(c) for c in air_select.columns)).toPandas().T #dropping last_scraped for its insignificance #dropping experiences for no variability #dropping host_name for its insignificance #dropping host_location, host_neighborhood, street, neighborhood, neighbourhood_cleansed, city, smart_location, # country_code, country, latitude, longitude, geolocation and keeping just state and zipcode #dropping calendar_updated, calendar_last_scraped for their insignificance air_select = air_select.drop(*['last_scraped','experiences_offered','host_name','host_neighbourhood',\ 'host_location','street','neighbourhood','neighbourhood_cleansed','city',\ 'smart_location','country','country_code','latitude','longitude','geolocation',\ 'calendar_updated','calendar_last_scraped']) shape(air_select) # + #Segregating cols on types text_cols = ['name','summary','space','description','neighborhood_overview','transit','access',\ 'interaction','house_rules','host_about','host_verifications','market','amenities','features'] date_cols = ['host_since','first_review','last_review'] cat_cols = ['host_response_time','state','zipcode','property_type','room_type','bed_type','cancellation_policy'] int_cols = ['host_listings_count', 'host_total_listings_count',\ 'accommodates','bedrooms','beds','cleaning_fee',\ 'guests_included','extra_people','minimum_nights','maximum_nights',\ 'availability_30','availability_60','availability_90','availability_365',\ 'number_of_reviews','review_scores_rating','review_scores_accuracy','review_scores_cleanliness',\ 'review_scores_checkin','review_scores_communication','review_scores_location',\ 'review_scores_value','calculated_host_listings_count'] float_cols = ['host_response_rate','bathrooms','reviews_per_month'] for col_name in date_cols: air_select = air_select.withColumn(col_name, Fn.col(col_name).cast(Tp.DateType())) for col_name in int_cols: air_select = air_select.withColumn(col_name, Fn.col(col_name).cast(Tp.IntegerType())) for col_name in float_cols: air_select = air_select.withColumn(col_name, Fn.col(col_name).cast(Tp.FloatType())) air_select.printSchema() # + def nans(df,cols): return df.select([Fn.count(Fn.when(Fn.isnan(c) | Fn.col(c).isNull(), c)).alias(c) for c in cols]) \ .toPandas().to_dict('records')[0] d = nans(air_select,int_cols+float_cols) print(d) thresh = air_select.count()/2 #43276 air_select = air_select.drop(*[k for k in d.keys() if d[k]>thresh]) shape(air_select) # - # ### Imputing Values #Imputing values air_imputed = air_select for c in text_cols+cat_cols: air_imputed = air_imputed.withColumn(c, Fn.when(Fn.trim(Fn.col(c))=="","unknown_"+c).otherwise(Fn.col(c))) empty(air_imputed) #As the average of columns are susceptible to outliers, imputing with median instead cols = int_cols+float_cols medians = {} for col in cols: medians[col] = air_imputed.approxQuantile(col, [0.5], 0.05)[0] air_imputed = air_imputed.fillna(medians) nans(air_imputed,int_cols+float_cols) # ### Handling outliers air_imputed.select(int_cols + float_cols).describe().toPandas().T # + #There as some outliers especially in 'maximum_nights', lets cap them bounds = {} air_bounded = air_imputed cols = int_cols + float_cols for c in cols: quantiles = air_bounded.approxQuantile(c, [0.25, 0.75], 0.005) IQR = quantiles[1] - quantiles[0] bounds[c] = [quantiles[0] - 1.5 * IQR, quantiles[1] + 1.5 * IQR] air_bounded = air_bounded.withColumn(c, Fn.when(Fn.col(c)<bounds[c][0],bounds[c][0]). \ when(Fn.col(c)>bounds[c][1],bounds[c][1]).otherwise(Fn.col(c))) for col_name in int_cols: air_bounded = air_bounded.withColumn(col_name, Fn.col(col_name).cast(Tp.IntegerType())) air_bounded.select(int_cols + float_cols).describe().toPandas().T # - #Some columns have no variability left, dropping those columns cols = ['host_response_rate','bathrooms','review_scores_accuracy', \ 'review_scores_checkin','review_scores_communication','review_scores_location'] air_bounded = air_bounded.drop(*cols) shape(air_bounded) # ### Column Transformations # + #Rather than date columns, we will create new column for each having days since that date def date_to_num_days(df, cols): df = df.withColumn("today", Fn.current_date()) for c in cols: df = df.withColumn("num_days_"+c, Fn.datediff('today',Fn.col(c))) return df.drop(*cols).drop("today") air_transformed = date_to_num_days(air_bounded,date_cols) #checking nans now, nans(air_transformed,air_transformed.columns) # - #imputing the new columns NaNs with -1 air_transformed = air_transformed.na.fill(-1) shape(air_transformed) # + #Lets take a look at our label column i.e. price label_histogram = air_transformed.select('price').rdd.flatMap(lambda x: x).histogram(11) pd.DataFrame(list(zip(*label_histogram)), columns=['bin', 'frequency']).set_index('bin').plot(kind='bar') # - # Regression's underlying assumption is that the dependent variable should have a normal distribution. However from above, our dependent variable. doesnt follow that. So we need to transform the variable in order to achieve it. Let's take a log of price and see the distribution. label_histogram = air_transformed.select(Fn.log('price')).rdd.flatMap(lambda x: x).histogram(11) pd.DataFrame(list(zip(*label_histogram)), columns=['bin', 'frequency']).set_index('bin').plot(kind='bar') # + #A bit negatively skewed but this is still close to normal distribution, #so we create our label with Log(price) air_transformed = air_transformed.withColumn('label', Fn.log('price')) shape(air_transformed) #Note at this point we have 2 columns which are not features # - # ### Correlation Analysis # + #Easiest way to see if there are some relationships among independent variables is to make Scatter Plots import matplotlib.pyplot as plt numeric_cols = [t[0] for t in air_transformed.dtypes if t[1] != 'string' and t[0] != 'price'] sampled_data = air_transformed.select(numeric_cols).sample(False, 0.1, 1).toPandas() axs = pd.scatter_matrix(sampled_data, figsize=(10, 10)) n = len(sampled_data.columns) for i in range(n): v = axs[i, 0] v.yaxis.label.set_rotation(0) v.yaxis.label.set_ha('right') v.set_yticks(()) h = axs[n-1, i] h.xaxis.label.set_rotation(90) h.set_xticks(()) #SINCE THIS IS NOT SO EASY TO READ, #WE WILL MAKE A CORRELATION HEATMAP TO SEE THE RELATIONSHIPS, IF ANY, AMONG THE INDEPENDENT VARIABLES # + import seaborn as sns def heatcorr(df, cols): sampled_data = df.select(cols).sample(False, 0.1,1).toPandas() sns.set(style="white") corr = sampled_data.corr() mask = np.zeros_like(corr, dtype=np.bool) mask[np.triu_indices_from(mask)] = True f, ax = plt.subplots(figsize=(11, 9)) cmap = sns.diverging_palette(220, 10, as_cmap=True) sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}) heatcorr(air_transformed, numeric_cols) #much better # + #Dropping 'host_total_listings_count','host_listings_count' for their correlation with 'calculated_host_listings_count' #Adding accommodates_per_bedroom and dropping accommodates #Dropping 'beds' because of its correlation with bedrooms #Adding cleaning_fee_per_bedroom and dropping cleaning_fee #Dropping 'guests_included' for its correlation with bedrooms #Dropping 'availability_60','availability_90','availability_365', high correlation with availability_30 #Dropping 'number_of_reviews' for its correlation with 'reviews_per_month' #Keeping 'review_scores_rating' and Dropping 'review_scores_value' #Dropping 'num_days_first_review' for its correlation with other num_days columns air_reduced = air_transformed air_reduced = air_reduced.drop(*['host_total_listings_count','host_listings_count']) \ .withColumn("accommodates_per_bedroom", \ Fn.when(Fn.isnull(air_transformed.accommodates/air_transformed.bedrooms), \ air_transformed.accommodates) \ .otherwise(air_transformed.accommodates/air_transformed.bedrooms)) \ .drop(*['accommodates','beds']) \ .withColumn("cleaning_fee_per_bedroom", \ Fn.when(Fn.isnull(air_transformed.cleaning_fee/air_transformed.bedrooms), \ air_transformed.cleaning_fee) \ .otherwise(air_transformed.cleaning_fee/air_transformed.bedrooms)) \ .drop(*['cleaning_fee','guests_included','availability_60','availability_90','availability_365', \ 'number_of_reviews','review_scores_cleanliness','review_scores_value','num_days_first_review']) numeric_cols = [c[0] for c in air_reduced.dtypes if c[1]!='string' and c[0] != 'price'] heatcorr(air_reduced, numeric_cols) #there are still correlations of ~0.3 but we will proceed as of now # - # ### Handling descriptive text columns #lets see the sample air_reduced.select(text_cols).sample(False, 0.0001,1).toPandas() # + #Rather than 14 text columns, adding their respective wordcount columns #This will give a sense of how price depends on number of words in a descriptive section #Another thing we can add is the sentiment of these texts #### NOTE #### #3 columns (host_verifications,amenities,features) are comma separated lists #Each unique value in the list of these columns will be converted to separate columns #the new columns will be binary indicating presence of that value in the list comma_cols = ['host_verifications','amenities','features'] space_cols = list(set(text_cols) - set(comma_cols)) def wordcount(df, cols): for c in cols: df = df.withColumn('wc_'+c, Fn.size(Fn.split(Fn.col(c), ' '))) return df import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer sia = SentimentIntensityAnalyzer() def get_sentiment(s): return sia.polarity_scores(s)['compound'] sentiment = Fn.udf(lambda t: get_sentiment(t), Tp.FloatType()) def sentiments(df, cols): for c in cols: df = df.withColumn('sentiment_'+c, sentiment(Fn.col(c))) return df.drop(*cols) def feature_cols(df, cols): for col in cols: vals = sorted(list(df.select(Fn.explode(Fn.split(Fn.col(col), ','))).distinct().toPandas()['col'])) for val in vals: df = df.withColumn(val.replace(' ','_'), Fn.when(Fn.col(col).like('%'+val+'%'), 1).otherwise(0)) return df.drop(*cols) air_expanded = wordcount(air_reduced, space_cols) air_expanded = sentiments(air_expanded, space_cols) air_expanded = feature_cols(air_expanded, comma_cols) shape(air_expanded) # - #lets see the sample again air_expanded.sample(False, 0.0001,1).toPandas() # ### Encoding categorical columns # + #cleaning Zipcode import string d = string.digits def extractzip(v): z = '' for ch in v: if ch in d: z+=ch if (len(z)!=5 and len(z)!=9): z='unknown_zip' return z zipclean = Fn.udf(lambda v: extractzip(v), Tp.StringType()) air_encoded = air_expanded.withColumn("zipcode", zipclean(air_expanded.zipcode)) air_encoded.select(Fn.length(Fn.col('zipcode')).alias('ziplength')).groupBy('ziplength').count().show() # + #NOT USING STRINGINDEXER AND ONE HOT ENCODER #USING THIS FUNCTION SO THAT THE COLUMN CAN BE RECOGNIZED FROM THE COLUMN NAME def categorical_cols(df, cols): for col in cols: vals = sorted(list(df.select(Fn.col(col)).distinct().toPandas()[col])) for val in vals: df = df.withColumn(val.replace(' ','_'), Fn.when(Fn.col(col).like('%'+val+'%'), 1).otherwise(0)) return df.drop(*cols) air_encoded = categorical_cols(air_encoded, cat_cols) shape(air_encoded) # + air_final = air_encoded.withColumnRenamed('translation_missing:_en.hosting_amenity_49','hosting_amenity_49') \ .withColumnRenamed('translation_missing:_en.hosting_amenity_50','hosting_amenity_50') air_final.columns #just showing columns as descriptive statistics was overloading the system # - #dropping duplicate rows if any air_final = air_final.dropDuplicates() print("\nFinally,") shape(air_final) #Note 2 of the columns are label and price which are not features # ### Assembling & scaling features air_final.sample(False, 0.0001,1).toPandas() #Dividing the data (trainingData, validationData, testData) = air_final.randomSplit([0.6, 0.2, 0.2], seed = 1) print("Training row count:",trainingData.count()) print("Validation row count:",validationData.count()) print("Testing row count:",testData.count()) # + #Combining features import pyspark.ml.feature as Ft features = [c for c in air_final.columns if c != 'label' and c != 'price'] assembler = Ft.VectorAssembler(inputCols=features, outputCol="assembled_features") assembledData = assembler.transform(air_final).drop(*features) assembledData.show(1,False) #1142 # + #Standardizing scaler = Ft.MinMaxScaler(inputCol="assembled_features", outputCol="features").fit(assembledData) scaledData = scaler.transform(assembledData).drop("assembled_features") scaledData.show(1,False) # - # ### Model building & evaluation # + #Building model from pyspark.ml.regression import LinearRegression lrModel1 = LinearRegression().fit(scaledData) #default settings result1 = lrModel1.transform(scaledData) print("R-squared of model is",lrModel1.summary.r2) def metrics(df): df = df.select('price', 'prediction', (Fn.col('price')-Fn.exp(Fn.col('prediction'))).alias('error')) df = df.withColumn('sq_error', Fn.pow(Fn.col('error'),2)) df = df.withColumn('abs_error', Fn.abs(Fn.col('error'))) print("MAE in predictions is",(df.agg({'abs_error':'sum'}).collect()[0]['sum(abs_error)'])/df.count()) print("RMSE in predictions is",np.power((df.agg({'sq_error':'sum'}).collect()[0]['sum(sq_error)'])/df.count(),0.5)) print("\nFor training,") metrics(result1) valresult1 = lrModel1.transform(scaler.transform(assembler.transform(validationData))) print("\nFor validation,") metrics(valresult1) # - #For comparison, result1.select("price").describe().show() # Validation result is high but good that its not too high. This indicates the model is may be slightly over-trained. # ### Using Feature selector #REDUCING COUNT OF FEATURES TO 850 selector2 = Ft.ChiSqSelector(numTopFeatures=850, outputCol="selectedFeatures").fit(scaledData) selectedData = selector2.transform(scaledData).drop('features') lrModel2 = LinearRegression(featuresCol="selectedFeatures").fit(selectedData) #default settings print("R-squared of model is",lrModel2.summary.r2) print("\nFor training,") result2 = lrModel2.transform(selectedData) metrics(result2) print("\nFor validation,") valresult2 = lrModel2.transform(selector2.transform(scaler.transform(assembler.transform(validationData)))) metrics(valresult2) #REDUCING COUNT OF FEATURES TO 500 selector3 = Ft.ChiSqSelector(numTopFeatures=500, outputCol="selectedFeatures").fit(scaledData) selectedData = selector3.transform(scaledData).drop('features') lrModel3 = LinearRegression(featuresCol="selectedFeatures").fit(selectedData) #default settings print("R-squared of model is",lrModel3.summary.r2) print("\nFor training,") result3 = lrModel3.transform(selectedData) metrics(result3) print("\nFor validation,") valresult3 = lrModel3.transform(selector3.transform(scaler.transform(assembler.transform(validationData)))) metrics(valresult3) #REDUCING COUNT OF FEATURES TO 100 selector4 = Ft.ChiSqSelector(numTopFeatures=100, outputCol="selectedFeatures").fit(scaledData) selectedData = selector4.transform(scaledData).drop('features') lrModel4 = LinearRegression(featuresCol="selectedFeatures").fit(selectedData) #default settings print("R-squared of model is",lrModel4.summary.r2) print("\nFor training,") result4 = lrModel4.transform(selectedData) metrics(result4) print("\nFor validation,") valresult4 = lrModel4.transform(selector4.transform(scaler.transform(assembler.transform(validationData)))) metrics(valresult4) # ### Trying other Models #Lets stick to 1133 features, and try other models from pyspark.ml.regression import RandomForestRegressor rfModel5 = RandomForestRegressor(seed=1).fit(scaledData) print("\nFor training,") result5 = rfModel5.transform(scaledData) metrics(result5) print("\nFor validation,") valresult5 = rfModel5.transform(scaler.transform(assembler.transform(validationData))) metrics(valresult5) from pyspark.ml.regression import GBTRegressor gbtModel6 = GBTRegressor(seed=1).fit(scaledData) print("\nFor training,") result6 = gbtModel6.transform(scaledData) metrics(result6) print("\nFor validation,") valresult6 = gbtModel6.transform(scaler.transform(assembler.transform(validationData))) metrics(valresult6) # ### Parameter tuning for linear regression print(lrModel1.explainParams()) #Lets try L1 penalty... i.e. Lasso Regression lrModel7 = LinearRegression(elasticNetParam=1).fit(scaledData) print("R-squared of model is",lrModel7.summary.r2) print("\nFor training,") result7 = lrModel7.transform(scaledData) metrics(result7) print("\nFor validation,") valresult7 = lrModel7.transform(scaler.transform(assembler.transform(validationData))) metrics(valresult7) len(list(lrModel7.coefficients)) #1133 coefficients keys = [c for c in validationData.columns[:-7] if c!='price' and c!='label'] print(len(keys)) keys values = list(lrModel7.coefficients) len(values) col_coeff = dict(zip(keys, values)) col_coeff #########THESE HAVE ZERO COEFF [k for k in col_coeff.keys() if col_coeff[k]==0] for w in sorted(col_coeff, key=col_coeff.get, reverse=True): print (w, col_coeff[w]) # + ##### OTHER THAN ZIPCODE, INFLUENTIAL FEATURES for w in sorted(col_coeff, key=col_coeff.get, reverse=True): if isnumeric(w)==False and col_coeff[w]!=0: print (w, col_coeff[w]) # -
AirBnB version 9.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 # --- # # Now You Code 2: Multiply By # # Write a program to ask for a number to multiply by and then lists the multiplication table for that number from 1 to 10. This process will repeat until you enter quit as which point the program will exit. # # Wow. Seems complicated! We'll use technique called problem simplification to make this problem a little easier to solve. # # First we'll write a complete program to solve *part* of the problem, then we will take our new level of understanding to solve the *entire* problem. # # ## Start with Sub-Problem 1 # # Let's write a program to simply input a number and then uses a loop to print out the multiplication table up to 10 for that number. # # For example, when you input `5`: # # ``` # Enter number to multiply by: 5 # 1 x 5 = 5 # 2 x 5 = 10 # 3 x 5 = 15 # 4 x 5 = 20 # 5 x 5 = 25 # 6 x 5 = 30 # 7 x 5 = 35 # 8 x 5 = 40 # 9 x 5 = 45 # 10 x 5 = 50 # ``` # # ## Step 1: Problem Analysis for Sub-Problem 1 # # Inputs: # # Outputs: # # Algorithm (Steps in Program): # # # num = input("enter number:") for i in range(0, 11): print(num,'x',i,'=',int(num)*i) # # Full Problem # # Now that we've got part of the problem figured out, let's solve the entire problem. The program should keep asking for numbers and then print out multiplcation tables until you enter `quit`. Here's an example: # # Example Run: # # ``` # Enter number to multiply by or type 'quit': 10 # 1 x 10 = 10 # 2 x 10 = 20 # 3 x 10 = 30 # 4 x 10 = 40 # 5 x 10 = 50 # 6 x 10 = 60 # 7 x 10 = 70 # 8 x 10 = 80 # 9 x 10 = 90 # 10 x 10 = 100 # Enter number to multiply by or type 'quit': 5 # 1 x 5 = 5 # 2 x 5 = 10 # 3 x 5 = 15 # 4 x 5 = 20 # 5 x 5 = 25 # 6 x 5 = 30 # 7 x 5 = 35 # 8 x 5 = 40 # 9 x 5 = 45 # 10 x 5 = 50 # Enter number to multiply by or type 'quit': quit # ``` # # **NOTE:** you need another loop complete this program. Take the code you wrote in the first part and repeat it in another loop until you type quit. # ## Step 3: Problem Analysis for Full Problem # # Inputs: # # Outputs: # # Algorithm (Steps in Program): # + # Step 4: Write code for full problem while True: num = input("enter number:") if (num=='quit'): break else: for i in range(1, 11): print(num,'x',i,'=',int(num)*i) # - # ## Step 3: Questions # # 1. What is the loop control variable for the first (outer) loop? # 2. What is the loop control variable for the second (inner) loop? # 3. Provide at least one way this program can be improved, or make more flexible by introducing more inputs? # # ## Reminder of Evaluation Criteria # # 1. What the problem attempted (analysis, code, and answered questions) ? # 2. What the problem analysis thought out? (does the program match the plan?) # 3. Does the code execute without syntax error? # 4. Does the code solve the intended problem? # 5. Is the code well written? (easy to understand, modular, and self-documenting, handles errors) #
content/lessons/05/Now-You-Code/NYC2-Multiply-By.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: stenv # language: python # name: stenv # --- # # Deep Neural Net with L2 Regularization # # Creating a variable-layer neural network from memory as a learning exercise. # # Uses the cat v non-cat dataset from the [coursera course](https://www.coursera.org/specializations/deep-learning) on Deep Learning by <NAME>. # # Hyperparameters are number of layers and hidden units, lambda for L2 regularisation, learning rate alpha and number of epochs. # ## Import Libraries # + # import libraries import numpy as np import h5py import matplotlib.pyplot as plt from sklearn.datasets import make_circles, make_moons, make_classification import time # load data train_data = h5py.File('C:/Users/leahy/Google Drive/Freelance/own_projects/ml_from_scratch/datasets/train_catvnoncat.h5', 'r') test_data = h5py.File('C:/Users/leahy/Google Drive/Freelance/own_projects/ml_from_scratch/datasets/test_catvnoncat.h5', 'r') X_train = np.array(train_data['train_set_x']) y_train = np.array(train_data['train_set_y']) X_test = np.array(test_data['test_set_x']) y_test = np.array(test_data['test_set_y']) # X_train and X_test contain samples of [m, 64, 64, 3], representing image # hight x width x RGB channels. Reshape to be single vector of size # n * m. Also rescale by 255 X_train = X_train.reshape(X_train.shape[0], -1).T / 255 X_test = X_test.reshape(X_test.shape[0], -1).T / 255 # reshape the y's y_train = y_train.reshape(1, len(y_train)) y_test = y_test.reshape(1, len(y_test)) # - # ## Set up Functions # + def sigmoid(Z): A = 1 / (1 + np.exp(-Z)) return A def initialise_params(layer_dims): init_params = dict() L = len(layer_dims) for i in range(1, L): cur_n = layer_dims[i] # set W initial weights to be the square root of nodes in prev. layer # ie using "He 2012" initialisiation init_params["W" + str(i)] = np.random.randn( layer_dims[i], layer_dims[i - 1]) *\ (np.sqrt(2 / layer_dims[i - 1])) init_params["b" + str(i)] = np.zeros([layer_dims[i], 1]) assert(init_params['W' + str(i)].shape == ( layer_dims[i], layer_dims[i - 1])) assert(init_params['b' + str(i)].shape == (layer_dims[i], 1)) return init_params def forward_prop(X, params): L = len(params) // 2 m = X.shape [1] preds = {} preds['A0'] = X A_prev = X # For layers 1:L-1 we use relu for i in range(1, L): W = params['W' + str(i)] b = params['b' + str(i)] Z = np.dot(W, A_prev) + b A = np.maximum(0, Z) preds['Z' + str(i)] = Z preds['A' + str(i)] = A assert(preds['Z' + str(i)].shape == (layer_dims[i], m)) assert(preds['A' + str(i)].shape == (layer_dims[i], m)) A_prev = A # For final layer use sigmoid W = params['W' + str(L)] b = params['b' + str(L)] Z = np.dot(W, A_prev) + b A = sigmoid(Z) preds['Z' + str(L)] = Z preds['A' + str(L)] = A assert(preds['Z' + str(L)].shape == (layer_dims[L], m)) assert(preds['A' + str(L)].shape == (layer_dims[L], m)) return preds def compute_cost(AL, y, params, l2_lambda=None): m = y.shape[1] L = len(params) // 2 log_probs = np.multiply(y, -np.log(AL)) + np.multiply( (1 - y), -np.log(1 - AL)) cost = np.nansum(log_probs) / m # calc L2 reg cost reg_term = 0 for i in range(1, L + 1): W = params['W' + str(i)] # we divide by 2m simply by convention so that the derivative # constant in backprop is lambda/m rather than 2 * lambda/m reg_term += (l2_lambda / (2 * m)) * (np.linalg.norm(W, ord='fro')) cost += reg_term assert cost.shape == () return cost def back_prop(y, preds, params, l2_lambda=None): L = len(params) // 2 grads = {} m = y.shape[1] for i in reversed(range(1, L + 1)): if i == L: # for final case, dLdZL = dLdAL*dALdZL = AL - y AL = preds['A' + str(L)] dZ = AL - y else: # for other cases # _plus represent values at i + 1 dZ_plus = grads['dZ' + str(i + 1)] W_plus = params['W' + str(i + 1)] Z = preds['Z' + str(i)] # gradient of relu fn relu_grad = np.zeros(Z.shape) relu_grad[Z > 0] = 1 dZ = np.dot(W_plus.T, dZ_plus) * relu_grad grads['dZ' + str(i)] = dZ A_prev = preds['A' + str(i - 1)] # including L2 regularization! W = params['W' + str(i)] grads['dW' + str(i)] = (np.dot(dZ, A_prev.T) + (l2_lambda * W)) / m grads['db' + str(i)] = np.sum(dZ, axis=1, keepdims=True) / m return grads def update_params(grads, params, alpha): L = len(params) // 2 for i in range(1, L + 1): params['W' + str(i)] -= (alpha * grads['dW' + str(i)]) params['b' + str(i)] -= (alpha * grads['db' + str(i)]) return params def fit(X, y, layer_dims, num_iterations, alpha, l2_lambda=None, cost_interval=200): params = initialise_params(layer_dims) L = len(params) // 2 costs = [] for i in range(num_iterations): preds = forward_prop(X, params) J = compute_cost(preds['A' + str(L)], y, params, l2_lambda) if i % cost_interval == 0: print(f'cost after iter {i}: {J}') if i % 100 == 0: costs += [J] grads = back_prop(y, preds, params, l2_lambda) params = update_params(grads, params, alpha) plt.plot(costs) plt.show() return params, costs def predict(X, params): L = len(params) // 2 preds = forward_prop(X, params) y_pred = preds['A' + str(L)] y_pred[y_pred > 0.5] = 1 y_pred[y_pred <= 0.5] = 0 return y_pred def accuracy_score(y_test, y_pred): m = y_test.shape[1] score = np.sum(y_test == y_pred) / m print(f'accuracy: {score}') return score # - # ## Fit, Predict, Score # # Let's see effects of regularisation # + layer_dims = [X_train.shape[0], 20, 7, 5, y_train.shape[0]] num_iterations = 2400 alpha = .0075 l2_lambdas = [0, 0.001, 0.01] # interval in the iterations for which the costs will be stored cost_interval = 200 for l2_lambda in l2_lambdas: start = time.time() print(f'lambda={l2_lambda}') params, costs = fit(X_train, y_train, layer_dims, num_iterations, alpha, l2_lambda, cost_interval) y_pred_train = predict(X_train, params) y_pred_test = predict(X_test, params) print('Train set:') accuracy_score(y_train, y_pred_train) print('Test Set:') accuracy_score(y_test, y_pred_test) end = time.time() print(f'took {end - start} seconds\n\n') # - # ## Performance on generated dataset # + m = 2000 # data = make_classification(n_features=2, n_redundant=0, n_informative=2, # n_clusters_per_class=2, n_samples=m) # data = make_circles(n_samples=m, factor=.5, noise=.03) data = make_moons(n_samples=m, noise=.25) X, y = data[0].T, data[1].reshape(1, -1) idx = np.arange(X.shape[1]) np.random.shuffle(idx) X_train = X[:, idx[0:int(m * .8)]] X_test = X[:, idx[int(m * .8):]] y_train = y[:, idx[0:int(m * .8)]] y_test = y[:, idx[int(m * .8):]] # - layer_dims = [X_train.shape[0], 20, 7, 5, y_train.shape[0]] num_iterations = 2400 alpha = .075 l2_lambdas = [0, 0.001, 0.01, .1] # interval in the iterations for which the costs will be stored cost_interval = 20000000 np.random.seed(1) for l2_lambda in l2_lambdas: start = time.time() print(f'lambda={l2_lambda}') params, costs = fit(X_train, y_train, layer_dims, num_iterations, alpha, l2_lambda, cost_interval) y_pred_train = predict(X_train, params) y_pred_test = predict(X_test, params) print('Train set:') accuracy_score(y_train, y_pred_train) print('Test Set:') accuracy_score(y_test, y_pred_test) end = time.time() print(f'took {end - start} seconds\n\n') # + # Set min and max values for meshgrid x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1 y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1 # Generate a grid of points with distance h between them h = 0.01 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Predict the function value for the whole grid using previous params L = len(params) // 2 X_mesh = np.c_[xx.ravel(), yy.ravel()].T Z = forward_prop(X_mesh, params)['A' + str(L)] Z = Z.reshape(xx.shape) # Plot the contour and training examples plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm) plt.ylabel('x2') plt.xlabel('x1') plt.scatter(X_test[0, :], X_test[1, :], c=np.squeeze(y_test))
deep_neural_net.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 os.path import numpy as np import pandas as pd from scipy.stats import probplot, expon, lognorm, weibull_min, ks_1samp from exp_mixture_model import EMM import matplotlib.pyplot as plt import seaborn as sns from empirical import * from plots import * from expon_mixture import ExponMixture # - # # Load data of an instance base_path = "../outputs/output_train/komb/" size = "n80" index = 1 filename = os.listdir(base_path + size)[index] print(filename) data = np.loadtxt(os.path.join(base_path, size, filename)) df = pd.DataFrame(data, columns=["flips", "time", "seed"]) flips = df['flips'] flips.mean(), flips.std() flips = np.sort(flips) cdf = ecdf(flips) surv = e_survival(flips) # # Check some cdfs of a komb instance plt.plot(flips, cdf) plt.yscale('log') plt.plot(flips, cdf) plt.xscale('log') plt.yscale('log') loc, scale = expon.fit(flips, floc=0) rv = expon(loc=loc, scale=scale) scale a= plot_and_compare_cdf(flips, rv) a,b,c = lognorm.fit(flips, floc=0) rv = lognorm(a,b,c) plot_and_compare_cdf(flips, rv) a,b,np.log(c) # # Fit an exponential mixture distribution model = EMM(k=2) pi, mu = model.fit(flips) model.print_result() rv = ExponMixture(pi, mu) plot_and_compare_cdf(flips, rv) ks_1samp(flips, rv.cdf) model = EMM(k=2) pi, mu = model.fit(flips) model.print_result() rv = ExponMixture(pi, mu) plot_and_compare_cdf(flips, rv) def make_figs(dest, flips, rv): fig = plot_and_compare_cdf(flips, rv) fig.savefig(dest, bbox_inches='tight') plt.close('all') def write_to_parameter_file(type_and_size, fit, instance, *parameters): with open(os.path.join(type_and_size, fit), 'a') as f: f.write(instance) for parameter in parameters: f.write(" " + str(parameter)) f.write("\n") def make_instance_data(base_path, type_and_size, instance): data = np.loadtxt(os.path.join(base_path, type_and_size, instance)) df = pd.DataFrame(data, columns=["flips", "time", "seed"]) flips = df['flips'] flips = np.sort(flips) # Start with fitting the exponential distribution with location 0 loc, scale = expon.fit(flips, floc=0) rv = expon(loc=loc, scale=scale) write_to_parameter_file(type_and_size, 'expon_fits.txt', instance, scale) dest = os.path.join(type_and_size, "expon_figs/") dest = dest + instance + ".pdf" make_figs(dest, flips, rv) # Next the lognormal dist a, b, c = lognorm.fit(flips, floc=0) rv = lognorm(a, b, c) write_to_parameter_file(type_and_size, 'logn_fits.txt', instance, a, b, c) dest = os.path.join(type_and_size, "logn_figs/") dest = dest + instance + ".pdf" make_figs(dest, flips, rv) # Next, the mixture model with an arbitary number of components. model = EMM() pi, mu = model.fit(flips) rv = ExponMixture(pi, mu) write_to_parameter_file(type_and_size, 'expon_mix_fits.txt', instance, *pi, *mu) dest = os.path.join(type_and_size, "expon_mixture_figs/") dest = dest + instance + ".pdf" make_figs(dest, flips, rv) # If more than two components were neccessary: Force at most 2 components. if len(pi) > 2: model = EMM(k=2) pi, mu = model.fit(flips) rv = ExponMixture(pi, mu) write_to_parameter_file(type_and_size, 'expon_mix_2comp_fits.txt', instance, *pi, *mu) dest = os.path.join(type_and_size, "expon_mixture_two_components_figs/") dest = dest + instance + ".pdf" make_figs(dest, flips, rv) def create_files(instance_type, size): path = os.path.join(instance_type, size) files = ['logn_fits.txt', 'expon_fits.txt', 'expon_mix_fits.txt', 'expon_mix_2comp_fits.txt'] for file in files: with open(path + file, 'w') as f: f.write("filename, parameters\n") # + base_path = "../outputs/output_train/" instance_type = "komb" os.makedirs(instance_type, exist_ok=True) path_to_files = os.path.join(base_path, instance_type) sizes = os.listdir(path_to_files) for size in sizes: os.makedirs(os.path.join(instance_type, size, "logn_figs"), exist_ok=True) os.makedirs(os.path.join(instance_type, size, "expon_figs"), exist_ok=True) os.makedirs(os.path.join(instance_type, size, "expon_mixture_figs"), exist_ok=True) os.makedirs(os.path.join(instance_type, size, "expon_mixture_two_components_figs"), exist_ok=True) create_files(instance_type, size) path = os.path.join(path_to_files, size) for instance in os.listdir(path): print(base_path, os.path.join(instance_type, size), instance) try: make_instance_data(base_path, os.path.join(instance_type, size), instance) except ValueError: print(f"Instance {instance} failed") # filename = os.listdir(base_path + size) # - # + base_path = "../outputs/output_train/" instance_type = "qhid" os.makedirs(instance_type, exist_ok=True) path_to_files = os.path.join(base_path, instance_type) #sizes = os.listdir(path_to_files) sizes = ["n80"] for size in sizes: os.makedirs(os.path.join(instance_type, size, "logn_figs"), exist_ok=True) os.makedirs(os.path.join(instance_type, size, "expon_figs"), exist_ok=True) os.makedirs(os.path.join(instance_type, size, "expon_mixture_figs"), exist_ok=True) os.makedirs(os.path.join(instance_type, size, "expon_mixture_two_components_figs"), exist_ok=True) create_files(instance_type, size) path = os.path.join(path_to_files, size) for instance in os.listdir(path): print(base_path, os.path.join(instance_type, size), instance) try: make_instance_data(base_path, os.path.join(instance_type, size), instance) except ValueError: print(f"Instance {instance} failed") # filename = os.listdir(base_path + size) # - p0 = 0.020000 ps = [p0, 1.0-p0] scales = [6.050000e+01, 9.632212e+08] rv = ExponMixture(ps, scales) rv.partial_exp(1.0) from scipy.optimize import root_scalar b = 100.0 def condition(t): F = rv.cdf(t) result = (F - 1.0)*t result += F*(1-F)/(rv.pdf(t)) result -= rv.partial_exp(t) return result - b condition(85) root_scalar(condition, x0=10.0*b, x1=b, method='secant') # # KS-Test for exponential mixture # ## All instances instance_type = "barthel" base_path = f"../outputs/output_train/{instance_type}/" ks_try = 0 ks_passed = 0 for size in os.listdir(base_path): size_path = base_path + size + "/" for instance in os.listdir(size_path): # Some runs were aborted because probSAT is unable to solve them in reasonable time. try: data = np.loadtxt(size_path + instance) except ValueError: print(f"skipped instance {instance}") continue df = pd.DataFrame(data, columns=["flips", "time", "seed"]) flips = df['flips'] model = EMM(k=2) pi, mu = model.fit(flips) rv = ExponMixture(pi, mu) _, p = ks_1samp(flips, rv.cdf) print(f"{instance}, fit: {pi}, {mu}, ks-p: {p}") if p >= 0.05: ks_passed += 1 ks_try += 1 print("total fits:", ks_try) print("total passed:", ks_passed) # ## Result summary # barthel: 26 of 100 passed, max 2 components: 28 of 100 # # qhid: 53 of 100, max 2 components: 54 of 100 # # komb: 92 of 100, max 2 components: 96 of 100 # ## Only hard instances (>100000 flips) instance_type = "barthel" base_path = f"../outputs/output_train/{instance_type}/" ks_try = 0 ks_passed = 0 for size in os.listdir(base_path): size_path = base_path + size + "/" for instance in os.listdir(size_path): try: data = np.loadtxt(size_path + instance) except ValueError: print(f"skipped instance {instance}") continue df = pd.DataFrame(data, columns=["flips", "time", "seed"]) flips = df['flips'] if flips.mean() > 100000: model = EMM(k=2) pi, mu = model.fit(flips) rv = ExponMixture(pi, mu) _, p = ks_1samp(flips, rv.cdf) print(f"{instance}, fit: {pi}, {mu}, ks-p: {p}") if p >= 0.05: ks_passed += 1 ks_try += 1 else: print(f"Skipped instance {instance} with mean {flips.mean()}") print("total fits:", ks_try) print("total passed:", ks_passed) # ## Result summary # On hard instances: mean more than 100000 flips: # # barthel: 6 of 6 # # qhid: 47 of 47 with two components # # komb: 85 of 86 with two components # # KS-Test for the lognormal, Weibull and exponential distribution instance_type = "komb" base_path = f"../outputs/output_train/{instance_type}/" ks_try = 0 ks_passed = {'lognorm':0, 'exp':0, 'weibull':0} for size in os.listdir(base_path): size_path = base_path + size + "/" for instance in os.listdir(size_path): try: data = np.loadtxt(size_path + instance) except ValueError: print(f"skipped instance {instance}") continue df = pd.DataFrame(data, columns=["flips", "time", "seed"]) flips = df['flips'] # Fit the lognormal distribution without location parameter a,b,c = lognorm.fit(flips, floc = 0) rv = lognorm(a, b, c) _, p_logn = ks_1samp(flips, rv.cdf) # Fit the Weibull distribution with location parameter a,b,c = weibull_min.fit(flips) rv = weibull_min(a,b,c) _, p_weib = ks_1samp(flips, rv.cdf) # Fit the exponential distribution with location parameter a,b = expon.fit(flips) rv = expon(a,b) _, p_exp = ks_1samp(flips, rv.cdf) print(f"{instance}, logn ks-p: {p_logn:.5f}, weib p {p_weib:.5f}, exp p{p_exp:.5f}") if p_logn >= 0.05: ks_passed['lognorm'] += 1 if p_weib >= 0.05: ks_passed['weibull'] += 1 if p_exp >= 0.05: ks_passed['exp'] += 1 ks_try += 1 print("total fits:", ks_try) print("total passed:", ks_passed) # ## Result summary # # barthel: {'lognorm': 89, 'exp': 51, 'weibull': 29} of 100 # # qhid: {'lognorm': 49, 'exp': 58, 'weibull': 37} of 100 # # komb: total passed: {'lognorm': 6, 'exp': 85, 'weibull': 49} of 100 # ## On hard instances (flips > 100000) instance_type = "barthel" base_path = f"../outputs/output_train/{instance_type}/" ks_try = 0 ks_passed = {'lognorm':0, 'exp':0, 'weibull':0} for size in os.listdir(base_path): size_path = base_path + size + "/" for instance in os.listdir(size_path): try: data = np.loadtxt(size_path + instance) except ValueError: print(f"skipped instance {instance}") continue df = pd.DataFrame(data, columns=["flips", "time", "seed"]) flips = df['flips'] if flips.mean() > 100000: # Fit the lognormal distribution without location parameter a,b,c = lognorm.fit(flips, floc = 0) rv = lognorm(a, b, c) _, p_logn = ks_1samp(flips, rv.cdf) # Fit the Weibull distribution with location parameter a,b,c = weibull_min.fit(flips) rv = weibull_min(a,b,c) _, p_weib = ks_1samp(flips, rv.cdf) # Fit the exponential distribution with location parameter a,b = expon.fit(flips) rv = expon(a,b) _, p_exp = ks_1samp(flips, rv.cdf) print(f"{instance}, logn ks-p: {p_logn:.5f}, weib p {p_weib:.5f}, exp p{p_exp:.5f}") if p_logn >= 0.05: ks_passed['lognorm'] += 1 if p_weib >= 0.05: ks_passed['weibull'] += 1 if p_exp >= 0.05: ks_passed['exp'] += 1 ks_try += 1 else: print(f"Skipped instance {instance} with mean {flips.mean()}") print("total fits:", ks_try) print("total passed:", ks_passed) # ## Result summary: # # {'lognorm': 2, 'exp': 6, 'weibull': 3} of 6 # # qhid: {'lognorm': 2, 'exp': 45, 'weibull': 22} of 47 # # komb: {'lognorm': 1, 'exp': 81, 'weibull': 42} of 86 # ## On easy instances (flips <= 100000) instance_type = "komb" base_path = f"../outputs/output_train/{instance_type}/" ks_try = 0 ks_passed = {'lognorm':0, 'exp':0, 'weibull':0} for size in os.listdir(base_path): size_path = base_path + size + "/" for instance in os.listdir(size_path): try: data = np.loadtxt(size_path + instance) except ValueError: print(f"skipped instance {instance}") continue df = pd.DataFrame(data, columns=["flips", "time", "seed"]) flips = df['flips'] if flips.mean() <= 100000: # Fit the lognormal distribution without location parameter a,b,c = lognorm.fit(flips, floc = 0) rv = lognorm(a, b, c) _, p_logn = ks_1samp(flips, rv.cdf) # Fit the Weibull distribution with location parameter a,b,c = weibull_min.fit(flips) rv = weibull_min(a,b,c) _, p_weib = ks_1samp(flips, rv.cdf) # Fit the exponential distribution with location parameter a,b = expon.fit(flips) rv = expon(a,b) _, p_exp = ks_1samp(flips, rv.cdf) print(f"{instance}, logn ks-p: {p_logn:.5f}, weib p {p_weib:.5f}, exp p{p_exp:.5f}") if p_logn >= 0.05: ks_passed['lognorm'] += 1 if p_weib >= 0.05: ks_passed['weibull'] += 1 if p_exp >= 0.05: ks_passed['exp'] += 1 ks_try += 1 else: print(f"Skipped instance {instance} with mean {flips.mean()}") print("total fits:", ks_try) print("total passed:", ks_passed) # ## Result summary # barthel: {'lognorm': 87, 'exp': 45, 'weibull': 26} of 96 # # qhid: {'lognorm': 47, 'exp': 13, 'weibull': 15} of 53 # # komb: {'lognorm': 5, 'exp': 4, 'weibull': 7} of 14
jupyter/Fit Exponential Mixture.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 # --- # Version 1.1.0 # # The task # In this assignment you will need to implement features, based on nearest neighbours. # # KNN classifier (regressor) is a very powerful model, when the features are homogeneous and it is a very common practice to use KNN as first level model. In this homework we will extend KNN model and compute more features, based on nearest neighbors and their distances. # # You will need to implement a number of features, that were one of the key features, that leaded the instructors to prizes in [Otto](https://www.kaggle.com/c/otto-group-product-classification-challenge) and [Springleaf](https://www.kaggle.com/c/springleaf-marketing-response) competitions. Of course, the list of features you will need to implement can be extended, in fact in competitions the list was at least 3 times larger. So when solving a real competition do not hesitate to make up your own features. # # You can optionally implement multicore feature computation. Nearest neighbours are hard to compute so it is preferable to have a parallel version of the algorithm. In fact, it is really a cool skill to know how to use `multiprocessing`, `joblib` and etc. In this homework you will have a chance to see the benefits of parallel algorithm. # # Check your versions # Some functions we use here are not present in old versions of the libraries, so make sure you have up-to-date software. # + import numpy as np import pandas as pd import sklearn import scipy.sparse for p in [np, pd, sklearn, scipy]: print (p.__name__, p.__version__) # - # The versions should be not less than: # # numpy 1.13.1 # pandas 0.20.3 # sklearn 0.19.0 # scipy 0.19.1 # # **IMPORTANT!** The results with `scipy=1.0.0` will be different! Make sure you use _exactly_ version `0.19.1`. # # Load data # Learn features and labels. These features are actually OOF predictions of linear models. # + train_path = 'X.npz' train_labels = 'Y.npy' test_path = 'X_test.npz' test_labels = 'Y_test.npy' # Train data X = scipy.sparse.load_npz(train_path) Y = np.load(train_labels) # Test data X_test = scipy.sparse.load_npz(test_path) Y_test = np.load(test_labels) # Out-of-fold features we loaded above were generated with n_splits=4 and skf seed 123 # So it is better to use seed 123 for generating KNN features as well skf_seed = 123 n_splits = 4 # - # Below you need to implement features, based on nearest neighbors. # + from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.neighbors import NearestNeighbors from multiprocessing import Pool from joblib import Parallel, delayed import numpy as np class NearestNeighborsFeats(BaseEstimator, ClassifierMixin): ''' This class should implement KNN features extraction ''' def __init__(self, n_jobs, k_list, metric, n_classes=None, n_neighbors=None, eps=1e-6): self.n_jobs = n_jobs self.k_list = k_list self.metric = metric if n_neighbors is None: self.n_neighbors = max(k_list) else: self.n_neighbors = n_neighbors self.eps = eps self.n_classes_ = n_classes def fit(self, X, y): ''' Set's up the train set and self.NN object ''' # Create a NearestNeighbors (NN) object. We will use it in `predict` function self.NN = NearestNeighbors(n_neighbors=self.n_neighbors, metric=self.metric, n_jobs=1, algorithm='brute' if self.metric=='cosine' else 'auto') self.NN.fit(X) # Store labels self.y_train = y # Save how many classes we have self.n_classes = np.unique(y).shape[0] if self.n_classes_ is None else self.n_classes_ def predict(self, X): ''' Produces KNN features for every object of a dataset X ''' if self.n_jobs == 1: test_feats = [] for i in range(X.shape[0]): test_feats.append(self.get_features_for_one(X[i:i+1])) else: ''' *Make it parallel* Number of threads should be controlled by `self.n_jobs` You can use whatever you want to do it For Python 3 the simplest option would be to use `multiprocessing.Pool` (but don't use `multiprocessing.dummy.Pool` here) You may try use `joblib` but you will most likely encounter an error, that you will need to google up (and eventually it will work slowly) For Python 2 I also suggest using `multiprocessing.Pool` You will need to use a hint from this blog http://qingkaikong.blogspot.ru/2016/12/python-parallel-method-in-class.html I could not get `joblib` working at all for this code (but in general `joblib` is very convenient) ''' with Parallel(n_jobs=self.n_jobs) as parallel: test_feats = parallel(delayed(self.get_features_for_one)(X[i:i+1]) \ for i in range(X.shape[0])) return np.vstack(test_feats) def get_features_for_one(self, x): ''' Computes KNN features for a single object `x` ''' NN_output = self.NN.kneighbors(x) # Vector of size `n_neighbors` # Stores indices of the neighbors neighs = NN_output[1][0] # Vector of size `n_neighbors` # Stores distances to corresponding neighbors neighs_dist = NN_output[0][0] # Vector of size `n_neighbors` # Stores labels of corresponding neighbors neighs_y = self.y_train[neighs] ## ========================================== ## ## YOUR CODE BELOW ## ========================================== ## # We will accumulate the computed features here # Eventually it will be a list of lists or np.arrays # and we will use np.hstack to concatenate those return_list = [] ''' 1. Fraction of objects of every class. It is basically a KNNСlassifiers predictions. Take a look at `np.bincount` function, it can be very helpful Note that the values should sum up to one ''' for k in self.k_list: feats = np.bincount(neighs_y[:k], minlength=self.n_classes) feats = feats / feats.sum() assert len(feats) == self.n_classes return_list += [feats] ''' 2. Same label streak: the largest number N, such that N nearest neighbors have the same label. What can help you: `np.where` ''' streak = np.where(neighs_y != neighs_y[0])[0] feats = [streak[0] if len(streak) > 0 else len(neighs_y)] assert len(feats) == 1 return_list += [feats] ''' 3. Minimum distance to objects of each class Find the first instance of a class and take its distance as features. If there are no neighboring objects of some classes, Then set distance to that class to be 999. `np.where` might be helpful ''' feats = [999] * self.n_classes for c in range(self.n_classes): occ_class = np.where(neighs_y == c)[0] if len(occ_class) >= 1: feats[c] = neighs_dist[occ_class[0]] assert len(feats) == self.n_classes return_list += [feats] ''' 4. Minimum *normalized* distance to objects of each class As 3. but we normalize (divide) the distances by the distance to the closest neighbor. If there are no neighboring objects of some classes, Then set distance to that class to be 999. Do not forget to add self.eps to denominator. ''' feats = [999] * self.n_classes for c in range(self.n_classes): occ_class = np.where(neighs_y == c)[0] if len(occ_class) >= 1: feats[c] = neighs_dist[occ_class[0]] / (neighs_dist[0] + self.eps) assert len(feats) == self.n_classes return_list += [feats] ''' 5. 5.1 Distance to Kth neighbor Think of this as of quantiles of a distribution 5.2 Distance to Kth neighbor normalized by distance to the first neighbor feat_51, feat_52 are answers to 5.1. and 5.2. should be scalars Do not forget to add self.eps to denominator. ''' for k in self.k_list: feat_51 = neighs_dist[k - 1] feat_52 = feat_51 / (neighs_dist[0] + self.eps) return_list += [[feat_51, feat_52]] ''' 6. Mean distance to neighbors of each class for each K from `k_list` For each class select the neighbors of that class among K nearest neighbors and compute the average distance to those objects If there are no objects of a certain class among K neighbors, set mean distance to 999 You can use `np.bincount` with appropriate weights Don't forget, that if you divide by something, You need to add `self.eps` to denominator. ''' for k in self.k_list: feats = np.bincount(neighs_y[:k], weights=neighs_dist[:k], minlength=self.n_classes) feats = feats / (np.bincount(neighs_y[:k], minlength=self.n_classes) + self.eps) feats[np.argwhere(feats == 0)] = 999 assert len(feats) == self.n_classes return_list += [feats] # merge knn_feats = np.hstack(return_list) assert knn_feats.shape == (239,) or knn_feats.shape == (239, 1) return knn_feats # - # ## Sanity check # To make sure you've implemented everything correctly we provide you the correct features for the first 50 objects. # + # a list of K in KNN, starts with one k_list = [3, 8, 32] # Load correct features true_knn_feats_first50 = np.load('./knn_feats_test_first50.npy') # Create instance of our KNN feature extractor NNF = NearestNeighborsFeats(n_jobs=1, k_list=k_list, metric='minkowski') # Fit on train set NNF.fit(X, Y) # Get features for test test_knn_feats = NNF.predict(X_test[:50]) # This should be zero print ('Deviation from ground thruth features: %f' % np.abs(test_knn_feats - true_knn_feats_first50).sum()) deviation =np.abs(test_knn_feats - true_knn_feats_first50).sum(0) for m in np.where(deviation > 1e-3)[0]: p = np.where(np.array([87, 88, 117, 146, 152, 239]) > m)[0][0] print ('There is a problem in feature %d, which is a part of section %d.' % (m, p + 1)) # - # Now implement parallel computations and compute features for the train and test sets. # ## Get features for test # Now compute features for the whole test set. for metric in ['minkowski', 'cosine']: print (metric) # Create instance of our KNN feature extractor NNF = NearestNeighborsFeats(n_jobs=4, k_list=k_list, metric=metric) # Fit on train set NNF.fit(X, Y) # Get features for test test_knn_feats = NNF.predict(X_test) # Dump the features to disk np.save('knn_feats_%s_test.npy' % metric , test_knn_feats) # ## Get features for train # Compute features for train, using out-of-fold strategy. # + # Differently from other homework we will not implement OOF predictions ourselves # but use sklearn's `cross_val_predict` from sklearn.model_selection import cross_val_predict from sklearn.model_selection import StratifiedKFold # We will use two metrics for KNN for metric in ['minkowski', 'cosine']: print (metric) # Set up splitting scheme, use StratifiedKFold # use skf_seed and n_splits defined above with shuffle=True skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=skf_seed) # Create instance of our KNN feature extractor # n_jobs can be larger than the number of cores NNF = NearestNeighborsFeats(n_jobs=4, k_list=k_list, metric=metric) # Get KNN features using OOF use cross_val_predict with right parameters preds = cross_val_predict(estimator=NNF, X=X, y=Y, cv=skf, n_jobs=4) # Save the features np.save('knn_feats_%s_train.npy' % metric, preds) # - # # Submit # If you made the above cells work, just run the following cell to produce a number to submit. # + s = 0 for metric in ['minkowski', 'cosine']: knn_feats_train = np.load('data/knn_feats_%s_train.npy' % metric) knn_feats_test = np.load('data/knn_feats_%s_test.npy' % metric) s += knn_feats_train.mean() + knn_feats_test.mean() answer = np.floor(s) print (answer) # - # Submit! # + from grader import Grader grader.submit_tag('statistic', answer) STUDENT_EMAIL = # EMAIL HERE STUDENT_TOKEN = # TOKEN HERE grader.status() grader.submit(STUDENT_EMAIL, STUDENT_TOKEN)
How_To_Win_A_Data_Science_Competition/week_4/notebooks/KNN_Features/Compute_KNN_features.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # # Vorlesungsinhalte 09.10.2020 (Raum 068C) # ## Bedingte Anweisung/Verzweigung (`if` und `else`) # Nicht immer ist der "Programmflow" linear und im Vorhinein festgelegt. Beispielsweise muss das Programm auf unterschiedliche Benutzereingaben auch unterschiedlich reagieren. Dafür gibt es die sogenannten bedingten Anweisungen und Verzweigungen. Im übertragenen Sinne ist das Konstrukt wie eine Weggabelung zu verstehen - je nachdem, welche Bedingung (z. B. "Ist heute Mittwoch?") erfüllt ist, wird eine andere "Strecke" gefahren. # # Über das Schlüsselwort `if` können wir eine konkrete Bedingung abfragen, also in diesem Fall `ist n gleich 42?`. Dafür können wir verschiedene Vergleichsoperatoren verwenden. Für die Gleichheit muss `==` verwendet werden, da `=` schon für die Zuweisung (Speichern eines Wertes in einer Variable, z. B. `x = 5`) reserviert ist. Außerdem kann dieser mit den bekannten Vergleichsoperatoren aus der Mathematik kombiniert werden: `<` (kleiner), `>` (größer), `<=` (kleiner oder gleich), `!=` (ungleich) usw. # **Beispiel:** Der Benutzer soll eine Ganzzahl `n` erraten und das Programm soll überprüfen, ob sie der gesuchten Zahl `42` entspricht. Dafür definieren wir eine Funktion, die `True` zurückgeben soll, falls der Benutzer die richtige Zahl `n` geraten hat, ansonsten `False`. # + def zahl_raten(n): if n == 42: # falls im Parameter 'n' der Wert '42' gespeichert ist ... return True # ... beende die Funktion und gebe `True` (wahr) zurück else: # in allen anderen Fällen ... return False # ... beende die Funktion und gebe `False` (falsch) zurück print(zahl_raten(42)) # - # Vor allem wenig komplexe Bedingungen, die über `if` und `else` abgefragt werden sollen, lassen sich teilweise vereinfachen: # + def zahl_raten_vereinfacht(n): return n == 42 # wird entweder zu 'True' (falls n = 42) oder 'False' (falls n != 42) print(zahl_raten_vereinfacht(42)) # - # Natürlich können auch mehrere Bedingungen bzw. Ausdrücke miteinander kombiniert werden. Dafür gibt es die sogenannten booleschen Operatoren. `or` (oder) bedeutet, dass entweder der linke oder der rechte oder beide Ausdrücke wahr sein müssen, damit der gesamte Ausdruck wahr ist. Bei `and` müssen sowohl der linke als auch der rechte Ausdruck wahr sein, damit der gesamte Ausdruck wahr wird. Mit `not` kann ein Ausdruck invertiert werden, `not True` ist also `False` und `not False` is `True`. # # **Beispiel anhand einer Wahrheitstabelle:** # # | Ausdruck `a` | Ausdruck `b` | `a and b` | `a or b` | # | :-: | :-: | :-: | :-: | # | False | False | **False** | **False** | # | False | True | **False** | **True** | # | True | False | **False** | **True** | # | True | True | **True** | **True** | # Möchte man zum Beispiel prüfen, ob `n == 42`, und falls nicht, ob `n == 0` ist, kann man das so lösen: n = 1 if n == 42 or n == 0: if n == 42: print("Du hast die Antwort auf alle Fragen gefunden!") else: print("'NICHTS' soll die Antwort sein?") # da 'n' nicht '42' ist und wir uns in der ersten Bedingung befinden, kann es nur noch '0' sein else: # für alle anderen Werte von 'n': print("Das war leider falsch.") # Man sieht auf den ersten Blick, dass der Code nicht besonders übersichtlich ist. Mit vielen Bedingungen kommt man schnell durcheinander, welches `else` zu welchem `if` gehört. Deshalb gibt es für solche Fälle eine weitere Variante: `elif` (else if). n = 1 if n == 42: # falls 'n' gleich '42' ist print("Du hast die Antwort auf alle Fragen gefunden!") elif n == 0: # falls 'n' NICHT gleich '42', aber '0' ist print("'NICHTS' soll die Antwort sein?") else: # alle anderen Werte von 'n' print("Das war leider falsch.") # Zudem kann man eine solche Bedingung auch direkt in das `return`-Statement einer Funktion einbauen: def echo(text): if(len(text) == 0): return "Leer" else: return text # ist das gleiche wie: def echo_einfach(text): return "Leer" if len(text) == 0 else text # Gebe 'Leer' zurück, falls die Länge des Strings in der Variable 'text' 0 ist, ansonsten den Text # ## AUFGABE: Eingaben eines Benutzers aufsummieren # Schreiben Sie eine Schleife, die den Benutzer so nach Zahlen fragt, bis er eine Null (0) eingibt. Am Ende soll die Summe der eingegebenen Zahlen ausgegeben werden. # + def aufsummieren(): # Wir definieren eine Funktion (def), die 'aufsummieren' heißt und keine Parameter '()' erwartet. x = 1 y = 0 # In dieser Variable speichern wir das Zwischenergebnis in jedem Schleifendurchlauf while True: # Diese Schleife wird endlos ausgeführt, da True immer 'wahr' ist ... x = int(input('Geben sie eine Zahl oder die Zahl 0 zum beenden ein:')) if x == 0: return y # ... außer der Benutzer gibt eine '0' ein else: y += x # Kurzform von y = y +x print(aufsummieren()) # Da wir in der Funktion das Ergebnis zurückgeben und nicht an der Konsole ausgeben ('print()'), müssen wir das hier tun # - # **Kommentar:** Wir haben uns hier für eine `While`-Schleife entschieden, da wir den Zähler (z. B. `i`) wie bei einer `for`-Schleife nicht benötigen. Zudem kann die Schleife über `While True` endlos ausgeführt und manuell im Schleifenrumpf (engl. "loop body") über `break` oder `return` abgebrochen werden kann, sobald eine Bedingung erfüllt ist. Weitere Informationen dazu gibt es z. B. auf [w3schools.com](https://www.w3schools.com/python/python_while_loops.asp). # ## AUFGABE: Eingaben eines Benutzers aufsummieren, bis er ein `x` oder nichts eingibt # Schreiben Sie eine Schleife, die den Benutzer so nach Zahlen fragt, bis er ein `x` (Hinweis: `String`) eingibt. Am Ende soll die Summe der eingegebenen Zahlen ausgegeben werden. # + def aufsummieren_bis_x(): x = 1 y = 0 while True: x = input('Geben sie eine Zahl oder x zum beenden ein:') if x == "x" or x = "": return y else: x = int(x) # Die Umwandlung in einen Integer darf erst hier passieren, da wir vorher auf den String 'x' prüfen möchten y += x print(aufsummieren_bis_x()) # - # # ## AUFGABE: Summe der Zahlen von `1` bis `n` # Schreiben Sie eine Funktion, die als Parameter eine Ganzzahl `n` erwartet. Die Funktion soll die Summe der Zahlen von `1` bis `n` berechnen und zurückgeben. def summe1bisn(n): x = 0 # Initialisieren der Variable, die die Summe speichern soll for i in range(1, n + 1): # Hinweis: range(n, m) = (n, n + 1, ..., m - 1) x += i return x # Wichtig: Das 'return' muss außerhalb der Schleife stehen, da sonst das Ergebnis immer ' 1' wäre (Einrückung beachten) # ## AUFGABE: Summe der Zahlen von `n` bis `m` # Schreiben Sie eine Funktion, die als Parameter zwei Ganzzahlen `m` und `n` erwartet. Die Funktion soll die Summe der Zahlen von `n` bis `m` berechnen und zurückgeben. def summe_n_m(n, m): x = 0 for i in range(n, m + 1): x += i return x # Falls der Benutzer für `n` den gleichen oder einen größeren Wert als für `m` eingibt, ist die Summe 0, da die Schleife nicht durchlaufen wird - die Abbruchbedingung ist bereits zu Beginn erfüllt. Um den Nutzer darauf hinzuweisen, können wir `if` und `else` benutzen: def summe_n_m_mit_hinweis(n, m): x = 0 if n > m or n == m: print("n muss kleiner als m sein!") # Hinweis für den Benutzer return x # Wir geben 'x' zurück (das dann immer '0' ist) else: for i in range(n, m + 1): x += i return x # ## AUFGABE: Ist die Eingabe eine Zahl? # Ein Benutzer gibt einen String beliebiger Länge über die Konsole ein. Unser Programm soll prüfen, ob der String nur aus Ganzzahlen besteht. Falls ja, soll die Funktion `True` zurückgeben, falls nein `False`. Hinweis: Es wird eine Schleife (loop) benötigt sowie mehrere if-Bedingungen. def string_pruefen(text): text = input() for buchstabe in text: if buchstabe == "0" or buchstabe == "1" or buchstabe == "2" or buchstabe == "3" or buchstabe == "4" or buchstabe == "5" or buchstabe == "6" or buchstabe == "7" or buchstabe == "8" or buchstabe == "9": # nicht besonders elegant, aber funktioniert print("Deutet auf eine Zahl hin") else: print("Abbruch, keine Zahl") return False return True # siehe Hinweis unten # **Hinweis:** Da wir den `text` nicht zu Integern umwandeln, muss mit den String `"0"` bis `"9"` vergleichen werden und nicht mit `0` bis `9`, da `9 == "9"` aufgrund der unterschiedlichen Typen immer `False` ergibt. Außerdem darf nicht vergessen werden, dass mit einer Variable und einem Vergleichsoperator verglichen wird. Beispiel: `if x == "0" or "1"` ist immer `True`, da `"1"` ein wahrer Ausdruck ist und `or` nur von mindestens einem der beiden Ausdrücke fordert, dass dieser `True` ist. Richtig ist `if x == "0" or x == "1"`. # Die Funktion darf im Positivfall, also wenn der String eine Zahl ist, erst außerhalb der Schleife beendet werden. Ansonsten würde die Funktion beim ersten Vorkommen einer Zahl bereits 'True' zurückgeben, wodurch das Programm z. B. auch die Eingabe '12ab' als valide Zahl "erkennen" würde. # # Der Schleifenkopf `for buchstabe in text:` macht in etwa folgendes: Er zerlegt den String `text` in die einzelnen Bestandteile (Buchstaben) und "speichert" in jeder Iteration der Schleife den jeweiligen Buchstaben in der Variable `buchstabe`. Siehe auch [w3schools.com](https://www.w3schools.com/python/python_for_loops.asp) (zweites Beispiel). # ## AUFGABE: Primzahltest # Gegeben ist eine Zahl `n`. `n` ist prim, wenn `n > 1` und `n` nur durch `1` und sich selbst (n) teilbar ist. Die zu schreibende Funktion soll `True` zurückgeben, falls die Zahl `n` prim ist, ansonsten `False`. def primzahltest(x): if x <= 1: return False # Falls die Zahl 1 oder kleiner ist, brauchen wir nicht weiter testen, es kann keine Primzahl sein else: for i in range(2, x): # ansonsten probieren wir, die Zahl durch alle Zahlen von 2 bis zu 'n - 1' zu teilen und schauen, ob der Rest 0 ergibt (bedeutet 'ist teilbar') if x % i == 0: return False return True # Für den Primzahltest verwenden wir den sogenannten `modulo`-Operator, der häufig mit `mod` oder (wie in Python) mit `%` abgekürzt wird. Er gibt den Rest zurück, der bei einer Division von zwei Zahlen übrigbleibt. Beispielsweise ist `12 % 10 = 2` oder `25 % 4 = 1`. # ## AUFGABE: Rekursive Fakultät # Die Fakultät einer Zahl `n` wird als `n!` notiert und beschreibt das Produkt aller Zahlen von `n` bis `1`. Beispielsweise ist `4! = 4 * 3 * 2 * 1 = 24`. Wie wir das über eine Schleife programmieren können haben wir bereits gesehen. Allerdings lässt sich `n!` auch als `n * (n - 1)!` aufschreiben. Folglich ist `4!` das gleiche wie `4 * 3!`, da `4 * (3 * 2 * 1) = 4 * 3 * 2 * 1`. Diese Gegebenheit können wir nutzen, um unsere Funktion `factorial` rekursiv mit `n - 1` aufzurufen und erhalten somit eine alternative und sehr kompakte Implementierungsmöglichkeit. def factorial(n): if n == 1: return 1 # Wenn wir bei 1 angelangt sind, geben wir 1 zurück, da '1! = 1' else: return n * factorial(n - 1) # Ansonsten rufen wir unsere Funktion 'factorial()' mit 'n - 1' als Parameter auf und multiplizieren den Rückgabewert mit 'n' # Zugegegebenermaßen sieht das erst einmal kompliziert aus. Wenn man sich nun aber die einzelnen Funktionsaufrufe und Werte von 'n' aufschreibt wird das Prinzip der Rekursion verständlich: # Im Fall von `6!` ("vier Fakultät") rufen wir in unserem Programm `factorial(n)` mit dem Wert `n = 6` (also `factorial(6)`) auf. # 1. Der Wert für n = 6. Da `n != 1` ist, geben wir `6 * factorial(5)` zurück. Zu diesem Zeitpunkt weiß das Programm aber noch nciht, was `factorial(5)` für einen Wert hat und "wartet" auf das Ergebnis dieser Funktion. # # 2. Der Wert für `n = 5`. Da `n != 1` ist, geben wir `5 * factorial(4)` zurück. # 3. Der Wert für `n = 4`. Da `n != 1` ist, geben wir `4 * factorial(3)` zurück. # 4. Der Wert für `n = 3`. Da `n != 1` ist, geben wir `3 * factorial(2)` zurück. # 5. Der Wert für `n = 2`. Da `n != 1` ist, geben wir `2 * factorial(1)` zurück. # 6. Der Wert für `n = 1`. Da `n == 1` nun wahr ist, geben wir den Wert `1` zurück. # # Nun kann das Programm von unten nach oben die jeweiligen Werte für `factorial(n)` bestimmen: # # --> 5. `factorial(1) = 1`, also geben wir `2 * 1 = 2` zurück. # # --> 4. `factorial(2) = 2`, also geben wir `3 * 2 = 6` zurück. # # --> 3. `factorial(3) = 6`, also geben wir `4 * 6 = 24` zurück. # # --> 2. `factorial(4) = 24`, also geben wir `5 * 24 = 120` zurück. # # --> 1. `factorial(5) = 120`, also geben wir `6 * 120 = 720` zurück. # # Wir sind wieder bei dem ursprünglichen Funktionsaufruf `factorial(6)` angekommen und können den Wert `720` zurückgeben. # ## Listen (Arrays) # In vielen Fällen möchte ich nicht nur einen Wert in einer Variable speichern, sondern z. B. auch eine dynamische Menge an Produkte in einem Warenkorb. Aus diesem Grund gibt es sogenannte Arrays (in Python "Listen"). Listen fangen *immer* bei `0` an, d.h. das erste Element steht an der Stelle `0` bzw. hat den Index `0`. Folglich besitzt das letzte Element den Index `Länge - 1`. Im folgenden einige Basics (mehr Informationen auf [w3schools.com](https://www.w3schools.com/python/python_lists.asp)). leere_liste = [] # sagt Python, dass ich eine leere Liste erstellen möchte liste = ["A", "B", "C", "D"] # eine Liste mit vier Elementen vom Typ "String" laenge = len(liste) # ermittelt die Anzahl der Elemente (Länge) der Liste # Für den Zugriff auf bestimmte Elemente oder Elemente in einem Bereich einer Liste gibt es die `[]`-Syntax: # + erstes_element = liste[0] # speichert das erste Element (also "A") in der Variable 'erstes_element' letztes_element = liste[len(liste) - 1]) # greift auf das letzte Element (also "B") zu letztes_element_einfach = liste[-1] # greift auf das letzte Element (also "B") zu (schneller zu tippen und einfacher zu lesen) die_ersten_zwei_elemente = liste[0:2] # ["A", "B"] (wie auch bei 'range()' ist das letzte Element 'excluded', d.h. das Element an Index 2 wird NICHT ausgegeben) die_ersten_zwei_elemente_einfach = liste[:2] # ["A", "B"] (wenn bei '0' gestartet wird, kann man den ersten Index weglassen) ab_index_zwei = liste[2:] # ["C", "D"] (startet bei Index 2, d.h. dem dritten Element) liste[2] = "E" # ersetzt das dritte Element (Index 2) in der Liste durch "E", also "C" durch "E" ist_a_in_liste = if "A" in liste # speichert 'True' in Variable, falls "A" in der Liste enthalten ist, sonst 'False' (Datentypen beachten!) # - # Um beispielsweise alle Elemente einer Liste zu durchsuchen, kann ich eine Schleife benutzen. Python bietet dafür eine einfache Syntax an, die der Syntax aus dem Abschnitt "Ist die Eingabe eine Zahl?" gleicht: for element in liste: print(element) # gibt jedes Element der Liste einzeln aus # ## AUFGABE: Zahlen zählen # Der Benutzer kann über die Konsole beliebig viele Zahlen in einer Liste speichern. Gibt dieser ein "x" ein, wird er in der Konsole nach einer gesuchten Zahl gefragt. Nach der Eingabe dieser gibt das Programm aus, wie oft diese Zahl in der Liste gespeichert wurde. # + def zahlen_zaehlen(): liste = [] # eine leere Liste initialisieren, damit Python weiß, dass wir eine dynamische Liste benötigen while True: x = input('Geben Sie eine Zahl oder x zum beenden ein:') if x == "x": return liste # beendet die Funktion und gibt die (gefüllte) Liste zurück else: x = int(x) # Wir wollen evtl. später mit den Zahlen rechnen, also macht die Speicherung als Integer Sinn liste.append(x) # '.append(element)' ermöglicht das Hinzufügen von Elementen an das Ende der Liste zahlen_liste = zahlen_zaehlen() # Wir speichern die Liste zwischen gesuchte_zahl = int(input("Welche Zahl soll gezählt werden?")) counter = 0 # Wir möchten eine Summe berechnen, beginnen folglich bei 0 for zahl in zahlen_liste: # wird für jedes Element (= Zahl) in der zahlen_liste durchlaufen if zahl == gesuchte_zahl: counter += 1 # erhöhe den Counter um 1 print(counter) # - # **Beispiel:** Gibt der Benutzer die Zahlen `1`, `2`, `2` und `4` gefolgt von einem `x` ein, sieht die `zahlen_liste` wie folgt aus: `[1, 2, 2, 4]`. Soll nun die Zahl `2` gezählt werden, gibt die Funktion `count(element)` eine `2` zurück. # # Mithilfe der Python-Bordmittel und -Funktionen kann man das Zählen auch kompakter lösen: Die Funktion '.count(element)' lässt sich ebenfalls auf der Liste aufrufen und gibt die Anzahl der Elemente aus der Liste, die dem Kriterium entsprechen, zurück. print(zahlen_liste.count(gesuchte_zahl)) # **Tipp:** Lassen Sie sich von Ihrer Entwicklungsumgebung (IDE = Integrated Development Environment) die möglichen Funktionen auf einer Liste anzeigen, indem Sie deN Variablennamen oder die leere Liste (`[]`) gefolgt von einem Punkt schreiben. Teilweise muss danach auch die Tastenkombination `STRG + Leertaste` gedrückt werden. Es wird eine Auswahl der möglichen Funktionen inklusive Beschreibung und Signatur (erwartete Parameter und Rückgabewerte) angezeigt. # ## AUFGABE: Buchstaben zählen # Die Aufgabe "Zahlen zählen" soll so angepasst werden, dass statt Zahlen nun die Buchstaben gezählt werden. In der hier präsentierten zweiten Ausbaustufe sollen auch die Elemente der Liste an sich (z. B. `["Test", "python", "nicht]`) berücksichtigt werden, sodass die Abfrage nach dem Buchstaben `t` das Ergebnis `4` liefert. Als Abbruchbedingung macht außerdem eine Zahl wie z. B. "0" mehr Sinn, da "x" ein valider Buchstabe ist. # # **Hinweis:** Die Strings können über die Funktion `.lower()` in Kleinbuchstaben oder über `.upper()` in Großbuchstaben konvertiert werden, da `A != a` (siehe z. B. [ASCII-Kodierung](https://de.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange)). # + # Listenbefüllungsteil def buchstaben_zaehlen(): liste = [] while True: eingabe = input('Geben Sie einen Buchstaben oder x zum beenden ein:') if eingabe == "0": # statt "x", da "x" ein Buchstabe ist return liste # abbrechen und 'liste' zurückgeben else: liste.append(eingabe) # eingegebenen Text zu 'liste' hinzufügen # Suchteil buchstaben_liste = buchstaben_zaehlen() # Buchstabenliste nach Befüllung durch den Benutzer zwischenspeichern zu_zaehlen = input("Welchen Buchstaben soll ich zählen? ") zu_zaehlen = zu_zaehlen.lower() # siehe Hinweis in der Aufgabenbeschreibung oben # Zählteil counter = 0 for element in buchstaben_liste: # buchstaben_liste ist z. B. ["ab", "cd", "af", "de"] for buchstabe in element: # element ist erst ["ab"], dann ["cd"] usw. buchstabe = buchstabe.lower() # siehe Hinweis in der Aufgabenbeschreibung oben if buchstabe == zu_zaehlen: # falls der aktuell untersuchte Buchstabe gleich dem zu zählenden Buchstabe ist ... counter += 1 # ... erhöhe die Zählersumme um eins print("Der Buchstabe {} wurde {} mal gefunden.".format(zu_zaehlen, counter)) # - # Damit wir unseren Code lesbarer gestalten, haben wir statt mehrerer `print()`-Anweisungen oder einer Anweisung wie `print("Der Buchstabe", zu_zaehlen, "wurde", counter, "mal gefunden")` einen `format`-String verwendet. Mit `{}` markieren wir Platzhalter, die über einen Aufruf der Funktion `format()` auf diesem String mit den entsprechenden Variablen (in diesem Fall `zu_zaehlen` und `counter`) als Parameter den "ausgefüllten" String zurückgibt, z. B. "Der Buchstabe a wurde 3 mal gefunden" im Fall der Eingabe von `["Abba", "Affe", "Fuchs"]`. # ## List Comprehensions # Ihr Auftraggeber möchte, dass Sie für eine Liste an Netto-Preisen seiner Produkte die Mehrwertsteuer (momentan 16 %) berechnen. Der einfachste Weg dazu wäre eine Schleife, die alle Elemente der Liste durchläuft und jeweils mit `1.19` multipliziert. # Python bietet u.a. für solche Fälle allerdings eine bequeme Schreibweise, die automatisch eine festgelegte Operation auf allen Elementen einer Liste ausführt, wenn diese eine Bedingung erfüllen. Für unser Beispiel sieht das so aus: # nettopreise = [2.00, 2.12, 11.22, 239.24, 93.84] nettopreise_verdoppelt = [x * 1.16 for x in nettopreise] # die Liste 'nettopreise_verdoppelt' soll alle Elemente aus der Liste 'nettopreise' mal den Mehrwertsteuersatz enthalten print(nettopreise_verdoppelt) # [2.32, 2.4592, 13.0152, 277.5184, 108.8544]
Vorlesungsinhalte/2020-10-09-Gruppe_Hammen.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 # --- # # Arena Kubeflow Pipeline Notebook demo # # ### Prepare data volume # # You should prepare data volume `user-susan` by following [docs](https://github.com/kubeflow/arena/blob/master/docs/userguide/4-tfjob-distributed-data.md). # # And run `arena data list` to check if it's created. # ! arena data list # ### Define the necessary environment variables and install the KubeFlow Pipeline SDK # We assume this notebook kernel has access to Python's site-packages and is in Python3. # # **Please fill in the below environment variables with you own settings.** # # - **KFP_PACKAGE**: The latest release of kubeflow pipeline platform library. # - **KUBEFLOW_PIPELINE_LINK**: The link to access the KubeFlow pipeline API. # - **MOUNT**: The mount configuration to map data above into the training job. The format is 'data:/directory' # - **GPUs**: The number of the GPUs for training. # KFP_SERVICE="ml-pipeline.kubeflow.svc.cluster.local:8888" KFP_PACKAGE = 'http://kubeflow.oss-cn-beijing.aliyuncs.com/kfp/0.1.14/kfp.tar.gz' KFP_ARENA_PACKAGE = 'http://kubeflow.oss-cn-beijing.aliyuncs.com/kfp-arena/kfp-arena-0.3.tar.gz' KUBEFLOW_PIPELINE_LINK = '' MOUNT="['user-susan:/training']" GPUs=1 # ### Install the necessary python packages # # Note: Please change pip3 to the package manager that's used for this Notebook Kernel. # !pip3 install $KFP_PACKAGE --upgrade # Note: Install arena's python package # !pip3 install $KFP_ARENA_PACKAGE --upgrade # ### 2. Define pipeline tasks using the kfp library. # + import arena import kfp.dsl as dsl @dsl.pipeline( name='pipeline to run jobs', description='shows how to run pipeline jobs.' ) def sample_pipeline(learning_rate='0.01', dropout='0.9', model_version='1'): """A pipeline for end to end machine learning workflow.""" # 1. prepare data prepare_data = arena.StandaloneOp( name="prepare-data", image="byrnedo/alpine-curl", data=MOUNT, command="mkdir -p /training/dataset/mnist && \ cd /training/dataset/mnist && \ curl -O https://code.aliyun.com/xiaozhou/tensorflow-sample-code/raw/master/data/t10k-images-idx3-ubyte.gz && \ curl -O https://code.aliyun.com/xiaozhou/tensorflow-sample-code/raw/master/data/t10k-labels-idx1-ubyte.gz && \ curl -O https://code.aliyun.com/xiaozhou/tensorflow-sample-code/raw/master/data/train-images-idx3-ubyte.gz && \ curl -O https://code.aliyun.com/xiaozhou/tensorflow-sample-code/raw/master/data/train-labels-idx1-ubyte.gz") # 2. prepare source code prepare_code = arena.StandaloneOp( name="source-code", image="alpine/git", data=MOUNT, command="mkdir -p /training/models/ && \ cd /training/models/ && \ if [ ! -d /training/models/tensorflow-sample-code ]; then https://github.com/cheyang/tensorflow-sample-code.git; else echo no need download;fi") # 3. train the models train = arena.StandaloneOp( name="train", image="tensorflow/tensorflow:1.11.0-gpu-py3", gpus=GPUs, data=MOUNT, command="echo %s; \ echo %s; \ python /training/models/tensorflow-sample-code/tfjob/docker/mnist/main.py --max_steps 500 --data_dir /training/dataset/mnist --log_dir /training/output/mnist" % (prepare_data.output, prepare_code.output), metric_name="Train-accuracy", metric_unit="PERCENTAGE", ) # 4. export the model export_model = arena.StandaloneOp( name="export-model", image="tensorflow/tensorflow:1.11.0-py3", data=MOUNT, command="echo %s; \ python /training/models/tensorflow-sample-code/tfjob/docker/mnist/export_model.py --model_version=%s --checkpoint_step=400 --checkpoint_path=/training/output/mnist /training/output/models" % (train.output,model_version)) # + learning_rate = "0.001" dropout = "0.8" model_verison = "1" arguments = { 'learning_rate': learning_rate, 'dropout': dropout, 'model_version': model_version, } import kfp client = kfp.Client(host=KUBEFLOW_PIPELINE_LINK) run = client.create_run_from_pipeline_func(sample_pipeline, arguments=arguments).run_info print('The above run link is assuming you ran this cell on JupyterHub that is deployed on the same cluster. ' + 'The actual run link is ' + KUBEFLOW_PIPELINE_LINK + '/#/runs/details/' + run.id) # -
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/arena-samples/standalonejob/standalone_pipeline.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 # --- # # Problem set 1: Solving the consumer problem # [<img src="https://mybinder.org/badge_logo.svg">](https://mybinder.org/v2/gh/NumEconCopenhagen/exercises-2019/master?urlpath=lab/tree/PS1/problem_set_1.ipynb) # In this first problem set, we will take a look at solving the canonical utility maximization problem for the consumer. # **Problem set structure:** Each problem set consists of tasks and problems. _Tasks_ train you in using specific techniques, while _problems_ train you in solving actual economic problems. Each problem set also contains solutions in hidden cells. *You should really try to solve the tasks and problems on your own before looking at the answers!* You goal should, however, not be to write everything from scratch. Finding similar code from the lectures and adjusting it is completely ok. I rarely begin completely from scratch, I figure out when I last did something similar and copy in the code to begin with. A quick peak at the solution, and then trying to write the solution yourself is also a very beneficial approach. # **Multiple solutions:** Within the field of numerical analysis there is often many more than one way of solving a specific problem. So the solution provided is just one example. If you get the same result, but use another approach, that might be just as good (or even better). # **Extra problems:** Solutions to the extra problems are not provided, but we encourage you to take a look at them if you have the time. You can share your solution with your fellow students following this [guide](https://numeconcopenhagen.netlify.com/guides/snippets/). # **Download guide:** # # 1. Follow the installation [guide](https://numeconcopenhagen.netlify.com/guides/python-setup/) in detail # 2. Open VScode # 3. Pres <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> # 4. Write `git: clone` + <kbd>Enter</kbd> # 5. Write `https://github.com/NumEconCopenhagen/exercises-2019` + <kbd>Enter</kbd> # # Tasks # ## functions # Implement a Python version of this function: # $$ # u(x_1,x_2) = (\alpha x_1^{-\beta} + (1-\alpha) x_2^{-\beta})^{-1/\beta} # $$ alpha, beta= 0.5, 1 u_lambda = lambda x1, x2 : (alpha*x1**(-beta) + (1-alpha)*x2**(-beta))**(-1/beta) u_lambda(1.5,0.5) # ?u_lambda # **Answer:** def u(x1,x2,alpha=0.5,beta=1): return (alpha*x1**(-beta) + (1-alpha)*x2**(-beta))**(-1/beta) u(1.5,0.5) # ## print x1_vec = [1.05,1.3,2.3,2.5,3.1] x2_vec = [1.05,1.3,2.3,2.5,3.1] # Construct a Python function `print_table(x1_vec,x2_vec)` to print values of `u(x1,x2)` in the table form shown below. # + # update this code def print_table(x1_vec,x2_vec): # a. empty text text = '' # b. top header text += f'{"":3}' for j, x2 in enumerate(x2_vec): text += f'{j:6d}' text += '\n' # line shift # c. body for i, x1 in enumerate(x1_vec): text += f'{i:3d} ' for x2 in x1_vec: text += f'{u(x1,x2):6.3f}' text += '\n' # line shift # d. print print(text) print_table(x1_vec,x2_vec) # - # **Answer:** # + def print_table(x1_vec,x2_vec): # a. empty text text = '' # b. top header text += f'{"":3s}' for j, x2 in enumerate(x2_vec): text += f'{j:6d}' text += '\n' # line shift # c. body for i,x1 in enumerate(x1_vec): if i > 0: text += '\n' # line shift text += f'{i:3d} ' # left header for j, x2 in enumerate(x2_vec): text += f'{u(x1,x2):6.3f}' # d. print print(text) print_table(x1_vec,x2_vec) # - # ## matplotlib # Reproduce the figure below of \\(u(x_1,x_2)\\) using the `meshgrid` function from _numpy_ and the `plot_surface` function from _matplotlib_. # + # evaluate utility function import numpy as np x1_grid,x2_grid = np.meshgrid(x1_vec,x2_vec,indexing='ij') u_grid = u(x1_grid,x2_grid) # import plot modules # %matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm # for colormaps fig = plt.figure() # create the figure ax = fig.add_subplot(1,1,1,projection='3d') # create a 3d axis in the figure ax.plot_surface(x1_grid,x2_grid,u_grid, cmap=cm.jet); # create surface plot in the axis # b. add labels ax.set_xlabel('$x_1$') ax.set_ylabel('$x_2$') ax.set_zlabel('$u$') # c. invert xaxis ax.invert_xaxis() # d. remove background ax.xaxis.pane.fill = False ax.yaxis.pane.fill = False ax.zaxis.pane.fill = False fig.tight_layout() # - # **Answer:** # + # a. plot fig = plt.figure() ax = fig.add_subplot(1,1,1,projection='3d') ax.plot_surface(x1_grid,x2_grid,u_grid,cmap=cm.jet) # b. add labels ax.set_xlabel('$x_1$') ax.set_ylabel('$x_2$') ax.set_zlabel('$utility,u$') # c. invert xaxis ax.invert_xaxis() # - # ## optimize # Consider the following minimization problem: # # $$ # \min_x f(x) = \min_x \sin(x) + 0.05 \cdot x^2 # $$ # Solve this problem and illustrate your results. # + # update this code # a. define function def f(x): return np.sin(x)+0.05*x**2 # b. solution using a loop N = 100 x_vec = np.linspace(-10,10,N) f_vec = np.empty(N) f_best = np.inf # initial maximum x_best = np.nan # not-a-number for i,x in enumerate(x_vec): f_now = f_vec[i] = f(x) if f_now<f_best: f_best = f_now x_best = x # c. solution using scipy optmize from scipy import optimize x_guess = [0] objective_function = lambda x: np.sin(x)+0.05*x**2 res = optimize.minimize(objective_function,x_guess) x_best_scipy = res.x[0] f_best_scipy = res.fun # d. print print(f'best with loop is {f_best:.8f} at x = {x_best:.8f}') print(f'best with scipy.optimize is {f_best_scipy:.8f} at x = {x_best_scipy:.8f}') # e. figure fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(x_vec,f_vec,ls='--',lw=2,color='black',label='$f(x)$') ax.plot(x_best,f_best,ls='',marker='s',color='blue',label='loop') ax.plot(x_best_scipy,f_best_scipy,ls='',marker='o', markersize=10,markerfacecolor='none', markeredgecolor='red',label='scipy.optimize') ax.set_xlabel('$x$') ax.set_ylabel('$f$') ax.grid(True) ax.legend(loc='upper center') fig.tight_layout() # - # **Answer:** # + # a. define function def f(x): return np.sin(x)+0.05*x**2 # b. solution using a loop import numpy as np N = 100 x_vec = np.linspace(-10,10,N) f_vec = np.empty(N) f_best = np.inf # initial maximum x_best = np.nan # not-a-number for i,x in enumerate(x_vec): f_now = f_vec[i] = f(x) if f_now < f_best: x_best = x f_best = f_now # c. solution using scipy optmize from scipy import optimize x_guess = [0] objective_function = lambda x: f(x[0]) res = optimize.minimize(objective_function, x_guess, method='Nelder-Mead') x_best_scipy = res.x[0] f_best_scipy = res.fun # d. print print(f'best with loop is {f_best:.8f} at x = {x_best:.8f}') print(f'best with scipy.optimize is {f_best_scipy:.8f} at x = {x_best_scipy:.8f}') # e. figure import matplotlib.pyplot as plt fig = plt.figure() # dpi = dots-per-inch (resolution) ax = fig.add_subplot(1,1,1) ax.plot(x_vec,f_vec,ls='--',lw=2,color='black',label='$f(x)$') ax.plot(x_best,f_best,ls='',marker='s',color='blue',label='loop') ax.plot(x_best_scipy,f_best_scipy,ls='',marker='o', markersize=10,markerfacecolor='none', markeredgecolor='red',label='scipy.optimize') ax.set_xlabel('$x$') ax.set_ylabel('$f$') ax.grid(True) ax.legend(loc='upper center'); # - # # Problem # Consider the following $M$-good, $x=(x_1,x_2,\dots,x_M)$, **utility maximization problem** with exogenous income $I$, and price-vector $p=(p_1,p_2,\dots,p_M)$, # # $$ # \begin{aligned} # V(p_{1},p_{2},\dots,,p_{M},I) & = \max_{x_{1},x_{2},\dots,x_M} x_{1}^{\alpha_1} x_{2}^{\alpha_2} \dots x_{M}^{\alpha_M} \\ # & \text{s.t.}\\ # E & = \sum_{i=1}^{M}p_{i}x_{i} \leq I,\,\,\,p_{1},p_{2},\dots,p_M,I>0\\ # x_{1},x_{2},\dots,x_M & \geq 0 # \end{aligned} # $$ # **Problem:** Solve the 5-good utility maximization problem for arbitrary preference parameters, \\( \alpha = (\alpha_1,\alpha_2,\dots,\alpha_5)\\), prices and income. First, with a loop, and then with a numerical optimizer. # You can use the following functions: # + def utility_function(x,alpha): # ensure you understand what this function is doing u = 1 for x_now,alpha_now in zip(x,alpha): u *= np.max(x_now,0)**alpha_now return u def expenditures(x,p): # ensure you understand what this function is doing E = 0 for x_now,p_now in zip(x,p): E += p_now*x_now return E def print_solution(x,alpha,I,p): # you can just use this function # a. x values text = 'x = [' for x_now in x: text += f'{x_now:.2f} ' text += f']\n' # b. utility u = utility_function(x,alpha) text += f'utility = {u:.3f}\n' # c. expenditure vs. income E = expenditures(x,p) text += f'E = {E:.2f} <= I = {I:.2f}\n' # d. expenditure shares e = p*x/I text += 'expenditure shares = [' for e_now in e: text += f'{e_now:.2f} ' text += f']' print(text) # - # You can initially use the following parameter choices: alpha = np.ones(5)/5 p = np.array([1,2,3,4,5]) I = 10 # + import time # magics # conda install line_profiler # conda install memory_profiler # %load_ext line_profiler # %load_ext memory_profiler # - # Solving with a loop: # + # %%time # update this code N = 15 # number of points in each dimension fac = np.linspace(0,1,N) # vector betweein 0 and 1 x_max = I/p # maximum x so E = I u_best = -np.inf for x1 in fac: for x2 in fac: for x3 in fac: for x4 in fac: for x5 in fac: x = np.array([x1,x2,x3,x4,x5])*x_max E = expenditures(x,p) if E <= I: u_now = utility_function(x,alpha) if u_now>u_best: u_best = u_now x_best = x print_solution(x_best,alpha,I,p) # + # %%time # A faster version N = 15 # number of points in each dimension fac = np.linspace(0,1,N) # vector betweein 0 and 1 x_max = I/p # maximum x so E = I u_best = -np.inf for x1 in fac: for x2 in np.linspace(0,1-x1,N): for x3 in np.linspace(0,1-x1-x2,N): for x4 in np.linspace(0,1-x1-x2-x3,N): x5 = 1-x1-x2-x3-x4 x = np.array([x1,x2,x3,x4,x5])*x_max u_now = utility_function(x,alpha) if u_now>u_best: u_best = u_now x_best = x print_solution(x_best,alpha,I,p) # - # > **Extra:** The above code can be written nicer with the ``product`` function from ``itertools``. # Solving with a numerical optimizer: # + # update this code from scipy import optimize # a. contraint function (negative if violated) constraints = ({'type': 'ineq', 'fun': lambda x: I-expenditures(x,p)}) bounds = [(0,I/p_now) for p_now in p] # b. call optimizer initial_guess = (I/p)/6 # some guess, should be feasible res = optimize.minimize(lambda x : -utility_function(x,alpha),initial_guess, method='SLSQP',bounds=bounds,constraints=constraints) print(res.message) # check that the solver has terminated correctly # c. print result print_solution(res.x,alpha,I,p) # - # ## Solutions using loops # Using **raw loops**: # + jupyter={"source_hidden": true} N = 15 # number of points in each dimension fac = np.linspace(0,1,N) # vector betweein 0 and 1 x_max = I/p # maximum x so E = I u_best = -np.inf x_best = np.empty(5) for x1 in fac: for x2 in fac: for x3 in fac: for x4 in fac: for x5 in fac: x = np.array([x1,x2,x3,x4,x5])*x_max E = expenditures(x,p) if E <= I: u_now = utility_function(x,alpha) if u_now > u_best: x_best = x u_best = u_now print_solution(x_best,alpha,I,p) # - # Using **smart itertools loop:** # + # %%time import itertools as it N = 15 # number of points in each dimension fac = np.linspace(0,1,N) # vector betweein 0 and 1 x_max = I/p # maximum x so E = I x_best = np.empty(5) u_best = -np.inf for x in it.product(fac, repeat =5): x *= x_max E = expenditures(x,p) if E <= I: u_now = utility_function(x,alpha) if u_now > u_best: x_best = x u_best = u_now print_solution(x_best,alpha,I,p) # + # %%time import itertools as it N = 15 # number of points in each dimension fac = np.linspace(0,1,N) # vector betweein 0 and 1 x_max = I/p # maximum x so E = I x_best = np.empty(5) u_best = -np.inf for x1_4 in it.product(fac,repeat=4): #x5 has been removed income_share = np.sum(x1_4) if income_share<=1: x = x1_4 + ((1-income_share),) # add x5 using monotonicity (requiring that all income is spent) # Because it.product ouput tuples, which are imutable, we have to create a new x x *= x_max u_now = utility_function(x,alpha) if u_now > u_best: x_best = x u_best = u_now print_solution(x_best,alpha,I,p) # - print(f'Combinations for old loop: {15**5}') print(f'Combinations for new loop: {15**4}') # ## Solutions using solvers from scipy import optimize # Solution using a **constrained optimizer:** # + # a. contraint function (negative if violated) constraints = ({'type': 'ineq', 'fun': lambda x: I-expenditures(x,p)}) bounds = [(0,I/p_now) for p_now in p] # b. call optimizer initial_guess = (I/p)/6 # some guess, should be feasible res = optimize.minimize( lambda x: -utility_function(x,alpha),initial_guess, method='SLSQP',bounds=bounds,constraints=constraints) print(res.message) # check that the solver has terminated correctly # c. print result print_solution(res.x,alpha,I,p) # - # Solution using an **unconstrained optimizer:** # + # a. define objective function def unconstrained_objective(x,alpha,I,p): penalty = 0 E = expenditures(x,p) if E >= I: ratio = I/E x *= ratio # now p*x = I penalty = 1000*(E-I)**2 u = utility_function(x,alpha) return -u + penalty # note: # "-u" because we are minimizing # "+ penalty" because the minimizer # will then avoid the E > I # b. call optimizer initial_guess = (I/p)/6 res = optimize.minimize( unconstrained_objective,initial_guess, method='Nelder-Mead',args=(alpha,I,p),options={'maxiter':5000},tol=1e-10) print(res.message) # c. print result print_solution(res.x,alpha,I,p) # - # # Extra Problems # ## Cost minimization # Consider the following 2-good **cost minimziation problem** with required utility $u_0$, and price-vector $p=(p_1,p_2)$, # # $$ # \begin{aligned} # E(p_{1},p_{2},u_0) & = \min_{x_{1},x_{2}} p_1 x_1+p_2 x_2\\ # & \text{s.t.}\\ # x_{1}^{\alpha}x_{2}^{1-\alpha} & \geq u_0 \\ # x_{1},x_{2} & \geq 0 # \end{aligned} # $$ # **Problem:** Solve the 2-good cost-minimization problem with arbitrary required utility, prices and income. Present your results graphically showing that the optimum is a point, where a budgetline is targent to the indifference curve through $u_0$. # ## Classy solution # **Problem:** Implement your solution to the utility maximization problem and/or the cost minimization problem above in a class as seen in Lecture 3.
PS1/problem_set_1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/SamuelLawrence876/Jamaica-stock-exchange-quantative-analysis/blob/master/Quantitative_analysis_with_the_JSE.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="hTxAx_qEsrY8" colab_type="text" # # This notebook serves as an introuction into using quantative finacne python modules on jamaican stocks # + [markdown] id="YF_Ycx12FeE1" colab_type="text" # What stocks will we be choosing? # # # * Caribbean Cement # * Seprod # * Jamaica Broilers # * Jamacia Producers # * Sagicor # * Grace Kennedy # * Lasco Distribution # * JMMB # * MIL # # Why did we choose these stocks? We wanted a combination of stocks from both the finacial as well as manufacuring and distrubution sector. # + id="20jO2EvhdWfl" colab_type="code" colab={} pip install git+https://github.com/pmorissette/ffn.git #ffn library isn't update with current git files # + id="_vHTQf1nuTQ-" colab_type="code" colab={} import pandas as pd import ffn # %pylab inline # + [markdown] id="--ghPleB5xAo" colab_type="text" # ## Pulling data from the Jamaica Stock Exhange # + id="z9QHcqU_wpcD" colab_type="code" colab={} JBG = 'https://www.jamstockex.com/market-data/download-data/price-history/JBG/2015-08-09/2020-09-07' df0 = pd.read_html(JBG) df0 = df0[0] str_val0 = 'JBG' df0 = df0.rename(columns={'Close Price ($)': str_val0}) # + id="Nzp7niSxPUk0" colab_type="code" colab={} CCC = 'https://www.jamstockex.com/market-data/download-data/price-history/CCC/2015-08-09/2020-09-07' df1 = pd.read_html(CCC) df1 = df1[0] str_val1 = 'CCC' df1 = df1.rename(columns={'Close Price ($)': str_val1}) # + id="XeddLYWAS2_J" colab_type="code" colab={} SEP = 'https://www.jamstockex.com/market-data/download-data/price-history/SEP/2015-08-09/2020-09-07' df2 = pd.read_html(SEP) df2 = df2[0] str_val2 = 'SEP' df2 = df2.rename(columns={'Close Price ($)': str_val2}) # + id="DcTpLcSgS3B5" colab_type="code" colab={} SJ = 'https://www.jamstockex.com/market-data/download-data/price-history/SJ/2015-08-09/2020-09-07' df3 = pd.read_html(SJ) df3 = df3[0] str_val3 = 'SJ' df3 = df3.rename(columns={'Close Price ($)': str_val3}) # + id="Wx77lrpxS3OA" colab_type="code" colab={} JP = 'https://www.jamstockex.com/market-data/download-data/price-history/JP/2015-08-09/2020-09-07' df4 = pd.read_html(JP) df4 = df4[0] str_val4 = 'JP' df4 = df4.rename(columns={'Close Price ($)': str_val4}) # + id="7sXK-TMGS3Sf" colab_type="code" colab={} GK = 'https://www.jamstockex.com/market-data/download-data/price-history/GK/2015-08-09/2020-09-07' df5 = pd.read_html(GK) df5 = df5[0] str_val5 = 'GK' df5 = df5.rename(columns={'Close Price ($)': str_val5}) # + id="_DSRB8BJS3L5" colab_type="code" colab={} LASD = 'https://www.jamstockex.com/market-data/download-data/price-history/LASD/2015-08-09/2020-09-07' df6 = pd.read_html(LASD) df6 = df6[0] str_val6 = 'LASD' df6 = df6.rename(columns={'Close Price ($)': str_val6}) # + id="VEdghWblS3Jr" colab_type="code" colab={} JMMBGL = 'https://www.jamstockex.com/market-data/download-data/price-history/JMMBGL/2015-08-09/2020-09-07' df7 = pd.read_html(JMMBGL) df7 = df7[0] str_val7 = 'JMMBGL' df7 = df7.rename(columns={'Close Price ($)': str_val7}) # + id="uR6zgNVqS3G8" colab_type="code" colab={} MIL = 'https://www.jamstockex.com/market-data/download-data/price-history/MIL/2015-08-09/2020-09-07' df8 = pd.read_html(MIL) df8 = df8[0] str_val8 = 'MIL' df8 = df8.rename(columns={'Close Price ($)': str_val8}) # + [markdown] id="yQnli2pftByx" colab_type="text" # ## Creating Data frames from data / making data readable by ffn API # + id="PnBcMaDIS7Bn" colab_type="code" colab={} df = pd.concat([df0, df1, df2, df3, df4, df5, df6, df7, df8], axis=1) # + id="wb4l-uH5yRbR" colab_type="code" colab={} df = df[['Date', str_val0, str_val1, str_val2, str_val3, str_val4, str_val5, str_val6, str_val7, str_val8]] # + id="LhGgZ5kWyRhl" colab_type="code" colab={} df = df.loc[:,~df.columns.duplicated()] # + [markdown] id="BiDGXcy4M2CO" colab_type="text" # How does our data look # + id="3x0t591Kj83b" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 197} outputId="fdb0fef3-3829-44f3-b091-eac8a53328a2" df.head() # + id="iI64h1q8z4V0" colab_type="code" colab={} df['Date'] = pd.to_datetime(df.Date) # + id="zYR9yKGLz4ad" colab_type="code" colab={} df['Date'] = df['Date'].dt.strftime('%m/%d/%Y') # + id="G4V3NBHuyRjy" colab_type="code" colab={} df.to_csv('df.csv', index=False) # + [markdown] id="B4TqzIettVBt" colab_type="text" # # Placing data into FFN format # + id="eTCK5uAKwpmW" colab_type="code" colab={} data = ffn.data.get(str_val0, provider=ffn.data.csv, path='df.csv') data = ffn.data.get(str_val1, provider=ffn.data.csv, path='df.csv', existing=data) data = ffn.data.get(str_val2, provider=ffn.data.csv, path='df.csv', existing=data) data = ffn.data.get(str_val3, provider=ffn.data.csv, path='df.csv', existing=data) data = ffn.data.get(str_val4, provider=ffn.data.csv, path='df.csv', existing=data) data = ffn.data.get(str_val5, provider=ffn.data.csv, path='df.csv', existing=data) data = ffn.data.get(str_val6, provider=ffn.data.csv, path='df.csv', existing=data) data = ffn.data.get(str_val7, provider=ffn.data.csv, path='df.csv', existing=data) # + id="qJzxDIwxITAo" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 227} outputId="121ed39a-9cd1-44f7-98c5-ad2c091435fc" data.head() # + [markdown] id="ttCpFZqLtgrY" colab_type="text" # # Analysis # + id="LpeMFd0yyHkm" colab_type="code" colab={} GS = ffn.GroupStats(data) # + id="eEM3mkt11cZV" colab_type="code" colab={} GS.set_riskfree_rate(.03) # Setting risk free rate at 3% # + [markdown] id="8pR3fO-BzyU2" colab_type="text" # Data summary # + id="zg0lEdQe1hPK" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="f047fa48-4253-41fc-f2a7-c657c52c3387" GS.display() # + [markdown] id="3qZWxOgpNJsZ" colab_type="text" # Key insights over the 5 year period: # # # * Best year performer: Sajicor # * Worst performer: Jamaica producers # * Best investment based on risk/reward: jmmbgl # * CCC Has potential for biggest return given the drawdown % from COVID # + id="wRimVlKI0Wxk" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 317} outputId="d0f0e09e-afb9-41d9-932b-d7633f04a298" GS.display_lookback_returns() # + [markdown] id="MNeIFAw-7Fa3" colab_type="text" # max drawdown of a price series # + id="F7cVCI3P7FgR" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="f797172d-6ba1-4ab1-f968-b345505b9760" ffn.calc_max_drawdown(data) # + [markdown] id="4smE3LG32fw_" colab_type="text" # CAGR (compound annual growth rate) for a given price series. # + id="--2CzB9O1GDu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="cc720f2c-7328-4934-ec07-fc6e5f38a142" ffn.calc_cagr(data) # + [markdown] id="EQquJ8q025r9" colab_type="text" # Calmar Ratio - function of a fund's average compounded annual rate of return versus its maximum drawdown # + id="ADtAlizs241u" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="a82ea4f4-ad6d-49c8-e5d1-61ce95d22a52" ffn.calc_calmar_ratio(data) # + [markdown] id="6WWlIvFp2mjr" colab_type="text" # Returns # + id="qH28Slt6wpsh" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 227} outputId="93fe8f8f-fffd-4ed1-8395-6fa5273ec914" returns = data.to_log_returns().dropna() returns.head() # + [markdown] id="8n3x2WXlfSW5" colab_type="text" # Correlation of returns # + id="X4zJxM37fScz" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 353} outputId="3fbd293a-6778-4213-9c16-fb0562f9dcf1" returns.plot_corr_heatmap(figsize=(12,5)) # + [markdown] id="g6qsiuzY3nmO" colab_type="text" # clusters based on k-means clustering # + id="QqCUJqWr0Gdc" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 354} outputId="19643171-4b69-4cc2-b5eb-a1b8a1c9c97a" ffn.calc_clusters(returns=returns,n=5,plot=True) # + [markdown] id="nFC5vMeJ3wba" colab_type="text" # equal risk contribution / risk parity weights # + id="29AtlM223wiO" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="cb0825e3-18c7-4fd5-e8c6-9d05788012dc" ffn.calc_erc_weights(returns=returns) # + [markdown] id="iAQzsK8d4KBk" colab_type="text" # Histogram of returns, mostly normal distributions # + id="nqW0U71Jwpvf" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 715} outputId="a33795c4-3508-4a2f-f457-a53a45ddd1fe" ax = returns.hist(figsize=(12, 12)) # + [markdown] id="YFwNiMB1k1RV" colab_type="text" # Total return over the period (5 years) # + id="fNzF7_Bm3-Y5" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="e636cb0b-5592-4b16-8aec-083b409b05ad" ffn.calc_total_return(data) # + [markdown] id="638tnPog6ZLH" colab_type="text" # weights that are inversely proportional to the stock's volatility resulting in a set of portfolio weights where each position has the same level of volatility. # # # + id="9RppL8VR6SdJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="684ed9fe-dc6e-45e5-ca13-dd23a21a0748" ffn.calc_inv_vol_weights(returns) # + id="GlV8R7va3-kD" colab_type="code" colab={} perf = data.calc_stats() # + [markdown] id="C2VbV1wBlK4F" colab_type="text" # Plot of stock prices # + id="c0fE7YHd3-mp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="2567de68-7357-468a-fa6e-8c70a11e89ae" perf.plot(figsize=(30,20)) # + [markdown] id="XPJDuJ27lr1I" colab_type="text" # mean-variance weights # + id="t9zuGDqo4JUx" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="ab625e6d-985c-45bc-9732-6d9982d0f876" returns.calc_mean_var_weights().as_format('.2%') # + [markdown] id="w178Koh98HTi" colab_type="text" # return / risk ratio ( without factoring in the risk-free rate. ) # + id="PfUmchh44JXT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="083413a2-2d76-4706-baa1-c1173936c85d" ffn.calc_risk_return_ratio(data) # + [markdown] id="kLRpxzzYPIjO" colab_type="text" # sortino ratio - measures the risk-adjusted return of an investment asset, portfolio, or strategy. It is a modification of the Sharpe ratio but penalizes only those returns falling below a user-specified target or required rate of return # + id="voL-pMGw4JaW" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="e3406273-1049-4558-c536-77b3dce983ec" ffn.calc_sortino_ratio(returns, rf=.05, nperiods=5, annualize=True) # # + [markdown] id="2OSiMjQSPNJP" colab_type="text" # Sharpe ratio - measures the performance of an investment compared to a risk-free asset, after adjusting for its risk. # + id="DVme4lHJ4MU3" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 176} outputId="8b921f4b-8c1c-4bc6-a1b4-5b850699bcf2" ffn.calc_sharpe(data, rf=0.05, nperiods=1, annualize=True) # + [markdown] id="OiOxXbnnmsqf" colab_type="text" # Implementation of <NAME>’s Fast Threshold Clustering Algorithm (FTCA) # + id="T1NLkA5j4MXc" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 123} outputId="5c42b213-7308-4635-dced-9709ff3986e9" returns.calc_ftca(threshold=0.1)
Quantitative_analysis_with_the_JSE.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] colab_type="text" id="view-in-github" # <a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/W2D1-postcourse-bugfix/tutorials/W2D2_LinearSystems/student/W2D2_Tutorial2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] colab_type="text" # # Neuromatch Academy 2020, Week 2, Day 2, Tutorial 2 # # # Markov Processes # # **Content Creators**: <NAME>, <NAME> # # **Content Reviewers**: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # + [markdown] colab_type="text" # --- # # Tutorial Objectives # # In this tutorial, we will look at the dynamical systems introduced in the first tutorial through a different lens. # # In Tutorial 1, we studied dynamical systems as a deterministic process. For Tutorial 2, we will look at **probabilistic** dynamical systems. You may sometimes hear these systems called _stochastic_. In a probabilistic process, elements of randomness are involved. Every time you observe some probabilistic dynamical system, started from the same initial conditions, the outcome will likely be different. Put another way, dynamical systems that involve probability will incorporate random variations in their behavior. # # For some probabilistic dynamical systems, the differential equations express a relationship between $\dot{x}$ and $x$ at every time $t$, so that the direction of $x$ at _every_ time depends entirely on the value of $x$. Said a different way, knowledge of the value of the state variables $x$ at time t is _all_ the information needed to determine $\dot{x}$ and therefore $x$ at the next time. # # This property --- that the present state entirely determines the transition to the next state --- is what defines a **Markov process** and systems obeying this property can be described as **Markovian**. # # The goal of Tutorial 2 is to consider this type of Markov process in a simple example where the state transitions are probabilistic. In particular, we will: # # * Understand Markov processes and history dependence. # * Explore the behavior of a two-state telegraph process and understand how its equilibrium distribution is dependent on its parameters. # # # + [markdown] colab_type="text" # --- # # Setup # + colab={} colab_type="code" import numpy as np import matplotlib.pyplot as plt # + cellView="form" colab={} colab_type="code" #@title Figure settings import ipywidgets as widgets # interactive display # %config InlineBackend.figure_format = 'retina' plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle") # + cellView="form" colab={} colab_type="code" #@title Helper Functions def plot_switch_simulation(t, x): fig = plt.figure() plt.plot(t, x) plt.title('State-switch simulation') plt.xlabel('Time') plt.xlim((0, 300)) # zoom in time plt.ylabel('State of ion channel 0/1', labelpad=-60) plt.yticks([0, 1], ['Closed (0)', 'Open (1)']) plt.show() return def plot_interswitch_interval_histogram(inter_switch_intervals): fig = plt.figure() plt.hist(inter_switch_intervals) plt.title('Inter-switch Intervals Distribution') plt.ylabel('Interval Count') plt.xlabel('time') plt.show() def plot_state_probabilities(time, states): fig = plt.figure() plt.plot(time, states[:,0], label='Closed to open') plt.plot(time, states[:,1], label='Open to closed') plt.legend() plt.xlabel('time') plt.ylabel('prob(open OR closed)') # + [markdown] colab_type="text" # --- # # Section 1: Telegraph Process # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 519} colab_type="code" outputId="d3b9f2a8-8e88-4f34-8bab-9deca3650ec2" #@title Video 1: Markov Process # Insert the ID of the corresponding youtube video from IPython.display import YouTubeVideo video = YouTubeVideo(id="xZO6GbU48ns", width=854, height=480, fs=1) print("Video available at https://youtu.be/" + video.id) video # + [markdown] colab_type="text" # Let's consider a Markov process with two states, where switches between each two states are probabilistic (known as a telegraph process). To be concrete, let's say we are modeling an **ion channel in a neuron that can be in one of two states: Closed (0) or Open (1)**. # # If the ion channel is Closed, it may transition to the Open state with probability $P(0 \rightarrow 1 | x = 0) = \mu_{c2o}$. Likewise, If the ion channel is Open, it transitions to Closed with probability $P(1 \rightarrow 0 | x=1) = \mu_{o2c}$. # # We simulate the process of changing states as a **Poisson process**. The Poisson process is a way to model discrete events where the average time between event occurrences is known but the exact time of some event is not known. Importantly, the Poisson process dictates the following points: # 1. The probability of some event occurring is _independent from all other events_. # 2. The average rate of events within a given time period is constant. # 3. Two events cannot occur at the same moment. Our ion channel can either be in an open or closed state, but not both simultaneously. # # In the simulation below, we will use the Poisson process to model the state of our ion channel at all points $t$ within the total simulation time $T$. # # As we simulate the state change process, we also track at which times thoughout the simulation the state makes a switch. We can use those times to measure the distribution of the time _intervals_ between state switches. # + [markdown] colab_type="text" # **Run the cell below** to show the state-change simulation process. Note that a random seed was set in the code block, so re-running the code will produce the same plot. Commenting out that line will produce a different simulation each run. # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 430} colab_type="code" outputId="5fad8266-7913-4c70-a085-0087533a83ac" # @title State-change simulation process # parameters T = 5000 # total Time duration dt = 0.001 # timestep of our simulation # simulate state of our ion channel in time # the two parameters that govern transitions are # c2o: closed to open rate # o2c: open to closed rate def ion_channel_opening(c2o, o2c, T, dt): # initialize variables t = np.arange(0, T, dt) x = np.zeros_like(t) switch_times = [] # assume we always start in Closed state x[0] = 0 # generate a bunch of random uniformly distributed numbers # between zero and unity: [0, 1), # one for each dt in our simulation. # we will use these random numbers to model the # closed/open transitions myrand = np.random.random_sample(size=len(t)) # walk through time steps of the simulation for k in range(len(t)-1): # switching between closed/open states are # Poisson processes if x[k] == 0 and myrand[k] < c2o*dt: # remember to scale by dt! x[k+1:] = 1 switch_times.append(k*dt) elif x[k] == 1 and myrand[k] < o2c*dt: x[k+1:] = 0 switch_times.append(k*dt) return t, x, switch_times c2o = 0.02 o2c = 0.1 np.random.seed(0) # set random seed t, x, switch_times = ion_channel_opening(c2o, o2c, T, .1) plot_switch_simulation(t,x) # + [markdown] colab_type="text" # ## Exercise 1 (2A): Computing intervals between switches # We now have `switch_times`, which is a list consisting of times when the state switched. Using this, calculate the time intervals between each state switch and store these in a list called `inter_switch_intervals`. # # We will then plot the distribution of these intervals. How would you describe the shape of the distribution? # # + colab={} colab_type="code" ############################################################################## ## TODO: Insert your code here to calculate between-state-switch intervals, ## and uncomment the last line to plot the histogram ############################################################################## # hint: see np.diff() # inter_switch_intervals = ... # plot_interswitch_interval_histogram(inter_switch_intervals) # + [markdown] colab={"base_uri": "https://localhost:8080/", "height": 433} colab_type="text" outputId="407f2b47-bc20-4723-9f97-f5ae3d2d98fb" # [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D2_LinearSystems/solutions/W2D2_Tutorial2_Solution_30701e58.py) # # *Example output:* # # <img alt='Solution hint' align='left' width=560 height=416 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W2D2_LinearSystems/static/W2D2_Tutorial2_Solution_30701e58_0.png> # # # + [markdown] colab_type="text" # We can also generate a bar graph to visualize the distribution of the number of time-steps spent in each of the two possible system states during the simulation. **Run the cell below** to visualize the distribution. # # # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 430} colab_type="code" outputId="1b4f1d75-b59b-4524-e167-ba6de9a14d7f" # @title Distribution of time spent in each state. states = ['Closed', 'Open'] (unique, counts) = np.unique(x, return_counts=True) plt.bar(states, counts) plt.ylabel('Number of time steps') plt.xlabel('State of ion channel'); # + [markdown] colab_type="text" # <!-- Though the system started initially in the Closed ($x=0$) state, over time, it settles into a equilibrium distribution where we can predict on what fraction of time it is Open as a function of the $\mu$ parameters. # # Before we continue exploring these distributions further, let's first take a look at the this fraction of Open states as a cumulative mean of the state $x$: --> # # Even though the state is _discrete_--the ion channel can only be either Closed or Open--we can still look at the **mean state** of the system, averaged over some window of time. # # Since we've coded Closed as $x=0$ and Open as $x=1$, conveniently, the mean of $x$ over some window of time has the interpretation of **fraction of time channel is Open**. # # Let's also take a look at the fraction of Open states as a cumulative mean of the state $x$. The cumulative mean tells us the average number of state-changes that the system will have undergone after a certain amount of time. **Run the cell below**. # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 431} colab_type="code" outputId="cab9f14b-ae8d-428d-cc57-aa737f99e962" # @title Cumulative mean of state plt.plot(t, np.cumsum(x) / np.arange(1, len(t)+1)) plt.xlabel('time') plt.ylabel('Cumulative mean of state'); # + [markdown] colab_type="text" # Notice in the plot above that, although the channel started in the Closed ($x=0$) state, gradually adopted some mean value after some time. This mean value is related to the transition probabilities $\mu_{c2o}$ # and $\mu_{o2c}$. # + [markdown] colab_type="text" # ## Interactive Demo: Varying transition probability values & T # # Using the interactive demo below, explore the state-switch simulation for different transition probability values of states $\mu_{c2o}$ and $\mu_{o2c}$. Also, try different values for total simulation time length *T*. # # Does the general shape of the inter-switch interval distribution change or does it stay relatively the same? How does the bar graph of system states change based on these values? # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 526, "referenced_widgets": ["0cb53bd8ab4c4371b28166f3b89f0c68", "fc03e6bf6c4841f8ac0f20746d302e68", "5aa7136ed3af4359b594468ca0b9a99b", "<KEY>", "bec5b78e22a342e0ba733362d6d5561b", "e32b1207067c40dabead946520475a43", "<KEY>", "<KEY>", "afce7d7951ed4e629fac35b4c6b40d89", "<KEY>", "485e8f8f88014f838f5305984ff67c41", "<KEY>", "2810d78a37dd46c686c7ee1397d28697"]} colab_type="code" outputId="8d82d162-6d77-432c-a3a8-74dd74ffa10c" #@title #@markdown Make sure you execute this cell to enable the widget! @widgets.interact def plot_inter_switch_intervals(c2o = (0,1, .01), o2c = (0, 1, .01), T=(1000,10000, 1000)): t, x, switch_times = ion_channel_opening(c2o, o2c, T, .1) inter_switch_intervals = np.diff(switch_times) #plot inter-switch intervals plt.hist(inter_switch_intervals) plt.title('Inter-switch Intervals Distribution') plt.ylabel('Interval Count') plt.xlabel('time') plt.show() plt.close() # + [markdown] colab={} colab_type="text" # [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D2_LinearSystems/solutions/W2D2_Tutorial2_Solution_ecb9dc3a.py) # # # + [markdown] colab_type="text" # --- # # Section 2: Distributional Perspective # # # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 519} colab_type="code" outputId="5f098500-bef5-4546-9d9b-03cd5105255b" #@title Video 2: State Transitions # Insert the ID of the corresponding youtube video from IPython.display import YouTubeVideo video = YouTubeVideo(id="U6YRhLuRhHg", width=854, height=480, fs=1) print("Video available at https://youtu.be/" + video.id) video # + [markdown] colab_type="text" # We can run this simulation many times and gather empirical distributions of open/closed states. Alternatively, we can formulate the exact same system probabilistically, keeping track of the probability of being in each state. # # <!-- Although the system started initially in the Closed ($x=0$) state, over time, it settles into a equilibrium distribution where we can predict on what fraction of time it is Open as a function of the $\mu$ parameters. --> # # (see diagram in lecture) # # The same system of transitions can then be formulated using a vector of 2 elements as the state vector and a dynamics matrix $\mathbf{A}$. The result of this formulation is a *state transition matrix*: # # $\left[ \begin{array}{c} C \\ O \end{array} \right]_{k+1} = \mathbf{A} \left[ \begin{array}{c} C \\ O \end{array} \right]_k = \left[ \begin{array} & 1-\mu_{\text{c2o}} & \mu_{\text{o2c}} \\ \mu_{\text{c2o}} & 1-\mu_{\text{o2c}} \end{array} \right] \left[ \begin{array}{c} C \\ O \end{array} \right]_k$. # # # Each transition probability shown in the matrix is as follows: # 1. $1-\mu_{\text{c2o}}$, the probability that the closed state remains closed. # 2. $\mu_{\text{c2o}}$, the probability that the closed state transitions to the open state. # 3. $\mu_{\text{o2c}}$, the probability that the open state transitions to the closed state. # 4. $1-\mu_{\text{o2c}}$, the probability that the open state remains open. # # # _Notice_ that this system is written as a discrete step in time, and $\mathbf{A}$ describes the transition, mapping the state from step $k$ to step $k+1$. This is different from what we did in the exercises above where $\mathbf{A}$ had described the function from the state to the time derivative of the state. # # + [markdown] colab_type="text" # ## Exercise 2 (2B): Probability Propagation # # Complete the code below to simulate the propagation of probabilities of closed/open of the ion channel through time. A variable called `x_kp1` (short for, $x$ at timestep $k$ plus 1) should be calculated per each step *k* in the loop. However, you should plot $x$. # + colab={} colab_type="code" def simulate_prob_prop(A, x0, dt, T): """ Simulate the propagation of probabilities given the transition matrix A, with initial state x0, for a duration of T at timestep dt. Args: A (ndarray): state transition matrix x0 (ndarray): state probabilities at time 0 dt (scalar): timestep of the simulation T (scalar): total duration of the simulation Returns: ndarray, ndarray: `x` for all simulation steps and the time `t` at each step """ # Initialize variables t = np.arange(0, T, dt) x = x0 # x at time t_0 # Step through the system in time for k in range(len(t)-1): ################################################################### ## TODO: Insert your code here to compute x_kp1 (x at k plus 1) raise NotImplementedError("Student exercise: need to implement simulation") ## hint: use np.dot(a, b) function to compute the dot product ## of the transition matrix A and the last state in x ## hint 2: use np.vstack to append the latest state to x ################################################################### # Compute the state of x at time k+1 x_kp1 = ... # Stack (append) this new state onto x to keep track of x through time steps x = ... return x, t # parameters T = 500 # total Time duration dt = 0.1 # timestep of our simulation # same parameters as above # c2o: closed to open rate # o2c: open to closed rate c2o = 0.02 o2c = 0.1 A = np.array([[1 - c2o*dt, o2c*dt], [c2o*dt, 1 - o2c*dt]]) # initial condition: start as Closed x0 = np.array([[1, 0]]) # Uncomment this to plot the probabilities # x, t = simulate_prob_prop(A, x0, dt, T) # plot_state_probabilities(t,x) # + [markdown] colab={"base_uri": "https://localhost:8080/", "height": 430} colab_type="text" outputId="b7d16b7a-4130-4b81-d10b-87a035087482" # [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D2_LinearSystems/solutions/W2D2_Tutorial2_Solution_f426cf5b.py) # # *Example output:* # # <img alt='Solution hint' align='left' width=558 height=414 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W2D2_LinearSystems/static/W2D2_Tutorial2_Solution_f426cf5b_0.png> # # # + [markdown] colab_type="text" # Here, we simulated the propagation of probabilities of the ion channel's state changing through time. Using this method is useful in that we can **run the simulation once** and see **how the probabilities propagate throughout time**, rather than re-running and empirically observing the telegraph simulation over and over again. # # Although the system started initially in the Closed ($x=0$) state, over time, it settles into a equilibrium distribution where we can predict what fraction of time it is Open as a function of the $\mu$ parameters. We can say that the plot above show this _relaxation towards equilibrium_. # # Re-calculating our value of the probability of $c2o$ again with this method, we see that this matches the simulation output from the telegraph process! # # # + colab={"base_uri": "https://localhost:8080/", "height": 52} colab_type="code" outputId="08290d22-8447-44d8-ccb3-4c866f1d1fdc" print("Probability of state c2o: %.3f"%(c2o / (c2o + o2c))) x[-1,:] # + [markdown] colab_type="text" # --- # # Section 3: Equilibrium of the telegraph process # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 519} colab_type="code" outputId="ff4541b5-56b1-427a-be95-fcd52af8392e" #@title Video 3: Continous vs. Discrete Time Formulation # Insert the ID of the corresponding youtube video from IPython.display import YouTubeVideo video = YouTubeVideo(id="csetTTauIh8", width=854, height=480, fs=1) print("Video available at https://youtu.be/" + video.id) video # + [markdown] colab_type="text" # Since we have now modeled the propagation of probabilities by the transition matrix $\mathbf{A}$ in Section 2, let's connect the behavior of the system at equilibrium with the eigendecomposition of $\mathbf{A}$. # # As introduced in the lecture video, the eigenvalues of $\mathbf{A}$ tell us about the stability of the system, specifically in the directions of the corresponding eigenvectors. # + colab={"base_uri": "https://localhost:8080/", "height": 69} colab_type="code" outputId="d29d7e0b-bd1b-425a-9ef2-bb8325006165" # compute the eigendecomposition of A lam, v = np.linalg.eig(A) # print the 2 eigenvalues print("Eigenvalues:",lam) # print the 2 eigenvectors eigenvector1 = v[:,0] eigenvector2 = v[:,1] print("Eigenvector 1:", eigenvector1) print("Eigenvector 2:", eigenvector2) # + [markdown] colab_type="text" # ## Exercise 3 (2C): Finding a stable state # # Which of these eigenvalues corresponds to the **stable** (equilibrium) solution? What is the eigenvector of this eigenvalue? How does that explain # the equilibrium solutions in simulation in Section 2 of this tutorial? # # _hint_: our simulation is written in terms of probabilities, so they must sum to 1. Therefore, you may also want to rescale the elements of the eigenvector such that they also sum to 1. These can then be directly compared with the probabilities of the states in the simulation. # + colab={} colab_type="code" ################################################################### ## Insert your thoughts here ################################################################### # + [markdown] colab={"base_uri": "https://localhost:8080/", "height": 52} colab_type="text" outputId="4dc32baf-8769-4d5b-ec79-aad4e61d086c" # [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D2_LinearSystems/solutions/W2D2_Tutorial2_Solution_5d5bcbfc.py) # # # + [markdown] colab_type="text" # --- # # Summary # # In this tutorial, we learned: # # * The definition of a Markov process with history dependence. # * The behavior of a simple 2-state Markov proces--the telegraph process--can be simulated either as a state-change simulation or as a propagation of probability distributions. # * The relationship between the stability analysis of a dynamical system expressed either in continuous or discrete time. # * The equilibrium behavior of a telegraph process is predictable and can be understood using the same strategy as for deterministic systems in Tutorial 1: by taking the eigendecomposition of the A matrix.
tutorials/W2D2_LinearSystems/student/W2D2_Tutorial2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # env: {} # interrupt_mode: signal # language: python # metadata: {} # name: python3 # --- # Seattle Weather Interactive # =========================== # This chart provides an interactive exploration of Seattle weather over the # course of the year. It includes a one-axis brush selection to easily # see the distribution of weather types in a particular date range. # # + # category: interactive import altair as alt alt.data_transformers.enable('json') from vega_datasets import data scale = alt.Scale(domain=['sun', 'fog', 'drizzle', 'rain', 'snow'], range=['#e7ba52', '#a7a7a7', '#aec7e8', '#1f77b4', '#9467bd']) color = alt.Color('weather:N', scale=scale) # We create two selections: # - a brush that is active on the top panel # - a multi-click that is active on the bottom panel brush = alt.selection_interval(encodings=['x']) click = alt.selection_multi(encodings=['color']) # Top panel is scatter plot of temperature vs time points = alt.Chart().mark_point().encode( alt.X('date:T', timeUnit='monthdate', axis=alt.Axis(title='Date')), alt.Y('temp_max:Q', axis=alt.Axis(title='Maximum Daily Temperature (C)'), scale=alt.Scale(domain=[-5, 40]) ), color=alt.condition(brush, color, alt.value('lightgray')), size=alt.Size('precipitation:Q', scale=alt.Scale(range=[5, 200])) ).properties( width=600, height=300, selection=brush ).transform_filter( click.ref() ) # Bottom panel is a bar chart of weather type bars = alt.Chart().mark_bar().encode( x='count()', y='weather:N', color=alt.condition(click, color, alt.value('lightgray')), ).transform_filter( brush.ref() ).properties( width=600, selection=click ) alt.vconcat(points, bars, data=data.seattle_weather.url, title="Seattle Weather: 2012-2015" )
notebooks/examples/seattle_weather_interactive.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # name: python2 # --- # + [markdown] colab_type="text" id="EheA5_j_cEwc" # ##### Copyright 2019 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # + colab={} colab_type="code" id="YCriMWd-pRTP" #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # + [markdown] colab_type="text" id="OvRwFTkqcp1e" # # Introduction to TensorFlow Part 3 - Advanced Tensor Manipulation # # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://colab.research.google.com/github/google/tf-quant-finance/blob/master/tf_quant_finance/examples/jupyter_notebooks/Introduction_to_TensorFlow.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> # </td> # <td> # <a target="_blank" href="https://github.com/google/tf-quant-finance/blob/master/tf_quant_finance/examples/jupyter_notebooks/Introduction_to_TensorFlow.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> # </td> # </table> # + cellView="form" colab={} colab_type="code" id="nPX9m7Q_w_8p" #@title Install and import Libraries for this colab. RUN ME FIRST! # !pip install matplotlib import matplotlib.pyplot as plt import tensorflow as tf tf.disable_eager_execution() # + [markdown] colab_type="text" id="obZHjPQScSqd" # # What this notebook covers # # This notebook carries on from [part 2](https://colab.research.google.com/github/google/tf-quant-finance/blob/master/tf_quant_finance/examples/jupyter_notebooks/Introduction_to_TensorFlow_Part_2_-_Debugging_and_Control_Flow.ipynb # ), and covers various advanced ways of manipulating tensors, including # * Scatter/Gather # * Sparse Tensors # * Various functional ops # # # # # + [markdown] colab_type="text" id="pVLqCYzuDhfT" # # Scatter / Gather # + [markdown] colab_type="text" id="_md9nF-EbCcn" # ## tf.gather_nd # # [Full documentation](https://www.tensorflow.org/api_docs/python/tf/gather_nd) # # This operation allows you to take a multi-dimensional tensor and extract a list of subsets of data from it, according to a list of indices. # + colab={"base_uri": "https://localhost:8080/", "height": 235} colab_type="code" executionInfo={"elapsed": 631, "status": "ok", "timestamp": 1568638253674, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mAuhiLGs9-CmN1BMtie2tWn3oucS__w2c4gNC6yBg=s64", "userId": "18064761308611293318"}, "user_tz": -60} id="z7nnDntT32V0" outputId="80c44424-c641-4504-c7d9-ae6ad71d8b11" source = tf.constant([[[111,112,113], [121,122,123], [131,132,133]], [[211,212,213], [221,222,223], [231,232,233]]]) with tf.Session() as sess: # if we specify all values for all of source's dimensions, then we get a # single value indices = [[1,1,1]] print("Looking up %s gives us\n%s" %( indices, sess.run(tf.gather_nd(source, indices)))) # we can look up multiple sets of indices indices = [[1,1,1], [0,0,0], [0,0,1]] print("\nLooking up %s gives us\n%s" %( indices, sess.run(tf.gather_nd(source, indices)))) # if we don't specify values for all of source's dimensions, then we get # results of larger shape indices = [[0,0]] print("\nLooking up %s gives us\n%s" %( indices, sess.run(tf.gather_nd(source, indices)))) indices = [[1]] print("\nLooking up %s gives us\n%s" %( indices, sess.run(tf.gather_nd(source, indices)))) # + [markdown] colab_type="text" id="9B9cza9zD4Iw" # The indices can easily be generated with tf.where_v2: # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 436, "status": "ok", "timestamp": 1568385897609, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mAuhiLGs9-CmN1BMtie2tWn3oucS__w2c4gNC6yBg=s64", "userId": "18064761308611293318"}, "user_tz": -60} id="npOjtvGYECW1" outputId="f2a94d9d-5420-4cb4-b30c-787660c35a4c" source = tf.constant([[[111,112,113], [121,122,123], [131,132,133]], [[211,212,213], [221,222,223], [231,232,233]]]) values_divisible_by_three = tf.gather_nd( source, tf.where_v2(tf.equal(0, source % 3))) with tf.Session() as sess: print(sess.run(values_divisible_by_three)) # + [markdown] colab_type="text" id="EfNajZEZG3sd" # ##tf.scatter_nd # # [Full documentation](https://www.tensorflow.org/api_docs/python/tf/scatter_nd) # # scatter_nd creates a zero-initialised tensor of a given shape, and then writes a series of specified values at specified positions in that tensor. # # # + colab={"base_uri": "https://localhost:8080/", "height": 756} colab_type="code" executionInfo={"elapsed": 656, "status": "ok", "timestamp": 1568708441852, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mAuhiLGs9-CmN1BMtie2tWn3oucS__w2c4gNC6yBg=s64", "userId": "18064761308611293318"}, "user_tz": -60} id="9dKH_Fg4H4R4" outputId="4210e38c-5e5d-4299-b471-f7cdd5b31e33" source = tf.constant([[[111,112,113], [121,122,123], [131,132,133]], [[211,212,213], [221,222,223], [231,232,233]]]) with tf.Session() as sess: print("Scattering single value:\n%s"%sess.run( tf.scatter_nd( indices = [[0,1,2]], updates = [1], shape = [2,3,3]))) print("\nScattering multiple values:\n%s"%sess.run( tf.scatter_nd( indices = [[0,0,0], [0,1,1], [0,2,2]], updates = [1,2,3], shape = [2,3,3]))) # You can reduce the dimensions of indices and increase the dimensions of # updates print("\nScattering entire rows:\n%s"%sess.run( tf.scatter_nd( indices = [[0,0], [0,1]], updates = [[1,2,3], [4,5,6]], shape = [2,3,3]))) print("\nScattering entire matrix:\n%s"%sess.run( tf.scatter_nd( indices = [[0]], updates = [[[1,2,3], [4,5,6], [7,8,9]]], shape = [2,3,3]))) # Note that if indices contains duplicate or overlapping values, then the # clashing updates will be added together (in an indeterminate order, which # may result in non-deterministic output in the case of multiple floating # point values of wildly different sizes). print("\nScattering single value multiple times:\n%s"%sess.run( tf.scatter_nd( indices = [[0,0,0], [0,0,0], [0,0,0]], updates = [1,2,3], shape = [2,3,3]))) # + [markdown] colab_type="text" id="kYiOe3ZsT05b" # ### Gather then Scatter # In some cases, you will want scatter_nd to act as a "setter" to gather_nd's "getter": i.e. you have a tensor, you extract a subset of values that meet a certain criteria using gather_nd, you calculate new values for that subset, and then create a new tensor based on the original that replaces the elements that met the criteria with the new values. # # There are two approaches you can take here, the first is to use where_v2: # + colab={"base_uri": "https://localhost:8080/", "height": 134} colab_type="code" executionInfo={"elapsed": 441, "status": "ok", "timestamp": 1568709877819, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mAuhiLGs9-CmN1BMtie2tWn3oucS__w2c4gNC6yBg=s64", "userId": "18064761308611293318"}, "user_tz": -60} id="gbpQx-xrU707" outputId="f5046ba6-5ec1-4940-de01-9d79496d178b" source = tf.constant([[[111,112,113], [121,122,123], [131,132,133]], [[211,212,213], [221,222,223], [231,232,233]]]) # create a boolean tensor the same shape as source is_divisible_by_three = tf.equal(0, source % 3) # create a list of indices where is_divisible_by_three is true indices = tf.where_v2(is_divisible_by_three) # extract a list of values that need updating values_divisible_by_three = tf.gather_nd(source, indices) # perform a really expensive operation on those values new_values = values_divisible_by_three % 100 # convert the list of new values back into a tensor the same shape as source # we need to force the type of shape to match that of indices shape = tf.shape(source, out_type=tf.dtypes.int64) new_values_or_zeros = tf.scatter_nd(indices, new_values, shape) # merge the new values into the original new_tensor = tf.where_v2(is_divisible_by_three, new_values_or_zeros, source) with tf.Session() as sess: print (sess.run(new_tensor)) # + [markdown] colab_type="text" id="OIMX9Vf-Zmdf" # The second approach is to subtract the original value from the updated value, and then you can just add the two tensors. # + colab={"base_uri": "https://localhost:8080/", "height": 134} colab_type="code" executionInfo={"elapsed": 443, "status": "ok", "timestamp": 1568710356563, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mAuhiLGs9-CmN1BMtie2tWn3oucS__w2c4gNC6yBg=s64", "userId": "18064761308611293318"}, "user_tz": -60} id="tMwh5kgAZ0aI" outputId="04aabaf3-8dfa-4dbd-e6ff-867baac23847" source = tf.constant([[[111,112,113], [121,122,123], [131,132,133]], [[211,212,213], [221,222,223], [231,232,233]]]) # create a list of indices where is_divisible_by_three is true (we no longer # need the to keep a reference to the result of tf.equal) indices = tf.where_v2(tf.equal(0, source % 3)) # extract a list of values that need updating values_divisible_by_three = tf.gather_nd(source, indices) # perform a really expensive operation on those values to get the value we want new_values = values_divisible_by_three % 100 new_values_minus_original = new_values - values_divisible_by_three # convert the list of new values back into a tensor the same shape as source # we need to force the type of shape to match that of indices shape = tf.shape(source, out_type=tf.dtypes.int64) new_values_or_zeros = tf.scatter_nd(indices, new_values_minus_original, shape) # now add the two tensors. For values that didn't meet the criteria this just # add 0 to the original value. For the values that did meet the criteria this # will add original_value + (value_we_want - original value) new_tensor = new_values_or_zeros + source with tf.Session() as sess: print (sess.run(new_tensor)) # + [markdown] colab_type="text" id="W6-o_3hTeCb1" # The addition approach is fractionally more efficient, and doesn't require the boolean tensor, but can hit accuracy problems in floating point. # + [markdown] colab_type="text" id="pnyntx09GpYW" # ### tf.scatter_nd_add/sub/update # # There are several other scatter_nd functions in tensorflow which are superficially similar to ```tf.scatter_nd```. They work using [Variables](https://www.tensorflow.org/guide/variables) which can have significant scalability/contention issues with larger graphs, especially when executing across distributed machines/hardware. # + [markdown] colab_type="text" id="FOqSOkTAH9No" # ## Exercise: Mandlebrot set # # Lets revisit the Mandlebrot set from the previous training course. In that solution, we ran the z=z*z+c calculation for all co-ordinates, even the ones whose magnitude had already gone over 2. # # For the purpose of this exercise, we will pretend that the complex calculation is very expensive and that we should eliminate the calculation where possible. In actual fact, the calculation is utterly trivial and swamped by the cost of the gather/scatter operations, but the same methods can be used in situations rather more expensive than a complex add and multiply # + colab={} colab_type="code" id="DZZxF2l0it9-" MAX_ITERATIONS = 64 NUM_PIXELS = 512 def generate_grid(nX, nY, bottom_left=(-1.0, -1.0), top_right=(1.0, 1.0)): """Generates a complex matrix of shape [nX, nY]. Generates an evenly spaced grid of complex numbers spanning the rectangle between the supplied diagonal points. Args: nX: A positive integer. The number of points in the horizontal direction. nY: A positive integer. The number of points in the vertical direction. bottom_left: The coordinates of the bottom left corner of the rectangle to cover. top_right: The coordinates of the top right corner of the rectangle to cover. Returns: A constant tensor of type complex64 and shape [nX, nY]. """ x = tf.linspace(bottom_left[0], top_right[0], nX) y = tf.linspace(bottom_left[1], top_right[1], nY) real, imag = tf.meshgrid(x, y) return tf.cast(tf.complex(real, imag), tf.complex128) c_values = generate_grid(NUM_PIXELS, NUM_PIXELS) initial_Z_values = tf.zeros_like(c_values, dtype=tf.complex128) initial_diverged_after = tf.ones_like(c_values, dtype=tf.int32) * MAX_ITERATIONS # You need to put the various values you want to change inside the loop here loop_vars = (0, initial_Z_values, initial_diverged_after) # this needs to take the same number of arguments as loop_vars contains and # return a tuple of equal size with the next iteration's values def body(iteration_count, Z_values, diverged_after): # a matrix of bools showing all the co-ordinatesthat haven't diverged yet not_diverged = tf.equal(diverged_after, MAX_ITERATIONS) # a list of the indices in not_diverged that are true not_diverged_indices = tf.where_v2(not_diverged) # you now need to gather just the Z and c values covered by # not_diverged_indices, calculate the new Z values, and then scatter the # values back into a new Z_values matrix to pass to the next iteration. new_Z_values = # TODO # And now we're back to the original code has_diverged = tf.abs(new_Z_values) > 2.0 new_diverged_after = tf.minimum(diverged_after, tf.where_v2( has_diverged, iteration_count, MAX_ITERATIONS)) return (iteration_count+1, new_Z_values, new_diverged_after) # this just needs to take the same number of arguments as loop_vars contains and # return true (we'll use maximum_iterations to exit the loop) def cond(iteration_count, Z_values, diverged_after): return True loop = tf.compat.v1.while_loop( loop_vars=loop_vars, body = body, cond = cond, maximum_iterations=MAX_ITERATIONS) with tf.Session() as sess: results = sess.run(loop) ## extract the final value of diverged_after from the tuple final_diverged_after = results[-1] plt.matshow(final_diverged_after) pass # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 275} colab_type="code" executionInfo={"elapsed": 2703, "status": "ok", "timestamp": 1568628827392, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mAuhiLGs9-CmN1BMtie2tWn3oucS__w2c4gNC6yBg=s64", "userId": "18064761308611293318"}, "user_tz": -60} id="JSitXn3PyIIe" outputId="794d10f9-8f20-4982-8326-96bc52a2388f" #@title Solution: Mandlebrot set (Double-click to reveal) MAX_ITERATIONS = 64 NUM_PIXELS = 512 def GenerateGrid(nX, nY, bottom_left=(-1.0, -1.0), top_right=(1.0, 1.0)): """Generates a complex matrix of shape [nX, nY]. Generates an evenly spaced grid of complex numbers spanning the rectangle between the supplied diagonal points. Args: nX: A positive integer. The number of points in the horizontal direction. nY: A positive integer. The number of points in the vertical direction. bottom_left: The coordinates of the bottom left corner of the rectangle to cover. top_right: The coordinates of the top right corner of the rectangle to cover. Returns: A constant tensor of type complex64 and shape [nX, nY]. """ x = tf.linspace(bottom_left[0], top_right[0], nX) y = tf.linspace(bottom_left[1], top_right[1], nY) real, imag = tf.meshgrid(x, y) return tf.cast(tf.complex(real, imag), tf.complex128) c_values = GenerateGrid(NUM_PIXELS, NUM_PIXELS) initial_Z_values = tf.zeros_like(c_values, dtype=tf.complex128) initial_diverged_after = tf.ones_like(c_values, dtype=tf.int32) * MAX_ITERATIONS # You need to put the various values you want to change inside the loop here loop_vars = (0, initial_Z_values, initial_diverged_after) # this needs to take the same number of arguments as loop_vars contains and # return a tuple of equal size with the next iteration's values def body(iteration_count, Z_values, diverged_after): # a matrix of bools showing all the co-ordinatesthat haven't diverged yet not_diverged = tf.equal(diverged_after, MAX_ITERATIONS) # a list of the indices in not_diverged that are true not_diverged_indices = tf.where_v2(not_diverged) # Gather the values for just the undiverged co-ordinates, and generate the # next iteration's values not_diverged_c_values_array = tf.gather_nd(c_values, not_diverged_indices) not_diverged_Z_values_array = tf.gather_nd(Z_values, not_diverged_indices) new_Z_values_array = (not_diverged_Z_values_array * not_diverged_Z_values_array + not_diverged_c_values_array) # merge the new values with the already-diverged new_Z_values_or_zeroes = tf.scatter_nd( not_diverged_indices, new_Z_values_array, tf.shape(Z_values, out_type=tf.dtypes.int64)) new_Z_values = tf.where_v2(not_diverged, new_Z_values_or_zeroes, Z_values) # And now we're back to the original code has_diverged = tf.abs(new_Z_values) > 2.0 new_diverged_after = tf.minimum(diverged_after, tf.where_v2( has_diverged, iteration_count, MAX_ITERATIONS)) return (iteration_count+1, new_Z_values, new_diverged_after) # this just needs to take the same number of arguments as loop_vars contains and # return true (we'll use maximum_iterations to exit the loop) def cond(iteration_count, Z_values, diverged_after): return True loop = tf.compat.v1.while_loop( loop_vars=loop_vars, body = body, cond = cond, maximum_iterations=MAX_ITERATIONS) with tf.Session() as sess: results = sess.run(loop) ## extract the final value of diverged_after from the tuple final_diverged_after = results[-1] plt.matshow(final_diverged_after) pass # + [markdown] colab_type="text" id="kAlaMKj0gZdX" # ## SparseTensor # # [Full documentation](https://www.tensorflow.org/api_docs/python/tf/sparse/SparseTensor]) # # A sparse tensor is created from a list of indices, a list of values and a shape: the same as the arguments to scatter_nd. Any element within the tensor that doesn't have an explicit value will be treated as zero. So a sparse tensor can be viewed as a deferred call to scatter_nd. # # For large tensors where most of the values are zero, sparse tensors can grant major savings in memory. The [tf.sparse module](https://www.tensorflow.org/api_docs/python/tf/sparse) contains several specialised operations that know how to work with sparse tensor's internals and skipping all the zero values, thus granting major savings in processing speed as well. # # Similarly sparse tensors can be efficiently divided or multiplied by a tensor or scalar. But attempts to perform inefficient operations on a sparse tensor (i.e. ones likely to set most elements to a non-zero value) are not allowed. You need to convert the sparse tensor to a normal, or "dense", tensor with the ```tf.sparse.to_dense``` function. # + colab={"base_uri": "https://localhost:8080/", "height": 840} colab_type="code" executionInfo={"elapsed": 447, "status": "ok", "timestamp": 1568714727763, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mAuhiLGs9-CmN1BMtie2tWn3oucS__w2c4gNC6yBg=s64", "userId": "18064761308611293318"}, "user_tz": -60} id="qDJmkGN2lBhB" outputId="c53c8ed7-a5bb-4b6c-e357-bf65bc28605b" source = tf.constant([[[111,112,113], [121,122,123], [131,132,133]], [[211,212,213], [221,222,223], [231,232,233]]]) # create a list of indices where is_divisible_by_three is true indices = tf.where_v2(tf.equal(0, source % 3)) # extract a matching list of values values_divisible_by_three = tf.gather_nd(source, indices) with tf.Session() as sess: sparse = tf.sparse.SparseTensor( indices, values_divisible_by_three, tf.shape(source, out_type=tf.dtypes.int64)) print ("sparse =") print(sess.run(sparse)) # We can efficiently multiply sparse by a dense tensor print ("\nsparse * dense =") print(sess.run(sparse * source)) # We can efficiently multiply a dense tensor by a sparse print ("\ndense * sparse") print(sess.run(source * sparse)) # We can efficiently divide sparse by a dense tensor print ("\nsparse / dense") print(sess.run(sparse / source)) # But attempts to perform inefficient operations on a sparse tensor (i.e. ones # likely to set most elements to a non-zero value) are not allowed. # You need to convert the sparse tensor into a dense tensor first. try: not_allowed = sparse + source except TypeError: pass # Running to_dense is exactly the same as calling scatter_nd: print ("\nto_dense gives") print(sess.run(tf.sparse.to_dense(sparse))) print ("\nscatter_nd gives") print(sess.run(tf.scatter_nd(sparse.indices, sparse.values, sparse.dense_shape))) # + [markdown] colab_type="text" id="Afi0jfqkI9as" # # Functional ops # + [markdown] colab_type="text" id="sAVQxV71JF59" # ## tf.foldl and tf.foldr # # [Full documentation](https://www.tensorflow.org/api_docs/python/tf/foldl) # # These two functions split a given tensor across its first dimension. The resulting subtensors are then each passed to an op along with an "accumulator". # For most iterations, the value of the accumulator will be the result of the previous iteration. But for the first iteration, the accumulator will either be passed an initial value passed into the foldl/foldr call, or the first subtensor. The final iteration's result then becomes the overall result of the op. # # So the rough pseudo code of ```x = tf.foldl(op, [[1,1], [2,2], [3,3]], initializer)``` would be # ``` python # result_iteration1 = op(initializer, [1,1]) # result_iteration2 = op(result_iteration1, [2,2]) # result iteration3 = op(result_iteration2, [3,3]) # x = result_iteration3 # ``` # Whereas the rough pseudo-code of ```x = tf.foldl(op, [[1,1], [2,2], [3,3])``` (i.e. no initializer supplied) would be # ``` python # result_iteration1 = op([1,1]], [2,2]) # result_iteration2 = op(result_iteration1, [3,3]) # x = result_iteration3 # ``` # # ```foldr``` is identical to ```foldl```, except that the order the tensor is iterated through is reversed. So the rough pseudo code of ```x = tf.foldr(op, [[1,1], [2,2], [3,3], initializer)``` would be # ``` python # result_iteration1 = op(initializer, [3,3]) # result_iteration2 = op(result_iteration1, [2,2]) # result iteration3 = op(result_iteration2, [1,1]) # x = result_iteration3 # ``` # # The only complication of this method is that the op is defined by a python callable. Note that the callable is only called once, at execution time, to build the operation. **Your python callable is not called for every row in the input**, nor can it see the individual values. It is the op created by your python code that will be repeatedly called. # # Note that despite this, use of these methods still eliminates several optimisation opportunities that are present in tensorflow built-in operations. So if you can use something like tf.math.reduce_sum instead of these ops then your code may well run significantly faster. # + colab={"base_uri": "https://localhost:8080/", "height": 168} colab_type="code" executionInfo={"elapsed": 440, "status": "ok", "timestamp": 1568711374271, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mAuhiLGs9-CmN1BMtie2tWn3oucS__w2c4gNC6yBg=s64", "userId": "18064761308611293318"}, "user_tz": -60} id="40cDr4ogOk8W" outputId="397c3127-6d7b-4050-93bb-d102df4fe4c1" source = tf.constant([[1,2],[3,4],[5,6]]) # element def my_function(previous_iterations_result, element): print("In my_function.") # this depends on the previous values, thus highlighting the difference # between foldl and foldr return tf.math.maximum( previous_iterations_result, element) + previous_iterations_result with tf.Session() as sess: print("Executing foldl") print("foldl result:\n%s"%sess.run( tf.foldl(my_function, source))) print("\nExecuting foldr") print("foldr result:\n%s"%sess.run( tf.foldr(my_function, source))) # + [markdown] colab_type="text" id="P9xLy92GtXHx" # ## tf.map_fn # # This op is similar to foldl, but the python function only takes a single argument, it lacks the accumulator argument containing the result of the previous iteration. Again the callable is called just once, and is used to generate an tensorflow op. It is this generated op that is executed once per row. And again, be aware that replacing the map_fn call with a built-in op - if possible - can result in significant increases in speed. # + colab={"height": 69} colab_type="code" executionInfo={"elapsed": 465, "status": "ok", "timestamp": 1568886060131, "user": {"displayName": "", "photoUrl": "", "userId": ""}, "user_tz": -60} id="x4CPdY9bzhjs" outputId="d6c582fa-a8e5-49ea-bb7f-bd0d2c67b819" source = tf.constant([[1,2],[3,4],[5,6]]) # element def my_function(element): print("In my_function") return tf.math.reduce_sum(element) with tf.Session() as sess: print("foldr result:\n%s"%sess.run( tf.map_fn(my_function, source)))
tf_quant_finance/examples/jupyter_notebooks/Introduction_to_TensorFlow_Part_3_-_Advanced_Tensor_Manipulation.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 (Intel\xAE oneAPI)" # language: python # name: c009-intel_distribution_of_python_3_oneapi-beta05-python # --- # + [markdown] tags=[] # # Data Parallel C++ Essentials Modules # + [markdown] tags=[] # The concepts build on top of each other introducing and reinforcing the concepts of Data Parallel C++. # # ## Module 0 - [Introduction to Jupyter Notebook (Optional) ](00_Introduction_to_Jupyter/Introduction_to_Jupyter.ipynb) # `Optional` This module explains how to use Jupyter Notebook which is used in all of the modules to edit and run coding excecises, this can be skipped if you are already familiar with using Jupyter Notebooks. # # ## Module 1 - [Introduction to oneAPI and DPC++ ](01_oneAPI_Intro/oneAPI_Intro.ipynb) # These initial hands-on exercises introduce you to DPC++ and the goal of oneAPI. In addition, it familiarizes you with the use of Jupyter notebooks as a front-end for all training exercises. This workshop is designed to be used on the DevCloud and includes details on how to submit batch jobs on DevCloud environment. # # ## Module 2 - [DPC++ Program Structure](02_DPCPP_Program_Structure/DPCPP_Program_Structure.ipynb) # These hands-on exercises present six basic DPC++ programs that illustrate the elements of a DPC++ application. You can modify the source code in some of the exercises to become more familiar with DPC++ programming concepts. # # ## Module 3 - [DPC++ Unified Shared Memory](03_DPCPP_Unified_Shared_Memory/Unified_Shared_Memory.ipynb) # These hands-on exercises show how to implement Unified Shared Memory (USM) in DPC++ code, as well as demonstrate how to solve for data dependencies for in-order and out-of-order queues. # # ## Module 4 - [DPC++ Subgroups](04_DPCPP_Sub_Groups/Sub_Groups.ipynb) # These hands-on exercises demonstrate the enhanced features that DPC++ brings to sub-groups. The code samples demonstrate how to implement a query for sub-group info, sub-group collectives, and sub-group shuffle operations. # # ## Module 5 - [Demonstration of Intel® Advisor](05_Intel_Advisor/offload_advisor.ipynb) # This set of hand-on exercises demonstrates various aspects of Intel® Advisor. The first uses Intel® Advisor to show performance offload opportunities found in a sample application, and then additional command-line options for getting offload advisor results. The second, [roofline analysis](05_Intel_Advisor/roofline_analysis.ipynb), gives an example of roofline analysis and command line options for getting advisor results. For both exercises, the results are rendered inside of the notebook. These notebooks are meant for exploration and familiarization, and do not require any cdoe modification. # # ## Module 6 - [Intel® Vtune™ Profiler on DevCloud](06_Intel_VTune_Profiler/Intel_VTune_Profiler.ipynb) # This hands-on exercise demonstrates using Intel® Vtune™ Profiler on the command-line to collect and analyze gpu_hotspots. You will learn how to collect performance metrics and explore the results with the HTML output rendered inside of the notebook. This module meant for exploration and familiarization, and does not require any code modification. # # ## Module 7 - [Intel® oneAPI DPC++ Library](07_DPCPP_Library/oneDPL_Introduction.ipynb) # This hands-on exercise demonstrates using Intel® oneAPI DPC++ Library (oneDPL) for heterogeneous computing. You will learn how to use various Parallel STL algorithms for heterogeneous computing and also look at gamma-correction sample code that uses oneDPL. # # ## Module 8 - [DPC++ Reductions](08_DPCPP_Reduction/Reductions.ipynb) # This hands-on exercise demonstrates various ways to optimizes reduction operations using DPC++. You will learn how to use ND-Range kernels to parallelize reductions on accelerators and also learn how to optimize reductions using new reduction extensions in DPC++. # # ## Module 9 - [Explore Buffers and Accessors in depth](09_DPCPP_Buffers_And_Accessors_Indepth/DPCPP_Buffers_accessors.ipynb) # This hands-on exercise demonstrates various ways to create Buffers in DPC++. You will learn how to use sub-buffers, buffer properties and when to use_host_ptr, set_final_data and set_write_data. You will also learn accessors, host_accessors and its usecases. # # ## Module 10 - [SYCL Task Scheduling and Data Dependences](10_DPCPP_Graphs_Scheduling_Data_management/DPCPP_Task_Scheduling_Data_dependency.ipynb) # This hands-on exercise demonstrates how to utilize USM and Buffers and accessors to apply Memory management and take control over data movement implicitly and explicitly, utilize different types of data dependences that are important for ensuring execution of graph scheduling. You will also learn to select the correct modes of dependences in Graphs scheduling. # # ## Module 11 - [Intel® Distribution for GDB on DevCloud](11_Intel_Distribution_for_GDB/gdb_oneapi.ipynb) # This hands-on exercise demonstrates how to use the Intel® Distribution for GDB to debug kernels running on GPUs. # - # --- # # # # # Reference Material # # ## [oneAPI GPU Optimization Guide](https://www.intel.com/content/www/us/en/develop/documentation/oneapi-gpu-optimization-guide/top/intro.html) # This guide focuses on different topics to guide you in your path to creating optimized solutions when programming for GPUs. Designing high-performance software requires you to “think differently” than you might normally do when writing software. You need to be aware of the hardware on which your code is intended to run, and the characteristics which control the performance of that hardware. Your goal is to structure the code such that it produces correct answers, but does so in a way that maximizes the hardware’s ability to execute the code. The Intel® oneAPI toolkits provide the languages and development tools you will use to optimize your code. This includes compilers, debuggers, profilers, analyzers, and libraries. # # ## [SYCL 2020 Specification](https://www.khronos.org/registry/SYCL/specs/sycl-2020/pdf/sycl-2020.pdf) # SYCL is a royalty-free, cross-platform abstraction C++ programming model for heterogeneous computing. SYCL builds on the underlying concepts, portability and efficiency of parallel API or standards like OpenCL while adding much of the ease of use and flexibility of single-source C++. #
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/Welcome.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 # --- # # Model Exploration & Explanation # Now that we have a working model with a 96% accuracy, we'll look into explaining why and how the model works. # Guide: # # - Feature importance # - Model Performance # - Feature Correlation # + # import libraries from warnings import filterwarnings filterwarnings("ignore") import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.ensemble import GradientBoostingClassifier from sklearn.feature_selection import SelectPercentile from sklearn.preprocessing import minmax_scale from sklearn.metrics import plot_confusion_matrix from src.helper import praf1 import pickle # %matplotlib inline sns.set(font_scale=1.2) # - # load our data df = pd.read_csv("../data/interim/data.csv") train = pd.read_csv("../data/processed/train.csv") test = pd.read_csv("../data/processed/test.csv") # load in classifier and feature selector with open("storage/gb-clf.pickle", "rb") as f: clf = pickle.load(f) with open("storage/feat-select.pickle", "rb") as f: selector = pickle.load(f) # ## Feature Importance # First on the agenda is identifying which features are important. We'll output the top 10 # + # get columns from feature selector and plot values selected_feats = train.iloc[:, :-1].columns[selector.get_support()] feat_impts = clf.feature_importances_ zipped = np.array(list(sorted(zip(selected_feats, feat_impts), key=lambda v: v[1], reverse=True))) plt.figure(figsize=(14, 16)) sns.barplot(minmax_scale(zipped[:, 1]), zipped[:, 0]) # scaled our values to be in the range [0, 1] plt.title("Gradient Boosted Random Forest Feature Importance") plt.show() # - # Interestingly the most important features for determining whether a customer will soon stop doing business are the amount of minutes they've used during the day which is correlated with price aka their charge which is also another important feature. Along with that, the next most important feature is the amount of customer service calls they've placed, followed by their evening minutes used/ charge. # # Looking into the reason why these features are important would be a great next step, but generally it may just be that customers as dissatisfied when their phone service bill is exceedingly large, and most importantly if an individual has to consistently call customer service for assistance they will become dissatisfied with the service provider, def fix_labels(string): return string.replace("_", " ").title() # + # output top 5 features plt.figure(figsize=(16, 9)) labels = [fix_labels(i) for i in zipped[:5, 0]] sns.barplot(minmax_scale(zipped[:, 1])[:5], labels) # scaled our values to be in the range [0, 1] plt.title("Top 5 Features for Determining Customer Churn") plt.tight_layout() plt.xlabel("Importance") plt.savefig("../docs/visuals/01-top-5-features.svg", orientation="vertical") plt.show() # - # ## Model Performance # Our stakeholders will most likely want to know how our model performs. We'll give them a few of the descriptive metrics. # + # get our testing results X = selector.transform(test.iloc[:, :-1]) y = test.iloc[:, -1] pred = clf.predict(X) results = praf1(y, pred, "Test Results") plt.figure(figsize=(16, 9)) sns.barplot(data=results) ticks = np.linspace(0, 1, 11) plt.yticks(ticks, [f"{i:.0%}" for i in ticks]) plt.title("Testing Metrics") plt.ylabel("Score") plt.xticks([0, 1, 2, 3], ["Precision", "Recall", "Accuracy", "F Measure"]) plt.savefig("../docs/visuals/02-model-testing-metrics.svg") plt.show() # - # ## Correlation of Features # + # correlation matrix of features corr = np.abs(df.iloc[:, :-1].corr()) mask = np.triu(np.ones_like(corr)) plt.figure(figsize=(12, 8)) sns.heatmap(corr, mask=mask) plt.title("Feature Correlation") plt.show() # - # Practically all our features are independent of each other, however, our \*_charge features are perfectly correlated with our \*_minutes features # ## Class Imbalance # what percentage of customers are churning vals = df[["churn", "state"]].groupby("churn").count()/df.shape[0] vals # + # output as stacked bar chart fig, ax = plt.subplots(figsize=(16, 9)) vals.T.plot.bar(stacked=True, ax=ax) plt.title("Customer Churn Rate") plt.xticks([0], "") plt.yticks(np.linspace(0, 1, 11), [f"{i:.0%}" for i in np.linspace(0, 1, 11)]) plt.savefig("../docs/visuals/03-customer-churn-rate.svg") plt.show() # - # In the data given to us by our client we see that the customer churn rate is about 15%. As a business this is a size-able amount of customers to be losing consistently. # ## Relationship between Minutes, Customer Service Calls, and Churn # + # plot a regression plot plt.figure(figsize=(16, 9)) sns.boxplot("customer_service_calls", "day_charge", "churn", df) plt.title("Dist. of Day Charge by Customer Service Calls") plt.show() # - # We can see some degree of separation between customers who eventually leave, and those that stay. Looking at the IQR, those who've had less than 3 customer service calls appears to have a higher day charge, whereas those who have to consistently call customer service have a reduced day charge.
notebooks/12-Skellet0r-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 # language: python # name: python3 # --- # # Introduction # # This notebook outlines how to build a recommendation system using SageMaker's Factorization Machines (FM). The main goal is to showcase how to extend FM model to predict top "X" recommendations using SageMaker's KNN and Batch Transform. # # There are four parts to this notebook: # # 1. Building a FM Model # 2. Repackaging FM Model to fit a KNN Model # 3. Building a KNN model # 4. Running Batch Transform for predicting top "X" items # # ## Part 1 - Building a FM Model using movie lens dataset # # <NAME> has written a fantastic blog about how to build a FM model using SageMaker with detailed explanation. Please see the links below for more information. In this part, I utilized his code for the most part to have continutity for performing additional steps. # # Source - https://aws.amazon.com/blogs/machine-learning/build-a-movie-recommender-with-factorization-machines-on-amazon-sagemaker/ import sagemaker import sagemaker.amazon.common as smac from sagemaker import get_execution_role from sagemaker.predictor import json_deserializer from sagemaker.amazon.amazon_estimator import get_image_uri import numpy as np from scipy.sparse import lil_matrix import pandas as pd import boto3, io, os # ### Download movie rating data from movie lens #download data # !wget http://files.grouplens.org/datasets/movielens/ml-100k.zip # !unzip -o ml-100k.zip # ### Shuffle the data # %cd ml-100k # !shuf ua.base -o ua.base.shuffled # ### Load Training Data user_movie_ratings_train = pd.read_csv('ua.base.shuffled', sep='\t', index_col=False, names=['user_id' , 'movie_id' , 'rating']) user_movie_ratings_train.head(5) # ### Load Test Data user_movie_ratings_test = pd.read_csv('ua.test', sep='\t', index_col=False, names=['user_id' , 'movie_id' , 'rating']) user_movie_ratings_test.head(5) nb_users= user_movie_ratings_train['user_id'].max() nb_movies=user_movie_ratings_train['movie_id'].max() nb_features=nb_users+nb_movies nb_ratings_test=len(user_movie_ratings_test.index) nb_ratings_train=len(user_movie_ratings_train.index) print " # of users: ", nb_users print " # of movies: ", nb_movies print " Training Count: ", nb_ratings_train print " Test Count: ", nb_ratings_test print " Features (# of users + # of movies): ", nb_features # ### FM Input # # Input to FM is a one-hot encoded sparse matrix. Only ratings 4 and above are considered for the model. We will be ignoring ratings 3 and below. # + def loadDataset(df, lines, columns): # Features are one-hot encoded in a sparse matrix X = lil_matrix((lines, columns)).astype('float32') # Labels are stored in a vector Y = [] line=0 for index, row in df.iterrows(): X[line,row['user_id']-1] = 1 X[line, nb_users+(row['movie_id']-1)] = 1 if int(row['rating']) >= 4: Y.append(1) else: Y.append(0) line=line+1 Y=np.array(Y).astype('float32') return X,Y X_train, Y_train = loadDataset(user_movie_ratings_train, nb_ratings_train, nb_features) X_test, Y_test = loadDataset(user_movie_ratings_test, nb_ratings_test, nb_features) # + print(X_train.shape) print(Y_train.shape) assert X_train.shape == (nb_ratings_train, nb_features) assert Y_train.shape == (nb_ratings_train, ) zero_labels = np.count_nonzero(Y_train) print("Training labels: %d zeros, %d ones" % (zero_labels, nb_ratings_train-zero_labels)) print(X_test.shape) print(Y_test.shape) assert X_test.shape == (nb_ratings_test, nb_features) assert Y_test.shape == (nb_ratings_test, ) zero_labels = np.count_nonzero(Y_test) print("Test labels: %d zeros, %d ones" % (zero_labels, nb_ratings_test-zero_labels)) # - # ### Convert to Protobuf format for saving to S3 # + #Change this value to your own bucket name bucket = 'recommendation-system-12-06' prefix = 'fm' train_key = 'train.protobuf' train_prefix = '{}/{}'.format(prefix, 'train') test_key = 'test.protobuf' test_prefix = '{}/{}'.format(prefix, 'test') output_prefix = 's3://{}/{}/output'.format(bucket, prefix) # + def writeDatasetToProtobuf(X, bucket, prefix, key, d_type, Y=None): buf = io.BytesIO() if d_type == "sparse": smac.write_spmatrix_to_sparse_tensor(buf, X, labels=Y) else: smac.write_numpy_to_dense_tensor(buf, X, labels=Y) buf.seek(0) obj = '{}/{}'.format(prefix, key) boto3.resource('s3').Bucket(bucket).Object(obj).upload_fileobj(buf) return 's3://{}/{}'.format(bucket,obj) fm_train_data_path = writeDatasetToProtobuf(X_train, bucket, train_prefix, train_key, "sparse", Y_train) fm_test_data_path = writeDatasetToProtobuf(X_test, bucket, test_prefix, test_key, "sparse", Y_test) print "Training data S3 path: ",fm_train_data_path print "Test data S3 path: ",fm_test_data_path print "FM model output S3 path: {}".format(output_prefix) # - # ### Run training job # # You can play around with the hyper parameters until you are happy with the prediction. For this dataset and hyper parameters configuration, after 100 epochs, test accuracy was around 70% on average and the F1 score (a typical metric for a binary classifier) was around 0.74 (1 indicates a perfect classifier). Not great, but you can fine tune the model further. # + instance_type='ml.m5.large' fm = sagemaker.estimator.Estimator(get_image_uri(boto3.Session().region_name, "factorization-machines"), get_execution_role(), train_instance_count=1, train_instance_type=instance_type, output_path=output_prefix, sagemaker_session=sagemaker.Session()) fm.set_hyperparameters(feature_dim=nb_features, predictor_type='binary_classifier', mini_batch_size=1000, num_factors=64, epochs=100) fm.fit({'train': fm_train_data_path, 'test': fm_test_data_path}) # - # ## Part 2 - Repackaging Model data to fit a KNN Model # # Now that we have the model created and stored in SageMaker, we can download the same and repackage it to fit a KNN model. # ### Download model data # + import mxnet as mx model_file_name = "model.tar.gz" model_full_path = fm.output_path +"/"+ fm.latest_training_job.job_name +"/output/"+model_file_name print "Model Path: ", model_full_path #Download FM model # %cd .. os.system('aws s3 cp '+model_full_path+ './') #Extract model file for loading to MXNet os.system('tar xzvf '+model_file_name) os.system("unzip -o model_algo-1") os.system("mv symbol.json model-symbol.json") os.system("mv params model-0000.params") # - # ### Extract model data to create item and user latent matrixes # + #Extract model data m = mx.module.Module.load('./model', 0, False, label_names=['out_label']) V = m._arg_params['v'].asnumpy() w = m._arg_params['w1_weight'].asnumpy() b = m._arg_params['w0_weight'].asnumpy() # item latent matrix - concat(V[i], w[i]). knn_item_matrix = np.concatenate((V[nb_users:], w[nb_users:]), axis=1) knn_train_label = np.arange(1,nb_movies+1) #user latent matrix - concat (V[u], 1) ones = np.ones(nb_users).reshape((nb_users, 1)) knn_user_matrix = np.concatenate((V[:nb_users], ones), axis=1) # - # ## Part 3 - Building KNN Model # # In this section, we upload the model input data to S3, create a KNN model and save the same. Saving the model, will display the model in the model section of SageMaker. Also, it will aid in calling batch transform down the line or even deploying it as an end point for real-time inference. # # This approach uses the default 'index_type' parameter for knn. It is precise but can be slow for large datasets. In such cases, you may want to use a different 'index_type' parameter leading to an approximate, yet fast answer. # + print('KNN train features shape = ', knn_item_matrix.shape) knn_prefix = 'knn' knn_output_prefix = 's3://{}/{}/output'.format(bucket, knn_prefix) knn_train_data_path = writeDatasetToProtobuf(knn_item_matrix, bucket, knn_prefix, train_key, "dense", knn_train_label) print('uploaded KNN train data: {}'.format(knn_train_data_path)) nb_recommendations = 100 # set up the estimator knn = sagemaker.estimator.Estimator(get_image_uri(boto3.Session().region_name, "knn"), get_execution_role(), train_instance_count=1, train_instance_type=instance_type, output_path=knn_output_prefix, sagemaker_session=sagemaker.Session()) knn.set_hyperparameters(feature_dim=knn_item_matrix.shape[1], k=nb_recommendations, index_metric="INNER_PRODUCT", predictor_type='classifier', sample_size=200000) fit_input = {'train': knn_train_data_path} knn.fit(fit_input) knn_model_name = knn.latest_training_job.job_name print "created model: ", knn_model_name # save the model so that we can reference it in the next step during batch inference sm = boto3.client(service_name='sagemaker') primary_container = { 'Image': knn.image_name, 'ModelDataUrl': knn.model_data, } knn_model = sm.create_model( ModelName = knn.latest_training_job.job_name, ExecutionRoleArn = knn.role, PrimaryContainer = primary_container) print "saved the model" # - # ## Part 4 - Batch Transform # # In this section, we will use SageMaker's batch transform option to batch predict top X for all the users. # + #upload inference data to S3 knn_batch_data_path = writeDatasetToProtobuf(knn_user_matrix, bucket, knn_prefix, train_key, "dense") print "Batch inference data path: ",knn_batch_data_path # Initialize the transformer object transformer =sagemaker.transformer.Transformer( base_transform_job_name="knn", model_name=knn_model_name, instance_count=1, instance_type=instance_type, output_path=knn_output_prefix, accept="application/jsonlines; verbose=true" ) # Start a transform job: transformer.transform(knn_batch_data_path, content_type='application/x-recordio-protobuf') transformer.wait() #Download predictions results_file_name = "inference_output" inference_output_file = "knn/output/train.protobuf.out" s3_client = boto3.client('s3') s3_client.download_file(bucket, inference_output_file, results_file_name) with open(results_file_name) as f: results = f.readlines() # + import json test_user_idx = 89 u_one_json = json.loads(results[test_user_idx]) print "Recommended movie Ids for user #{} : {}".format(test_user_idx+1, [int(movie_id) for movie_id in u_one_json['labels']]) print print "Movie distances for user #{} : {}".format(test_user_idx+1, [round(distance, 4) for distance in u_one_json['distances']])
Starter-Code/Recommendation-System-FM-KNN.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 # --- # + # OPTIONAL: Load the "autoreload" extension so that code can change # %load_ext autoreload # OPTIONAL: always reload modules so that as you change code in src, it gets loaded # %autoreload 2 # some_file.py import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '../src') # -
notebooks/experiment.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Build and Evaluate a Linear Risk model # # Welcome to the first assignment in Course 2! # # ## Outline # # - [1. Import Packages](#1) # - [2. Load Data](#2) # - [3. Explore the Dataset](#3) # - [4. Mean-Normalize the Data](#4) # - [Exercise 1](#Ex-1) # - [5. Build the Model](#Ex-2) # - [Exercise 2](#Ex-2) # - [6. Evaluate the Model Using the C-Index](#6) # - [Exercise 3](#Ex-3) # - [7. Evaluate the Model on the Test Set](#7) # - [8. Improve the Model](#8) # - [Exercise 4](#Ex-4) # - [9. Evalute the Improved Model](#9) # + [markdown] colab_type="text" id="DU20mFeib5Kd" # ## Overview of the Assignment # # In this assignment, you'll build a risk score model for retinopathy in diabetes patients using logistic regression. # # As we develop the model, we will learn about the following topics: # # - Data preprocessing # - Log transformations # - Standardization # - Basic Risk Models # - Logistic Regression # - C-index # - Interactions Terms # # ### Diabetic Retinopathy # Retinopathy is an eye condition that causes changes to the blood vessels in the part of the eye called the retina. # This often leads to vision changes or blindness. # Diabetic patients are known to be at high risk for retinopathy. # # ### Logistic Regression # Logistic regression is an appropriate analysis to use for predicting the probability of a binary outcome. In our case, this would be the probability of having or not having diabetic retinopathy. # Logistic Regression is one of the most commonly used algorithms for binary classification. It is used to find the best fitting model to describe the relationship between a set of features (also referred to as input, independent, predictor, or explanatory variables) and a binary outcome label (also referred to as an output, dependent, or response variable). Logistic regression has the property that the output prediction is always in the range $[0,1]$. Sometimes this output is used to represent a probability from 0%-100%, but for straight binary classification, the output is converted to either $0$ or $1$ depending on whether it is below or above a certain threshold, usually $0.5$. # # It may be confusing that the term regression appears in the name even though logistic regression is actually a classification algorithm, but that's just a name it was given for historical reasons. # + [markdown] colab_type="text" id="pzuRKOt1cU8B" # <a name='1'></a> # ## 1. Import Packages # # We'll first import all the packages that we need for this assignment. # # - `numpy` is the fundamental package for scientific computing in python. # - `pandas` is what we'll use to manipulate our data. # - `matplotlib` is a plotting library. # + colab={} colab_type="code" id="qHjB-KVmwmtR" import numpy as np import pandas as pd import matplotlib.pyplot as plt # + [markdown] colab_type="text" id="3J7NXuQadLnY" # <a name='2'></a> # ## 2. Load Data # # First we will load in the dataset that we will use for training and testing our model. # # - Run the next cell to load the data that is stored in csv files. # - There is a function `load_data` which randomly generates data, but for consistency, please use the data from the csv files. # + colab={} colab_type="code" id="FN5Y5hU5yXnE" from utils import load_data # This function creates randomly generated data # X, y = load_data(6000) # For stability, load data from files that were generated using the load_data X = pd.read_csv('X_data.csv',index_col=0) y_df = pd.read_csv('y_data.csv',index_col=0) y = y_df['y'] # + [markdown] colab_type="text" id="5yF06E6sZMmD" # `X` and `y` are Pandas DataFrames that hold the data for 6,000 diabetic patients. # - # <a name='3'></a> # ## 3. Explore the Dataset # # The features (`X`) include the following fields: # * Age: (years) # * Systolic_BP: Systolic blood pressure (mmHg) # * Diastolic_BP: Diastolic blood pressure (mmHg) # * Cholesterol: (mg/DL) # # We can use the `head()` method to display the first few records of each. # + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" id="qp1SgI7PT024" outputId="3ff454c2-65fb-4fea-858a-647c7a5d750d" X.head() # + [markdown] colab_type="text" id="Q0o8DaDayXnM" # The target (`y`) is an indicator of whether or not the patient developed retinopathy. # # * y = 1 : patient has retinopathy. # * y = 0 : patient does not have retinopathy. # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="2d6L8BHO3-QJ" outputId="1b58dfe9-178e-491d-e2cb-738b083a1db7" y.head() # + [markdown] colab_type="text" id="DAobb_-hFtAn" # Before we build a model, let's take a closer look at the distribution of our training data. To do this, we will split the data into train and test sets using a 75/25 split. # # For this, we can use the built in function provided by sklearn library. See the documentation for [sklearn.model_selection.train_test_split](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html). # + colab={} colab_type="code" id="C9FxG6hDyXnQ" from sklearn.model_selection import train_test_split # + colab={} colab_type="code" id="1fvqevMtFsHh" X_train_raw, X_test_raw, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=0) # + [markdown] colab_type="text" id="nYgcS0vjdbpc" # Plot the histograms of each column of `X_train` below: # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="EBckdYHyUudi" outputId="2e987230-a0eb-40d1-f3a6-ac943cbedf4d" for col in X.columns: X_train_raw.loc[:, col].hist() plt.title(col) plt.show() # - # As we can see, the distributions have a generally bell shaped distribution, but with slight rightward skew. # # Many statistical models assume that the data is normally distributed, forming a symmetric Gaussian bell shape (with no skew) more like the example below. from scipy.stats import norm data = np.random.normal(50,12, 5000) fitting_params = norm.fit(data) norm_dist_fitted = norm(*fitting_params) t = np.linspace(0,100, 100) plt.hist(data, bins=60, density=True) plt.plot(t, norm_dist_fitted.pdf(t)) plt.title('Example of Normally Distributed Data') plt.show() # + [markdown] colab_type="text" id="jhZ3UKs3U-FG" # We can transform our data to be closer to a normal distribution by removing the skew. One way to remove the skew is by applying the log function to the data. # # Let's plot the log of the feature variables to see that it produces the desired effect. # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="r3fiFAipU9nm" outputId="c46e9627-4db9-4992-8736-ba974ffadde0" for col in X_train_raw.columns: np.log(X_train_raw.loc[:, col]).hist() plt.title(col) plt.show() # + [markdown] colab_type="text" id="84vqBnYZT80j" # We can see that the data is more symmetric after taking the log. # + [markdown] colab_type="text" id="gnj1zUmaG94h" # <a name='4'></a> # ## 4. Mean-Normalize the Data # # Let's now transform our data so that the distributions are closer to standard normal distributions. # # First we will remove some of the skew from the distribution by using the log transformation. # Then we will "standardize" the distribution so that it has a mean of zero and standard deviation of 1. Recall that a standard normal distribution has mean of zero and standard deviation of 1. # # - # <a name='Ex-1'></a> # ### Exercise 1 # * Write a function that first removes some of the skew in the data, and then standardizes the distribution so that for each data point $x$, # $$\overline{x} = \frac{x - mean(x)}{std(x)}$$ # * Keep in mind that we want to pretend that the test data is "unseen" data. # * This implies that it is unavailable to us for the purpose of preparing our data, and so we do not want to consider it when evaluating the mean and standard deviation that we use in the above equation. Instead we want to calculate these values using the training data alone, but then use them for standardizing both the training and the test data. # * For a further discussion on the topic, see this article ["Why do we need to re-use training parameters to transform test data"](https://sebastianraschka.com/faq/docs/scale-training-test.html). # #### Note # - For the sample standard deviation, please calculate the unbiased estimator: # $$s = \sqrt{\frac{\sum_{i=1}^n(x_{i} - \bar{x})^2}{n-1}}$$ # - In other words, if you numpy, set the degrees of freedom `ddof` to 1. # - For pandas, the default `ddof` is already set to 1. # <details> # <summary> # <font size="3" color="darkgreen"><b>Hints</b></font> # </summary> # <p> # <ul> # <li> When working with Pandas DataFrames, you can use the aggregation functions <code>mean</code> and <code>std</code> functions. Note that in order to apply an aggregation function separately for each row or each column, you'll set the axis parameter to either <code>0</code> or <code>1</code>. One produces the aggregation along columns and the other along rows, but it is easy to get them confused. So experiment with each option below to see which one you should use to get an average for each column in the dataframe. # <code> # avg = df.mean(axis=0) # avg = df.mean(axis=1) # </code> # </li> # <br></br> # <li>Remember to use <b>training</b> data statistics when standardizing both the training and the test data.</li> # </ul> # </p> # </details> # + colab={} colab_type="code" id="wwqPOiZGRfhv" # UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) def make_standard_normal(df_train, df_test): """ In order to make the data closer to a normal distribution, take log transforms to reduce the skew. Then standardize the distribution with a mean of zero and standard deviation of 1. Args: df_train (dataframe): unnormalized training data. df_test (dataframe): unnormalized test data. Returns: df_train_normalized (dateframe): normalized training data. df_test_normalized (dataframe): normalized test data. """ ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ### # Remove skew by applying the log function to the train set, and to the test set df_train_unskewed = np.log(df_train) df_test_unskewed = np.log(df_test) #calculate the mean and standard deviation of the training set mean = df_train_unskewed.mean(axis = 0) stdev = df_train_unskewed.std(axis = 0 ) # standardize the training set df_train_standardized = (df_train_unskewed - mean) / stdev # standardize the test set (see instructions and hints above) df_test_standardized = (df_test_unskewed - mean) / stdev ### END CODE HERE ### return df_train_standardized, df_test_standardized # + [markdown] colab_type="text" id="9ohs6TqjUEHU" # #### Test Your Work # + # test tmp_train = pd.DataFrame({'field1': [1,2,10], 'field2': [4,5,11]}) tmp_test = pd.DataFrame({'field1': [1,3,10], 'field2': [4,6,11]}) tmp_train_transformed, tmp_test_transformed = make_standard_normal(tmp_train,tmp_test) print(f"Training set transformed field1 has mean {tmp_train_transformed['field1'].mean(axis=0):.4f} and standard deviation {tmp_train_transformed['field1'].std(axis=0):.4f} ") print(f"Test set transformed, field1 has mean {tmp_test_transformed['field1'].mean(axis=0):.4f} and standard deviation {tmp_test_transformed['field1'].std(axis=0):.4f}") print(f"Skew of training set field1 before transformation: {tmp_train['field1'].skew(axis=0):.4f}") print(f"Skew of training set field1 after transformation: {tmp_train_transformed['field1'].skew(axis=0):.4f}") print(f"Skew of test set field1 before transformation: {tmp_test['field1'].skew(axis=0):.4f}") print(f"Skew of test set field1 after transformation: {tmp_test_transformed['field1'].skew(axis=0):.4f}") # + [markdown] colab_type="text" id="XpqHiFfwyXne" # #### Expected Output: # ```CPP # Training set transformed field1 has mean -0.0000 and standard deviation 1.0000 # Test set transformed, field1 has mean 0.1144 and standard deviation 0.9749 # Skew of training set field1 before transformation: 1.6523 # Skew of training set field1 after transformation: 1.0857 # Skew of test set field1 before transformation: 1.3896 # Skew of test set field1 after transformation: 0.1371 # ``` # + [markdown] colab_type="text" id="gran7yoORxQ9" # #### Transform training and test data # Use the function that you just implemented to make the data distribution closer to a standard normal distribution. # + colab={} colab_type="code" id="DDC2ThP_K3Ea" X_train, X_test = make_standard_normal(X_train_raw, X_test_raw) # + [markdown] colab_type="text" id="TnmdKuXDyXnk" # After transforming the training and test sets, we'll expect the training set to be centered at zero with a standard deviation of $1$. # # We will avoid observing the test set during model training in order to avoid biasing the model training process, but let's have a look at the distributions of the transformed training data. # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="WUYtMPVyyXnk" outputId="213ebd54-8d2b-4317-9f78-d946bd7fff49" for col in X_train.columns: X_train[col].hist() plt.title(col) plt.show() # + [markdown] colab_type="text" id="ovLMYBz6dteZ" # <a name='5'></a> # ## 5. Build the Model # # Now we are ready to build the risk model by training logistic regression with our data. # # - # <a name='Ex-2'></a> # ### Exercise 2 # # * Implement the `lr_model` function to build a model using logistic regression with the `LogisticRegression` class from `sklearn`. # * See the documentation for [sklearn.linear_model.LogisticRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.fit). # <details> # <summary> # <font size="3" color="darkgreen"><b>Hints</b></font> # </summary> # <p> # <ul> # <li>You can leave all the parameters to their default values when constructing an instance of the <code>sklearn.linear_model.LogisticRegression</code> class. If you get a warning message regarding the <code>solver</code> parameter, however, you may want to specify that particular one explicitly with <code>solver='lbfgs'</code>. # </li> # <br></br> # </ul> # </p> # </details> # + colab={} colab_type="code" id="iLvr0IgoyXnz" # UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) def lr_model(X_train, y_train): ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ### # import the LogisticRegression class from sklearn.linear_model import LogisticRegression # create the model object model = LogisticRegression(solver='lbfgs') # fit the model to the training data model.fit(X_train, y_train) ### END CODE HERE ### #return the fitted model return model # - # #### Test Your Work # # Note: the `predict` method returns the model prediction *after* converting it from a value in the $[0,1]$ range to a $0$ or $1$ depending on whether it is below or above $0.5$. # + colab={"base_uri": "https://localhost:8080/", "height": 198} colab_type="code" id="9Fr-HA-TyXnv" outputId="68ba88ab-be91-4543-8c2c-481bdb3a3f84" # Test tmp_model = lr_model(X_train[0:3], y_train[0:3] ) print(tmp_model.predict(X_train[4:5])) print(tmp_model.predict(X_train[5:6])) # + [markdown] colab_type="text" id="LpafSX3tyXny" # #### Expected Output: # ```CPP # [1.] # [1.] # ``` # + [markdown] colab_type="text" id="FhuY1GjlyXn1" # Now that we've tested our model, we can go ahead and build it. Note that the `lr_model` function also fits the model to the training data. # + colab={} colab_type="code" id="sG6nr4hCyXn2" model_X = lr_model(X_train, y_train) # + [markdown] colab_type="text" id="YI34GRSgeAaL" # <a name='6'></a> # ## 6. Evaluate the Model Using the C-index # # Now that we have a model, we need to evaluate it. We'll do this using the c-index. # * The c-index measures the discriminatory power of a risk score. # * Intuitively, a higher c-index indicates that the model's prediction is in agreement with the actual outcomes of a pair of patients. # * The formula for the c-index is # # $$ \mbox{cindex} = \frac{\mbox{concordant} + 0.5 \times \mbox{ties}}{\mbox{permissible}} $$ # # * A permissible pair is a pair of patients who have different outcomes. # * A concordant pair is a permissible pair in which the patient with the higher risk score also has the worse outcome. # * A tie is a permissible pair where the patients have the same risk score. # # - # <a name='Ex-3'></a> # ### Exercise 3 # # * Implement the `cindex` function to compute c-index. # * `y_true` is the array of actual patient outcomes, 0 if the patient does not eventually get the disease, and 1 if the patient eventually gets the disease. # * `scores` is the risk score of each patient. These provide relative measures of risk, so they can be any real numbers. By convention, they are always non-negative. # * Here is an example of input data and how to interpret it: # ```Python # y_true = [0,1] # scores = [0.45, 1.25] # ``` # * There are two patients. Index 0 of each array is associated with patient 0. Index 1 is associated with patient 1. # * Patient 0 does not have the disease in the future (`y_true` is 0), and based on past information, has a risk score of 0.45. # * Patient 1 has the disease at some point in the future (`y_true` is 1), and based on past information, has a risk score of 1.25. # + colab={} colab_type="code" id="a6fzYxG0R7Sp" # UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) def cindex(y_true, scores): ''' Input: y_true (np.array): a 1-D array of true binary outcomes (values of zero or one) 0: patient does not get the disease 1: patient does get the disease scores (np.array): a 1-D array of corresponding risk scores output by the model Output: c_index (float): (concordant pairs + 0.5*ties) / number of permissible pairs ''' n = len(y_true) assert len(scores) == n concordant = 0 permissible = 0 ties = 0 ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ### # use two nested for loops to go through all unique pairs of patients for i in range(n): for j in range(i+1, n): #choose the range of j so that j>i # Check if the pair is permissible (the patient outcomes are different) if y_true[i] != y_true[j]: # Count the pair if it's permissible permissible += 1 # For permissible pairs, check if they are concordant or are ties # check for ties in the score if scores[i] == scores[j]: # count the tie ties += 1 # if it's a tie, we don't need to check patient outcomes, continue to the top of the for loop. continue # case 1: patient i doesn't get the disease, patient j does if y_true[i] == 0 and y_true[j] == 1: # Check if patient i has a lower risk score than patient j if scores[i] < scores[j]: # count the concordant pair concordant += 1 # Otherwise if patient i has a higher risk score, it's not a concordant pair. # Already checked for ties earlier # case 2: patient i gets the disease, patient j does not if y_true[i] == 1 and y_true[j] == 0: # Check if patient i has a higher risk score than patient j if scores[i] > scores[j]: #count the concordant pair concordant += 1 # Otherwise if patient i has a lower risk score, it's not a concordant pair. # We already checked for ties earlier # calculate the c-index using the count of permissible pairs, concordant pairs, and tied pairs. c_index = (concordant + 0.5 * ties) / permissible ### END CODE HERE ### return c_index # + [markdown] colab_type="text" id="b5l0kdOkUO_Y" # #### Test Your Work # # You can use the following test cases to make sure your implementation is correct. # + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" id="CzmPPfVQN8ET" outputId="6e4af0e8-1666-4704-f83a-a27b90ce7103" # test y_true = np.array([1.0, 0.0, 0.0, 1.0]) # Case 1 scores = np.array([0, 1, 1, 0]) print('Case 1 Output: {}'.format(cindex(y_true, scores))) # Case 2 scores = np.array([1, 0, 0, 1]) print('Case 2 Output: {}'.format(cindex(y_true, scores))) # Case 3 scores = np.array([0.5, 0.5, 0.0, 1.0]) print('Case 3 Output: {}'.format(cindex(y_true, scores))) cindex(y_true, scores) # + [markdown] colab_type="text" id="qHKVO2ipyXoA" # #### Expected Output: # # ```CPP # Case 1 Output: 0.0 # Case 2 Output: 1.0 # Case 3 Output: 0.875 # ``` # - # #### Note # Please check your implementation of the for loops. # - There is way to make a mistake on the for loops that cannot be caught with unit tests. # - Bonus: Can you think of what this error could be, and why it can't be caught by unit tests? # + [markdown] colab_type="text" id="GOEaZigmOPVF" # <a name='7'></a> # ## 7. Evaluate the Model on the Test Set # # Now, you can evaluate your trained model on the test set. # # To get the predicted probabilities, we use the `predict_proba` method. This method will return the result from the model *before* it is converted to a binary 0 or 1. For each input case, it returns an array of two values which represent the probabilities for both the negative case (patient does not get the disease) and positive case (patient the gets the disease). # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="_J5TbdH_LSjB" outputId="e5b8802a-8c41-4f7f-e3ba-428c6cfb5f87" scores = model_X.predict_proba(X_test)[:, 1] c_index_X_test = cindex(y_test.values, scores) print(f"c-index on test set is {c_index_X_test:.4f}") # + [markdown] colab_type="text" id="8Iy7rIiyyXoD" # #### Expected output: # ```CPP # c-index on test set is 0.8182 # ``` # + [markdown] colab_type="text" id="-BC_HAM6MXWU" # Let's plot the coefficients to see which variables (patient features) are having the most effect. You can access the model coefficients by using `model.coef_` # + colab={"base_uri": "https://localhost:8080/", "height": 316} colab_type="code" id="lZeo6AJbMdCq" outputId="613b4ce8-2d04-40b1-e2ce-d2232a62005f" coeffs = pd.DataFrame(data = model_X.coef_, columns = X_train.columns) coeffs.T.plot.bar(legend=None); # - # ### Question: # > __Which three variables have the largest impact on the model's predictions?__ # + [markdown] colab_type="text" id="7KbLT-zkNgLT" # <a name='8'></a> # ## 8. Improve the Model # # You can try to improve your model by including interaction terms. # * An interaction term is the product of two variables. # * For example, if we have data # $$ x = [x_1, x_2]$$ # * We could add the product so that: # $$ \hat{x} = [x_1, x_2, x_1*x_2]$$ # # - # <a name='Ex-4'></a> # ### Exercise 4 # # Write code below to add all interactions between every pair of variables to the training and test datasets. # + colab={} colab_type="code" id="biuVl-lGSaJp" # UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) def add_interactions(X): """ Add interaction terms between columns to dataframe. Args: X (dataframe): Original data Returns: X_int (dataframe): Original data with interaction terms appended. """ features = X.columns m = len(features) X_int = X.copy(deep=True) ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ### # 'i' loops through all features in the original dataframe X for i in range(m): # get the name of feature 'i' feature_i_name = features[i] # get the data for feature 'i' feature_i_data = X[feature_i_name] # choose the index of column 'j' to be greater than column i for j in range(i + 1, m): # get the name of feature 'j' feature_j_name = features[j] # get the data for feature j' feature_j_data = X[feature_j_name] # create the name of the interaction feature by combining both names # example: "apple" and "orange" are combined to be "apple_x_orange" feature_i_j_name = f"{feature_i_name}_x_{feature_j_name}" # Multiply the data for feature 'i' and feature 'j' # store the result as a column in dataframe X_int X_int[feature_i_j_name] = feature_i_data * feature_j_data ### END CODE HERE ### return X_int # + [markdown] colab_type="text" id="qV4rRIdwVJPm" # #### Test Your Work # # Run the cell below to check your implementation. # + colab={"base_uri": "https://localhost:8080/", "height": 255} colab_type="code" id="x5Q7eUpBcyLG" outputId="18722d74-ce4c-4b36-ca29-196b4010ed06" print("Original Data") print(X_train.loc[:, ['Age', 'Systolic_BP']].head()) print("Data w/ Interactions") print(add_interactions(X_train.loc[:, ['Age', 'Systolic_BP']].head())) # - # #### Expected Output: # ```CPP # Original Data # Age Systolic_BP # 1824 -0.912451 -0.068019 # 253 -0.302039 1.719538 # 1114 2.576274 0.155962 # 3220 1.163621 -2.033931 # 2108 -0.446238 -0.054554 # Data w/ Interactions # Age Systolic_BP Age_x_Systolic_BP # 1824 -0.912451 -0.068019 0.062064 # 253 -0.302039 1.719538 -0.519367 # 1114 2.576274 0.155962 0.401800 # 3220 1.163621 -2.033931 -2.366725 # 2108 -0.446238 -0.054554 0.024344 # ``` # + [markdown] colab_type="text" id="rKKiFF5Pdwtv" # Once you have correctly implemented `add_interactions`, use it to make transformed version of `X_train` and `X_test`. # + colab={} colab_type="code" id="mYcDf7nsd2nh" X_train_int = add_interactions(X_train) X_test_int = add_interactions(X_test) # + [markdown] colab_type="text" id="Y6IgFZWxLqTa" # <a name='9'></a> # ## 9. Evaluate the Improved Model # # Now we can train the new and improved version of the model. # - model_X_int = lr_model(X_train_int, y_train) # Let's evaluate our new model on the test set. # + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" id="xn7U6_bEfWKI" outputId="d43fe99f-e3c0-4575-b44c-93efe24917bb" scores_X = model_X.predict_proba(X_test)[:, 1] c_index_X_int_test = cindex(y_test.values, scores_X) scores_X_int = model_X_int.predict_proba(X_test_int)[:, 1] c_index_X_int_test = cindex(y_test.values, scores_X_int) print(f"c-index on test set without interactions is {c_index_X_test:.4f}") print(f"c-index on test set with interactions is {c_index_X_int_test:.4f}") # + [markdown] colab_type="text" id="-tYVyw-6jLfV" # You should see that the model with interaction terms performs a bit better than the model without interactions. # # Now let's take another look at the model coefficients to try and see which variables made a difference. Plot the coefficients and report which features seem to be the most important. # + colab={"base_uri": "https://localhost:8080/", "height": 389} colab_type="code" id="9PpyFFqFjRpW" outputId="9cc3ce2c-3a8a-4d3a-cf76-bef5862cc6c3" int_coeffs = pd.DataFrame(data = model_X_int.coef_, columns = X_train_int.columns) int_coeffs.T.plot.bar(); # + [markdown] colab_type="text" id="1bvx65OqOCUT" # ### Questions: # > __Which variables are most important to the model?__<br> # > __Have the relevant variables changed?__<br> # > __What does it mean when the coefficients are positive or negative?__<br> # # You may notice that Age, Systolic_BP, and Cholesterol have a positive coefficient. This means that a higher value in these three features leads to a higher prediction probability for the disease. You also may notice that the interaction of Age x Cholesterol has a negative coefficient. This means that a higher value for the Age x Cholesterol product reduces the prediction probability for the disease. # # To understand the effect of interaction terms, let's compare the output of the model we've trained on sample cases with and without the interaction. Run the cell below to choose an index and look at the features corresponding to that case in the training set. # + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" id="Xj8v7ZxSShC7" outputId="0d80937f-7645-4e68-eafa-766b228ed981" index = index = 3432 case = X_train_int.iloc[index, :] print(case) # + [markdown] colab_type="text" id="0LbyZ8a39hSw" # We can see that they have above average Age and Cholesterol. We can now see what our original model would have output by zero-ing out the value for Cholesterol and Age. # + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" id="2HcpczwN9sB4" outputId="8570702b-9b8d-4420-a2dc-0913bc4d84f9" new_case = case.copy(deep=True) new_case.loc["Age_x_Cholesterol"] = 0 new_case # + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" id="iasI8KMLmcPO" outputId="5c7d8884-ae10-4453-9717-d4818d45f0d7" print(f"Output with interaction: \t{model_X_int.predict_proba([case.values])[:, 1][0]:.4f}") print(f"Output without interaction: \t{model_X_int.predict_proba([new_case.values])[:, 1][0]:.4f}") # - # #### Expected output # ```CPP # Output with interaction: 0.9448 # Output without interaction: 0.9965 # ``` # + [markdown] colab_type="text" id="rdYQijiWnhyZ" # We see that the model is less confident in its prediction with the interaction term than without (the prediction value is lower when including the interaction term). With the interaction term, the model has adjusted for the fact that the effect of high cholesterol becomes less important for older patients compared to younger patients. # + [markdown] colab_type="text" id="zY6_1iIeajok" # # Congratulations! # # You have finished the first assignment of Course 2.
AI for Medical Prognosis/Week 1/Build and Evaluate a Linear Risk model.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.0 64-bit (''.venv'': venv)' # language: python # name: python38064bitvenvvenv9d6d87d02a55435484c2918c1e517d9a # --- # # 线性代数 # ## 矩阵的定义 # $$ # \boldsymbol{A}=\left[\begin{array}{cccc} # a_{11} & a_{12} & \cdots & a_{1 n} \\ # a_{21} & a_{22} & \cdots & a_{2 n} \\ # \vdots & \vdots & & \vdots \\ # a_{m 1} & a_{m 2} & \cdots & a_{m n} # \end{array}\right], \quad a_{i j} \in \mathbb{R} # $$ # ## 矩阵的加法 # $$ # \boldsymbol{A}+\boldsymbol{B}:=\left[\begin{array}{ccc} # a_{11}+b_{11} & \cdots & a_{1 n}+b_{1 n} \\ # \vdots & & \vdots \\ # a_{m 1}+b_{m 1} & \cdots & a_{m n}+b_{m n} # \end{array}\right] \in \mathbb{R}^{m \times n} # $$ # ## 矩阵的乘法 # $$ # c_{i j}=\sum_{l=1}^{n} a_{i l} b_{l j}, \quad i=1, \ldots, m, \quad j=1, \ldots, k # $$ # # $$ # \underbrace{\boldsymbol{A}}_{n \times k} \underbrace{\boldsymbol{B}}_{k \times m}=\underbrace{\boldsymbol{C}}_{n \times m} # $$ # ## 单位矩阵 # $$ # \boldsymbol{I}_{n}:=\left[\begin{array}{cccccc} # 1 & 0 & \cdots & 0 & \cdots & 0 \\ # 0 & 1 & \cdots & 0 & \cdots & 0 \\ # \vdots & \vdots & \ddots & \vdots & \ddots & \vdots \\ # 0 & 0 & \cdots & 1 & \cdots & 0 \\ # \vdots & \vdots & \ddots & \vdots & \ddots & \vdots \\ # 0 & 0 & \cdots & 0 & \cdots & 1 # \end{array}\right] \in \mathbb{R}^{n \times n} # $$ # ## 矩阵的结合律 # $$ # \forall \boldsymbol{A} \in \mathbb{R}^{m \times n}, \boldsymbol{B} \in \mathbb{R}^{n \times p}, \boldsymbol{C} \in \mathbb{R}^{p \times q}:(\boldsymbol{A} \boldsymbol{B}) \boldsymbol{C}=\boldsymbol{A}(\boldsymbol{B} \boldsymbol{C}) # $$ # ## 矩阵的分配律 # $$ # \begin{aligned} # \forall \boldsymbol{A}, \boldsymbol{B} \in \mathbb{R}^{m \times n}, \boldsymbol{C}, \boldsymbol{D} \in \mathbb{R}^{n \times p}:(\boldsymbol{A}+\boldsymbol{B}) \boldsymbol{C} &=\boldsymbol{A} \boldsymbol{C}+\boldsymbol{B} \boldsymbol{C} \\ # \boldsymbol{A}(\boldsymbol{C}+\boldsymbol{D}) &=\boldsymbol{A} \boldsymbol{C}+\boldsymbol{A} \boldsymbol{D} # \end{aligned} # $$ # ## 矩阵乘法单位元 # $$ # \forall \boldsymbol{A} \in \mathbb{R}^{m \times n}: \boldsymbol{I}_{m} \boldsymbol{A}=\boldsymbol{A} \boldsymbol{I}_{n}=\boldsymbol{A} # $$ # ## 逆矩阵和转置矩阵 # $$ # \begin{aligned} # \boldsymbol{A} \boldsymbol{A}^{-1} &=\boldsymbol{I}=\boldsymbol{A}^{-1} \boldsymbol{A} \\ # (\boldsymbol{A B})^{-1} &=\boldsymbol{B}^{-1} \boldsymbol{A}^{-1} \\ # (\boldsymbol{A}+\boldsymbol{B})^{-1} & \neq \boldsymbol{A}^{-1}+\boldsymbol{B}^{-1} \\ # \left(\boldsymbol{A}^{\top}\right)^{\top} &=\boldsymbol{A} \\ # (\boldsymbol{A}+\boldsymbol{B})^{\top} &=\boldsymbol{A}^{\top}+\boldsymbol{B}^{\top} \\ # (\boldsymbol{A B})^{\top} &=\boldsymbol{B}^{\top} \boldsymbol{A}^{\top} # \end{aligned} # $$
02_linear_algebra.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [py27] # language: python # name: Python [py27] # --- # + # %matplotlib notebook import itertools import logging from functools import partial from collections import defaultdict, OrderedDict import gensim import matplotlib from matplotlib import rc import matplotlib.pyplot as plt from matplotlib import colors as plt_colors import numpy as np import pandas as pnd import os from sklearn.cluster import * from sklearn.preprocessing import normalize from sklearn.cross_validation import train_test_split from sklearn.decomposition import PCA, RandomizedPCA from sklearn.manifold import TSNE from sklearn import svm, metrics from multiprocessing import Pool from knub.thesis.util import * pnd.set_option("display.max_colwidth", 200) LIGHT_COLORS = ["#a6cee3", "#b2df8a", "#fb9a99", "#fdbf6f", "#cab2d6", "#ffff99"] # light colors DARK_COLORS = ["#1f78b4", "#33a02c", "#e31a1c", "#ff7f00", "#6a3d9a"] # dark colors rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) rc('text', usetex=True) SIZE = 11 rc('font', size=SIZE) # controls default text sizes rc('axes', titlesize=SIZE) # fontsize of the axes title rc('axes', labelsize=SIZE) # fontsize of the x and y labels rc('xtick', labelsize=SIZE) # fontsize of the tick labels rc('ytick', labelsize=SIZE) # fontsize of the tick labels rc('legend', fontsize=SIZE) # legend fontsize rc('figure', titlesize=SIZE) # fontsize of the figure title def cm2inch(*tupl): inch = 2.54 if isinstance(tupl[0], tuple): return tuple(i/inch for i in tupl[0]) else: return tuple(i/inch for i in tupl) # + def evaluate_single(df_param): nr_inclusions = len(df_param) nr_succ = len(df_param[df_param.successful]) return float(nr_succ) / nr_inclusions def evaluate_df(df_param, print_eval): for method, df_group in df_param.groupby("method"): if "mixture" in method: continue succ_prob = evaluate_single(df_group) if print_eval: print "%s: %.2f" % (method, succ_prob) def evaluate_file(f, print_eval=True): df_file = pnd.read_csv("/home/knub/Repositories/master-thesis/webapp/out/" + f, sep="\t", header=None) df_file.columns = ["inclusion_idx", "inclusion_id", "method", "words", "intruder", "selected_word", "successful"] evaluate_df(df_file, print_eval) return df_file # - for f_name in sorted([f for f in os.listdir("../webapp/out") if f.endswith(".txt")]): print f_name evaluate_file(f_name) print # **Evaluating all results** # + dfs = [] for f_name in sorted([f for f in os.listdir("../webapp/out") if f.endswith(".txt")]): df_tmp = evaluate_file(f_name, print_eval=False) df_tmp["evaluator"] = f_name.replace(".txt", "").replace("20_", "") dfs.append(df_tmp) df_all = pnd.concat(dfs) evaluate_df(df_all, print_eval=True) # + def aggregate_samples(df_param): return all(df_param) df_agreement = df_all.groupby(["inclusion_id", "method"], as_index=False)["successful"].agg(aggregate_samples).reset_index() pnd.reset_option('display.max_rows') df_agreement.groupby("method")["successful"].agg(["mean", "count"]) # - df_agreement.groupby(["method"])["mean"].mean() # + def build_word_intrusion(df_param): models = sorted(list(set(df_param.method))) evaluators = sorted(list(set(df_param.evaluator))) df_return = pnd.DataFrame(columns=models, index=evaluators) df_return.index.name = "evaluator" df_return.columns.name = "model" print models for evaluator, df_group_evaluator in df_param.groupby("evaluator"): for model, df_group_model in df_group_evaluator.groupby("method"): df_return.set_value(evaluator, model, evaluate_single(df_group_model)) return df_return def plot_word_intrusion(df_param): df_param = pnd.melt(df_param.reset_index(), id_vars=['evaluator']) df_param = df_param.dropna() df_param = df_param.sort_values(["model", "value"]) models = sorted(list(set(df_param["model"]))) for m in models: df_param.loc[df_param["model"] == m, "offset"] = range(len(df_param["model"] == m)) models = OrderedDict([(v, k+1) for k, v in enumerate(models)]) scatters = np.linspace(-0.25, 0.25, 8) df_param["scatter_x"] = df_param.apply(lambda x: models[x.model] + scatters[x.offset], axis=1) plt.figure(figsize=cm2inch(12, 6), dpi=300) plt.xlim(0.6, 4.8) plt.ylim((0.,1.0)) plt.xticks(models.values(), ["LDA", "LFTM", "TopicVec", "WELDA"], rotation='horizontal') plt.scatter(df_param["scatter_x"], df_param["value"], c="black", marker='x', s=20, alpha=1.0, lw = 0.5) width = 0.25 for m in models: mean = df_param[df_param.model == m]["value"].mean() #plt.axhline(y=mean) #print models[m] plt.hlines(y=mean, xmin=models[m]-width, xmax=models[m]+width, linestyles="dashed", linewidth=0.5) plt.text(models[m] + width + 0.03, mean, "$%.2f$" % mean, verticalalignment="center") df_no_mixture = df_all[df_all.method.apply(lambda x: "mixture" not in x)] df_20 = df_no_mixture[df_no_mixture.method.apply(lambda x: "20" in x)] df_50 = df_no_mixture[df_no_mixture.method.apply(lambda x: "20" not in x)] df_word_intrusion_20 = build_word_intrusion(df_20) plot_word_intrusion(df_word_intrusion_20) df_word_intrusion_50 = build_word_intrusion(df_50) plot_word_intrusion(df_word_intrusion_50) # - df_word_intrusion_20 df_word_intrusion_50
notebooks/Word Intrusion.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 matplotlib.pyplot as plt # per i plot import numpy as np # per manipolazione vettori from scipy.odr import * # per i fit from uncertainties import ufloat from uncertainties.umath import * from math import sqrt # %matplotlib notebook # + # definizione delle funzioni utili per i calcoli # definisco la funzione di fit def fit_function(params, x): return params[4]*(params[0]**2 + params[1]**2 + 2*params[0]*params[1]*np.cos(2*params[2]*x + params[3])) # Calcolo del rapporto d'onda stazionaria def rapporto_onda_stazionaria(U_F, U_B): return (U_F + U_B) / (U_F - U_B) # Calcolo dell'impedenza del carico def impedenza_carico(impedenza_guida_onda, U_F, U_B, delta_phi): cos_phi = float(cos(delta_phi)) sin_phi = float(sin(delta_phi)) real = impedenza_guida_onda * (U_F**2 - U_B**2) / (U_F**2 + U_B**2 - 2*U_F*U_B*cos_phi) imaginary = impedenza_guida_onda * (2*U_F*U_B*sin_phi) / (U_F**2 + U_B**2 - 2*U_F*U_B*cos_phi) return real, imaginary def calc_lambda_guida(nu, a, c): first = (nu/c)**2 second = (1/(2*a))**2 return (first - second)**(-1/2) # - # # Impedenza e SWR dei vari carichi # # * Calcoliamo l'impedenza in guida d'onda # # 1. Eseguiamo il fit della funzione # 2. Calcoliamo impedenza del carico # 3. Calcoliamo il rapporto $SWR$ # ## Impedenza in guida d'onda # # $$ # Z_{guida} = Z_0 \frac{\lambda_{guida}}{\lambda_{0}}\frac{2b}{a} # $$ # # Utilizziamo # $$ # Z_0 = 377 \Omega \qquad \text{impedenza caratteristica del vuoto} \\ # a = 2.29 cm \\ # b = 1.01 cm \\ # \lambda_{guida} = 3.65cm \\ # \lambda_{0} = 2.85 cm # $$ # Stimiamo gli errori sulla misura della posizione con una precisione di $0.05$mm e l'incertezza sulla tensione di $0.1$V # + b = ufloat(0.0101, 0.0005) # cm a = ufloat(0.0229, 0.0005) c = 3e8 nu = ufloat(10.5275e9, 0.0001e9) lambda_guida = calc_lambda_guida(nu, a, c) lambda_0 = c/nu sigma_x = 0.05 # cm sigma_y = 0.5 Z_g = 377 * lambda_guida / lambda_0 * 2*b/a Z_g # - # Da cui otteniamo # $$ # Z_g = 425 \pm 26 \Omega # $$ # ## Fit del carico adattato # # Utilizziamo il carico adattato `data_adattato.txt` e lo fittiamo. # # + # %matplotlib notebook x_adattato, y_adattato = np.genfromtxt('data_adattato.txt', skip_header=1, unpack=True) model_adattato = Model(fit_function) data_adattato = Data(x_adattato, y_adattato, wd=np.full( (1, np.size(x_adattato)), 1/sigma_x**2),\ we=np.full((1, np.size(y_adattato)), 1/sigma_y**2)) myodr = ODR(data_adattato, model_adattato, beta0=[5.62, 1.35, 1.72, 2.8, 1], ifixb=[1, 1, 1, 1, 0]) myoutput = myodr.run() myoutput.pprint() chi_2 = myoutput.sum_square dof = np.size(x_adattato) - 1 chi_2_ridotto = chi_2/dof U_F = myoutput.beta[0] sigma_U_F = myoutput.sd_beta[0] U_B = myoutput.beta[1] sigma_U_B = myoutput.sd_beta[1] k = myoutput.beta[2] sigma_k = myoutput.sd_beta[2] delta_phi = myoutput.beta[3] sigma_delta_phi = myoutput.sd_beta[3] amplitude = myoutput.beta[4] sigma_amplitude = myoutput.sd_beta[4] parameters = [U_F, U_B, k, delta_phi, amplitude] parameters_text = """ $U_f$ = {} $\pm$ {} $U_b$ = {} $\pm$ {} $k$ = {} $\pm$ {} $\Delta \phi$ = {} $\pm$ {} $A$ = {} $\pm$ {} $\chi_2/dof$ = {} """.format(round(U_F,2), round(sigma_U_F,2), round(U_B,2), round(sigma_U_B,2), round(k,2), round(sigma_k,2), round(delta_phi,2), round(sigma_delta_phi,2), round(amplitude,2), round(sigma_amplitude,2), round(chi_2_ridotto, 2)) x = np.linspace(8, 13, 200) y = fit_function(parameters, x) fig, ax = plt.subplots() ax.plot(x, y, label='Fit') ax.errorbar(x_adattato, y_adattato, xerr=sigma_x, yerr=sigma_y, fmt='.', label='Dati') ax.text(12.5, 35, parameters_text, size=11, bbox={ 'alpha':0.5, 'pad':4}) ax.grid() ax.legend() ax.set_ylabel('Voltage (V)') ax.set_xlabel('Length (cm)') ax.set_title('Carico Adattato') ax.set_ylim(15., 50) # - # ## Fit del carico aperto # # Utilizziamo il carico adattato `data_aperto.txt` e lo fittiamo. # + # %matplotlib notebook x_adattato, y_adattato = np.genfromtxt('data_aperto.txt', skip_header=1, unpack=True) model_adattato = Model(fit_function) data_adattato = Data(x_adattato, y_adattato, wd=np.full( (1, np.size(x_adattato)), 1/sigma_x**2),\ we=np.full((1, np.size(y_adattato)), 1/sigma_y**2)) myodr = ODR(data_adattato, model_adattato, beta0=[5.62, 1.35, 1.72, 2.8, 1], ifixb=[1, 1, 1, 1, 0]) myoutput = myodr.run() myoutput.pprint() chi_2 = myoutput.sum_square dof = np.size(x_adattato) - 1 chi_2_ridotto = chi_2/dof U_F = myoutput.beta[0] sigma_U_F = myoutput.sd_beta[0] U_B = myoutput.beta[1] sigma_U_B = myoutput.sd_beta[1] k = myoutput.beta[2] sigma_k = myoutput.sd_beta[2] delta_phi = myoutput.beta[3] sigma_delta_phi = myoutput.sd_beta[3] amplitude = myoutput.beta[4] sigma_amplitude = myoutput.sd_beta[4] parameters = [U_F, U_B, k, delta_phi, amplitude] parameters_text = """ $U_f$ = {} $\pm$ {} $U_b$ = {} $\pm$ {} $k$ = {} $\pm$ {} $\Delta \phi$ = {} $\pm$ {} $A$ = {} $\pm$ {} $\chi_2/dof$ = {} """.format(round(U_F,2), round(sigma_U_F,2), round(U_B,2), round(sigma_U_B,2), round(k,2), round(sigma_k,2), round(delta_phi,2), round(sigma_delta_phi,2), round(amplitude,2), round(sigma_amplitude,2), round(chi_2_ridotto, 2)) x = np.linspace(8, 13, 200) y = fit_function(parameters, x) fig, ax = plt.subplots() ax.plot(x, y, label='Fit') ax.errorbar(x_adattato, y_adattato, xerr=sigma_x, yerr=sigma_y, fmt='.', label='Dati') ax.text(12.5, 35, parameters_text, size=11, bbox={ 'alpha':0.5, 'pad':4}) ax.grid() ax.legend() ax.set_ylabel('Voltage (V)') ax.set_xlabel('Length (cm)') ax.set_title('Carico Adattato') ax.set_ylim(15., 50) # - # ## Analisi con horn # # Utilizziamo il carico adattato `data_aperto.txt` e lo fittiamo. # + # %matplotlib notebook x_adattato, y_adattato = np.genfromtxt('data_horn.txt', skip_header=1, unpack=True) model_adattato = Model(fit_function) data_adattato = Data(x_adattato, y_adattato, wd=np.full( (1, np.size(x_adattato)), 1/sigma_x**2),\ we=np.full((1, np.size(y_adattato)), 1/sigma_y**2)) myodr = ODR(data_adattato, model_adattato, beta0=[5.62, 1.35, 1.72, 2.8, 1], ifixb=[1, 1, 1, 1, 0]) myoutput = myodr.run() myoutput.pprint() chi_2 = myoutput.sum_square dof = np.size(x_adattato) - 1 chi_2_ridotto = chi_2/dof U_F = myoutput.beta[0] sigma_U_F = myoutput.sd_beta[0] U_B = myoutput.beta[1] sigma_U_B = myoutput.sd_beta[1] k = myoutput.beta[2] sigma_k = myoutput.sd_beta[2] delta_phi = myoutput.beta[3] sigma_delta_phi = myoutput.sd_beta[3] amplitude = myoutput.beta[4] sigma_amplitude = myoutput.sd_beta[4] parameters = [U_F, U_B, k, delta_phi, amplitude] parameters_text = """ $U_f$ = {} $\pm$ {} $U_b$ = {} $\pm$ {} $k$ = {} $\pm$ {} $\Delta \phi$ = {} $\pm$ {} $A$ = {} $\pm$ {} $\chi_2/dof$ = {} """.format(round(U_F,2), round(sigma_U_F,2), round(U_B,2), round(sigma_U_B,2), round(k,2), round(sigma_k,2), round(delta_phi,2), round(sigma_delta_phi,2), round(amplitude,2), round(sigma_amplitude,2), round(chi_2_ridotto, 2)) x = np.linspace(8, 13, 200) y = fit_function(parameters, x) fig, ax = plt.subplots() ax.plot(x, y, label='Fit') ax.errorbar(x_adattato, y_adattato, xerr=sigma_x, yerr=sigma_y, fmt='.', label='Dati') ax.text(12.5, 35, parameters_text, size=14, bbox={ 'alpha':0.5, 'pad':4}) ax.grid() ax.legend() ax.set_ylabel('Voltage (V)') ax.set_xlabel('Length (cm)') ax.set_title('Carico Adattato') ax.set_ylim(15., 50) # - # ## Analisi con configurazione riflettente # # Utilizziamo il file `data_riflettente.txt` # + # %matplotlib notebook x_adattato, y_adattato = np.genfromtxt('data_riflettente.txt', skip_header=1, unpack=True) model_adattato = Model(fit_function) data_adattato = Data(x_adattato, y_adattato, wd=np.full( (1, np.size(x_adattato)), 1/sigma_x**2),\ we=np.full((1, np.size(y_adattato)), 1/sigma_y**2)) myodr = ODR(data_adattato, model_adattato, beta0=[5.04, 4.46, 1.74, 0., 1], ifixb=[1, 1, 1, 1, 0], maxit=1000) myoutput = myodr.run() myoutput.pprint() chi_2 = myoutput.sum_square dof = np.size(x_adattato) - 1 chi_2_ridotto = chi_2/dof U_F = myoutput.beta[0] sigma_U_F = myoutput.sd_beta[0] U_B = myoutput.beta[1] sigma_U_B = myoutput.sd_beta[1] k = myoutput.beta[2] sigma_k = myoutput.sd_beta[2] delta_phi = myoutput.beta[3] sigma_delta_phi = myoutput.sd_beta[3] amplitude = myoutput.beta[4] sigma_amplitude = myoutput.sd_beta[4] parameters = [U_F, U_B, k, delta_phi, amplitude] parameters_text = """ $U_f$ = {} $\pm$ {} $U_b$ = {} $\pm$ {} $k$ = {} $\pm$ {} $\Delta \phi$ = {} $\pm$ {} $A$ = {} $\pm$ {} $\chi_2/dof$ = {} """.format(round(U_F,2), round(sigma_U_F,2), round(U_B,2), round(sigma_U_B,2), round(k,2), round(sigma_k,2), round(delta_phi,2), round(sigma_delta_phi,2), round(amplitude,2), round(sigma_amplitude,2), round(chi_2_ridotto, 2)) x = np.linspace(8, 13, 200) y = fit_function(parameters, x) fig, ax = plt.subplots() ax.plot(x, y, label='Fit') ax.errorbar(x_adattato, y_adattato, xerr=sigma_x, yerr=sigma_y, fmt='.', label='Dati') ax.text(12.5, 0, parameters_text, size=14, bbox={ 'alpha':0.5, 'pad':4}) ax.grid() ax.legend() ax.set_ylabel('Voltage (V)') ax.set_xlabel('Length (cm)') ax.set_title('Carico Riflettente') #ax.set_ylim(15., 50) # + # importo le librerire per visualizzare i widgets from ipywidgets import * from IPython.display import display # %matplotlib inline # leggo i dati x_adattato, y_adattato = np.genfromtxt('data_riflettente.txt', skip_header=1, unpack=True) def execute_fit(x, y, sigma_x, sigma_y, fit_function, beta0, ifixb=[1,1,1,1,1]): # eseguo il fit dei dati usando come pesi le deviazioni standard e come parametri # iniziali quelli definiti nel parametro 'beta0' model_adattato = Model(fit_function) data_adattato = Data(x, y, wd=np.full( (1, np.size(x)), 1/sigma_x**2),\ we=np.full((1, np.size(y)), 1/sigma_y**2)) myodr = ODR(data_adattato, model_adattato, beta0=beta0, ifixb=ifixb) myoutput = myodr.run() # salvo i parametri ottenuti chi_2 = myoutput.sum_square dof = np.size(x_adattato) - 1 chi_2_ridotto = round(chi_2/dof, 2) U_F = round(myoutput.beta[0], 5) sigma_U_F = round(myoutput.sd_beta[0], 5) U_B = round(myoutput.beta[1], 5) sigma_U_B = round(myoutput.sd_beta[1], 5) k = round(myoutput.beta[2], 2) sigma_k = round(myoutput.sd_beta[2], 2) delta_phi = round(myoutput.beta[3], 2) sigma_delta_phi = round(myoutput.sd_beta[3], 2) amplitude = round(myoutput.beta[4], 2) sigma_amplitude = round(myoutput.sd_beta[4], 2) parameters = [chi_2, dof, chi_2_ridotto, U_F, sigma_U_F, U_B, sigma_U_B, k, sigma_k, delta_phi, sigma_delta_phi, amplitude, sigma_amplitude] # preparo la stringa di testo da visualizzare nel grafico parameters_text = """ $U_f$ = {} $\pm$ {} $U_b$ = {} $\pm$ {} $k$ = {} $\pm$ {} $\Delta \phi$ = {} $\pm$ {} $A$ = {} $\pm$ {} $\chi_2/dof$ = {} """.format(U_F, sigma_U_F, U_B, sigma_U_B, k, sigma_k, delta_phi, sigma_delta_phi, amplitude, sigma_amplitude, chi_2_ridotto) # plotto i dati da manipolare e i dati reali x = np.linspace(8, 13, 200) y = fit_function(parameters, x) fig, ax = plt.subplots() plot_data, = ax.plot(x, y, label='Fit') # definisco la funzione che viene chiamata quando un widget cambia valore def manipulate(U_F, U_B, k, delta_phi, amplitude): x = np.linspace(8, 13, 200) params = [U_F, U_B, k, delta_phi, amplitude] plot_data.set_ydata(fit_function(params, x)) display(fig) # definisco i ranges, gli step e i valori iniziali dei vari parametri che voglio modificare options = interactive(manipulate, U_F=widgets.FloatSlider(min=0,max=6,step=0.05,value=parameters[0]), U_B=widgets.FloatSlider(min=0,max=6,step=0.05,value=parameters[1]), k=widgets.FloatSlider(min=-10,max=180,step=5,value=parameters[2]), delta_phi=widgets.FloatSlider(min=-3,max=10,step=0.05,value=parameters[3]), amplitude=widgets.FloatSlider(min=0,max=2,step=0.02,value=parameters[4])) display(options) # definisco la funzione che viene chiamata quando il bottone viene cliccato def handle_fit(obj): params = [obj.data['params']] execute_fit(obj.data['x'], obj.data['y'], obj.data['sigma_x'], obj.data['sigma_y'], obj.data['fit_function'], params) print(obj.data) # impacchettizzo tutti i dati per poter eseguire un fit completo data = { 'x': x_adattato, 'y': y_adattato, 'sigma_x': sigma_x, 'sigma_y': sigma_y, 'fit_function': fit_function, 'params': options.kwargs #'ifixb': [0, 0, 0, 1, 1] } # giusto perchè siamo belli aggiungiamo un bottone che quando viene schiacciato # riesegue il fit utilizzando i parametri impostati ''' fit_button = widgets.Button(description="Fit this function", data=data) display(fit_button) fit_button.on_click(handle_fit) ''' # plotto i dati reali con le loro incertezze ax.errorbar(x_adattato, y_adattato, xerr=sigma_x, yerr=sigma_y, fmt='.', label='Dati') #ax.text(8, 5, parameters_text, size=14, # bbox={ 'alpha':0.5, 'pad':10}) ax.grid() ax.legend() #ax.set_ylim(0., 40) # -
lab16microonde/.ipynb_checkpoints/Analisi e fit-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 # --- # # read html table from Wikipedia # # https://en.wikipedia.org/wiki/Government_debt #เรียนรู้ การดึงข้อมูลตารางต่างๆ บนเว็บไซต์ from IPython.display import IFrame, YouTubeVideo, SVG, HTML YouTubeVideo('ucjGGJHzC9I', 400,300) import pandas as pd print(f'pandas version: {pd.__version__}') from datetime import datetime str(datetime.now()) dfs=pd.read_html('https://en.wikipedia.org/wiki/Government_debt') len(dfs) dfs dfs[0] dfs[1] dfs[2] dfs=pd.read_html('https://en.wikipedia.org/wiki/Government_debt', match='country') len(dfs) dfs dfs[0] dfs=pd.read_html('https://en.wikipedia.org/wiki/Government_debt', match='country', header=0) len(dfs) df=dfs[0] df df.info() df['% of GDP']=df['% of GDP'].str.replace(r'%', '').astype('float') df['% of world public debt']=df['% of world public debt'].str.replace(r'%', '').astype('float') df df.info() df.country=df.country.str.replace(r'[^\s+\w]', '') df import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline # %config InlineBackend.figure_format = 'retina' plt.figure(figsize=(7, 7)) sns.barplot(x='% of GDP', y='country', data=df.sort_values(by='% of GDP', ascending=False), color='.75') dg=df.sort_values(by='% of GDP', ascending=False) dg colors = ['deepskyblue' if s == 'Thailand' else '.75' for s in dg['country']] colors plt.figure(figsize=(7, 7)) sns.barplot(x='% of GDP', y='country', data=df.sort_values(by='% of GDP', ascending=False), palette=colors); colors = ['deepskyblue' if s == 'Thailand' else '.75' if s != 'World' else 'yellowgreen' for s in dg['country']] colors plt.figure(figsize=(7, 7)) sns.barplot(x='% of GDP', y='country', data=df.sort_values(by='% of GDP', ascending=False), palette=colors) sns.despine() plt.ylabel('');
learn_jupyter/15_pandas_read_html_gov_debt.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/caujw/fchollet/blob/main/chapter07_working-with-keras.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="iKFkh13mQTAr" # This is a companion notebook for the book [Deep Learning with Python, Second Edition](https://www.manning.com/books/deep-learning-with-python-second-edition?a_aid=keras&a_bid=76564dff). For readability, it only contains runnable code blocks and section titles, and omits everything else in the book: text paragraphs, figures, and pseudocode. # # **If you want to be able to follow what's going on, I recommend reading the notebook side by side with your copy of the book.** # # This notebook was generated for TensorFlow 2.6. # + [markdown] id="GJp9uS9tQTAu" # # Working with Keras: A deep dive # + [markdown] id="BTzYqnNJQTAv" # ## A spectrum of workflows # + [markdown] id="ujFqi56OQTAv" # ## Different ways to build Keras models # + [markdown] id="559ZqGAiQTAw" # ### The Sequential model # + [markdown] id="EWWi5eXIQTAw" # **The `Sequential` class** # + id="HqqbzA-6QTAw" from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential([ layers.Dense(64, activation="relu"), layers.Dense(10, activation="softmax") ]) # + [markdown] id="sRBQK4lYQTAx" # **Incrementally building a Sequential model** # + id="7Av1h0TXQTAy" model = keras.Sequential() model.add(layers.Dense(64, activation="relu")) model.add(layers.Dense(10, activation="softmax")) # + [markdown] id="dOG5srnPQTAy" # **Calling a model for the first time to build it** # + id="Q0r-Uee3QTAy" model.build(input_shape=(None, 3)) model.weights # + [markdown] id="hfzw5i7kQTAz" # **The summary method** # + id="n6d3wqvWQTAz" model.summary() # + [markdown] id="6_xzT_pbQTAz" # **Naming models and layers with the `name` argument** # + id="b_pZMu2DQTAz" model = keras.Sequential(name="my_example_model") model.add(layers.Dense(64, activation="relu", name="my_first_layer")) model.add(layers.Dense(10, activation="softmax", name="my_last_layer")) model.build((None, 3)) model.summary() # + [markdown] id="rmW_f7x3QTA0" # **Specifying the input shape of your model in advance** # + id="yiS-6hUhQTA0" model = keras.Sequential() model.add(keras.Input(shape=(3,))) model.add(layers.Dense(64, activation="relu")) # + id="zQJ5r4hvQTA0" model.summary() # + id="wPUQ63WHQTA1" model.add(layers.Dense(10, activation="softmax")) model.summary() # + [markdown] id="2jqGpztTQTA1" # ### The Functional API # + [markdown] id="rdr2xX-VQTA1" # #### A simple example # + [markdown] id="Pwgsj2EnQTA2" # **A simple Functional model with two `Dense` layers** # + id="uHb0TRuXQTA2" inputs = keras.Input(shape=(3,), name="my_input") features = layers.Dense(64, activation="relu")(inputs) outputs = layers.Dense(10, activation="softmax")(features) model = keras.Model(inputs=inputs, outputs=outputs) # + id="0_M-vJIGQTA2" inputs = keras.Input(shape=(3,), name="my_input") # + id="XvtsRzxTQTA3" inputs.shape # + id="a7dito19QTA3" inputs.dtype # + id="WPp_UcCkQTA3" features = layers.Dense(64, activation="relu")(inputs) # + id="HCVA5h69QTA3" features.shape # + id="NfOJnxI1QTA3" outputs = layers.Dense(10, activation="softmax")(features) model = keras.Model(inputs=inputs, outputs=outputs) # + id="-hq7z0R-QTA4" model.summary() # + [markdown] id="Kt3GsFWTQTA4" # #### Multi-input, multi-output models # + [markdown] id="s8mTdcquQTA4" # **A multi-input, multi-output Functional model** # + id="u2Fi_4cLQTA4" vocabulary_size = 10000 num_tags = 100 num_departments = 4 title = keras.Input(shape=(vocabulary_size,), name="title") text_body = keras.Input(shape=(vocabulary_size,), name="text_body") tags = keras.Input(shape=(num_tags,), name="tags") features = layers.Concatenate()([title, text_body, tags]) features = layers.Dense(64, activation="relu")(features) priority = layers.Dense(1, activation="sigmoid", name="priority")(features) department = layers.Dense( num_departments, activation="softmax", name="department")(features) model = keras.Model(inputs=[title, text_body, tags], outputs=[priority, department]) # + [markdown] id="Y4NwsfeuQTA4" # #### Training a multi-input, multi-output model # + [markdown] id="n-rmuX51QTA5" # **Training a model by providing lists of input & target arrays** # + id="FrsRNOifQTA5" import numpy as np num_samples = 1280 title_data = np.random.randint(0, 2, size=(num_samples, vocabulary_size)) text_body_data = np.random.randint(0, 2, size=(num_samples, vocabulary_size)) tags_data = np.random.randint(0, 2, size=(num_samples, num_tags)) priority_data = np.random.random(size=(num_samples, 1)) department_data = np.random.randint(0, 2, size=(num_samples, num_departments)) model.compile(optimizer="rmsprop", loss=["mean_squared_error", "categorical_crossentropy"], metrics=[["mean_absolute_error"], ["accuracy"]]) model.fit([title_data, text_body_data, tags_data], [priority_data, department_data], epochs=1) model.evaluate([title_data, text_body_data, tags_data], [priority_data, department_data]) priority_preds, department_preds = model.predict([title_data, text_body_data, tags_data]) # + [markdown] id="ltEDshOrQTA5" # **Training a model by providing dicts of input & target arrays** # + id="qaC3pZGWQTA6" model.compile(optimizer="rmsprop", loss={"priority": "mean_squared_error", "department": "categorical_crossentropy"}, metrics={"priority": ["mean_absolute_error"], "department": ["accuracy"]}) model.fit({"title": title_data, "text_body": text_body_data, "tags": tags_data}, {"priority": priority_data, "department": department_data}, epochs=1) model.evaluate({"title": title_data, "text_body": text_body_data, "tags": tags_data}, {"priority": priority_data, "department": department_data}) priority_preds, department_preds = model.predict( {"title": title_data, "text_body": text_body_data, "tags": tags_data}) # + [markdown] id="1rK6ZaVsQTA6" # #### The power of the Functional API: Access to layer connectivity # + id="I7ZP_CToQTA6" keras.utils.plot_model(model, "ticket_classifier.png") # + id="N-_X5RrTQTA6" keras.utils.plot_model(model, "ticket_classifier_with_shape_info.png", show_shapes=True) # + [markdown] id="j04nw7_FQTA6" # **Retrieving the inputs or outputs of a layer in a Functional model** # + id="r-T9uju4QTA7" model.layers # + id="aG1EI9e2QTA7" model.layers[3].input # + id="1A3KrrH7QTA7" model.layers[3].output # + [markdown] id="FjXBhMuqQTA7" # **Creating a new model by reusing intermediate layer outputs** # + id="3D5LbmNMQTA7" features = model.layers[4].output difficulty = layers.Dense(3, activation="softmax", name="difficulty")(features) new_model = keras.Model( inputs=[title, text_body, tags], outputs=[priority, department, difficulty]) # + id="3UBrQisWQTA8" keras.utils.plot_model(new_model, "updated_ticket_classifier.png", show_shapes=True) # + [markdown] id="xf_ZHWbxQTA8" # ### Subclassing the Model class # + [markdown] id="dvgKviKBQTA8" # #### Rewriting our previous example as a subclassed model # + [markdown] id="uBk2SyS7QTA8" # **A simple subclassed model** # + id="fVJinEERQTA8" class CustomerTicketModel(keras.Model): def __init__(self, num_departments): super().__init__() self.concat_layer = layers.Concatenate() self.mixing_layer = layers.Dense(64, activation="relu") self.priority_scorer = layers.Dense(1, activation="sigmoid") self.department_classifier = layers.Dense( num_departments, activation="softmax") def call(self, inputs): title = inputs["title"] text_body = inputs["text_body"] tags = inputs["tags"] features = self.concat_layer([title, text_body, tags]) features = self.mixing_layer(features) priority = self.priority_scorer(features) department = self.department_classifier(features) return priority, department # + id="lnim2GMEQTA8" model = CustomerTicketModel(num_departments=4) priority, department = model( {"title": title_data, "text_body": text_body_data, "tags": tags_data}) # + id="0Kk20Ye-QTA9" model.compile(optimizer="rmsprop", loss=["mean_squared_error", "categorical_crossentropy"], metrics=[["mean_absolute_error"], ["accuracy"]]) model.fit({"title": title_data, "text_body": text_body_data, "tags": tags_data}, [priority_data, department_data], epochs=1) model.evaluate({"title": title_data, "text_body": text_body_data, "tags": tags_data}, [priority_data, department_data]) priority_preds, department_preds = model.predict({"title": title_data, "text_body": text_body_data, "tags": tags_data}) # + [markdown] id="xNd5HDRuQTA9" # #### Beware: What subclassed models don't support # + [markdown] id="cVUGWtAUQTA9" # ### Mixing and matching different components # + [markdown] id="k0m9GWgRQTA9" # **Creating a Functional model that includes a subclassed model** # + id="QI4YAe7mQTA9" class Classifier(keras.Model): def __init__(self, num_classes=2): super().__init__() if num_classes == 2: num_units = 1 activation = "sigmoid" else: num_units = num_classes activation = "softmax" self.dense = layers.Dense(num_units, activation=activation) def call(self, inputs): return self.dense(inputs) inputs = keras.Input(shape=(3,)) features = layers.Dense(64, activation="relu")(inputs) outputs = Classifier(num_classes=10)(features) model = keras.Model(inputs=inputs, outputs=outputs) # + [markdown] id="z-9sKRICQTA-" # **Creating a subclassed model that includes a Functional model** # + id="PQgH350dQTA-" inputs = keras.Input(shape=(64,)) outputs = layers.Dense(1, activation="sigmoid")(inputs) binary_classifier = keras.Model(inputs=inputs, outputs=outputs) class MyModel(keras.Model): def __init__(self, num_classes=2): super().__init__() self.dense = layers.Dense(64, activation="relu") self.classifier = binary_classifier def call(self, inputs): features = self.dense(inputs) return self.classifier(features) model = MyModel() # + [markdown] id="_ebIy6xQQTA-" # ### Remember: Use the right tool for the job # + [markdown] id="yKNokVsSQTA-" # ## Using built-in training and evaluation loops # + [markdown] id="irTDtC1HQTA-" # **The standard workflow: `compile()`, `fit()`, `evaluate()`, `predict()`** # + id="wIDQV_U_QTA-" from tensorflow.keras.datasets import mnist def get_mnist_model(): inputs = keras.Input(shape=(28 * 28,)) features = layers.Dense(512, activation="relu")(inputs) features = layers.Dropout(0.5)(features) outputs = layers.Dense(10, activation="softmax")(features) model = keras.Model(inputs, outputs) return model (images, labels), (test_images, test_labels) = mnist.load_data() images = images.reshape((60000, 28 * 28)).astype("float32") / 255 test_images = test_images.reshape((10000, 28 * 28)).astype("float32") / 255 train_images, val_images = images[10000:], images[:10000] train_labels, val_labels = labels[10000:], labels[:10000] model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=3, validation_data=(val_images, val_labels)) test_metrics = model.evaluate(test_images, test_labels) predictions = model.predict(test_images) # + [markdown] id="iHTw9kPhQTA_" # ### Writing your own metrics # + [markdown] id="wzhIHVYNQTA_" # **Implementing a custom metric by subclassing the `Metric` class** # + id="AO3ZrIbvQTA_" import tensorflow as tf class RootMeanSquaredError(keras.metrics.Metric): def __init__(self, name="rmse", **kwargs): super().__init__(name=name, **kwargs) self.mse_sum = self.add_weight(name="mse_sum", initializer="zeros") self.total_samples = self.add_weight( name="total_samples", initializer="zeros", dtype="int32") def update_state(self, y_true, y_pred, sample_weight=None): y_true = tf.one_hot(y_true, depth=tf.shape(y_pred)[1]) mse = tf.reduce_sum(tf.square(y_true - y_pred)) self.mse_sum.assign_add(mse) num_samples = tf.shape(y_pred)[0] self.total_samples.assign_add(num_samples) def result(self): return tf.sqrt(self.mse_sum / tf.cast(self.total_samples, tf.float32)) def reset_state(self): self.mse_sum.assign(0.) self.total_samples.assign(0) # + id="W8ZX82kYQTA_" model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy", RootMeanSquaredError()]) model.fit(train_images, train_labels, epochs=3, validation_data=(val_images, val_labels)) test_metrics = model.evaluate(test_images, test_labels) # + [markdown] id="24N5TAV0QTA_" # ### Using callbacks # + [markdown] id="6GJpGjTgQTA_" # #### The EarlyStopping and ModelCheckpoint callbacks # + [markdown] id="etVYaPMqQTBA" # **Using the `callbacks` argument in the `fit()` method** # + id="0IS6WSK_QTBA" callbacks_list = [ keras.callbacks.EarlyStopping( monitor="val_accuracy", patience=2, ), keras.callbacks.ModelCheckpoint( filepath="checkpoint_path.keras", monitor="val_loss", save_best_only=True, ) ] model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=10, callbacks=callbacks_list, validation_data=(val_images, val_labels)) # + id="9Wx3d7vSQTBA" model = keras.models.load_model("checkpoint_path.keras") # + [markdown] id="ffXmlueoQTBA" # ### Writing your own callbacks # + [markdown] id="4zn0jivCQTBA" # **Creating a custom callback by subclassing the `Callback` class** # + id="2v9CZs37QTBB" from matplotlib import pyplot as plt class LossHistory(keras.callbacks.Callback): def on_train_begin(self, logs): self.per_batch_losses = [] def on_batch_end(self, batch, logs): self.per_batch_losses.append(logs.get("loss")) def on_epoch_end(self, epoch, logs): plt.clf() plt.plot(range(len(self.per_batch_losses)), self.per_batch_losses, label="Training loss for each batch") plt.xlabel(f"Batch (epoch {epoch})") plt.ylabel("Loss") plt.legend() plt.savefig(f"plot_at_epoch_{epoch}") self.per_batch_losses = [] # + id="TsK9XcQrQTBB" model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=10, callbacks=[LossHistory()], validation_data=(val_images, val_labels)) # + [markdown] id="vpdxhwc1QTBB" # ### Monitoring and visualization with TensorBoard # + id="bZCTMhofQTBB" model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) tensorboard = keras.callbacks.TensorBoard( log_dir="/full_path_to_your_log_dir", ) model.fit(train_images, train_labels, epochs=10, validation_data=(val_images, val_labels), callbacks=[tensorboard]) # + id="Cds5vbwTQTBC" # %load_ext tensorboard # %tensorboard --logdir /full_path_to_your_log_dir # + [markdown] id="ExKk4AZxQTBC" # ## Writing your own training and evaluation loops # + [markdown] id="WHKBY3m5QTBD" # ### Training versus inference # + [markdown] id="mdT5oLfMQTBD" # ### Low-level usage of metrics # + id="1pO5UUDrQTBD" metric = keras.metrics.SparseCategoricalAccuracy() targets = [0, 1, 2] predictions = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] metric.update_state(targets, predictions) current_result = metric.result() print(f"result: {current_result:.2f}") # + id="bFZWRMcBQTBD" values = [0, 1, 2, 3, 4] mean_tracker = keras.metrics.Mean() for value in values: mean_tracker.update_state(value) print(f"Mean of values: {mean_tracker.result():.2f}") # + [markdown] id="BJ1AHhIfQTBE" # ### A complete training and evaluation loop # + [markdown] id="Kqe9upbiQTBE" # **Writing a step-by-step training loop: the training step function** # + id="d5ZHbGGvQTBE" model = get_mnist_model() loss_fn = keras.losses.SparseCategoricalCrossentropy() optimizer = keras.optimizers.RMSprop() metrics = [keras.metrics.SparseCategoricalAccuracy()] loss_tracking_metric = keras.metrics.Mean() def train_step(inputs, targets): with tf.GradientTape() as tape: predictions = model(inputs, training=True) loss = loss_fn(targets, predictions) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) logs = {} for metric in metrics: metric.update_state(targets, predictions) logs[metric.name] = metric.result() loss_tracking_metric.update_state(loss) logs["loss"] = loss_tracking_metric.result() return logs # + [markdown] id="V-cet0e6QTBE" # **Writing a step-by-step training loop: resetting the metrics** # + id="kVtMhfr2QTBF" def reset_metrics(): for metric in metrics: metric.reset_state() loss_tracking_metric.reset_state() # + [markdown] id="Kdg4EKCjQTBF" # **Writing a step-by-step training loop: the loop itself** # + id="WR3nrpXJQTBF" training_dataset = tf.data.Dataset.from_tensor_slices((train_images, train_labels)) training_dataset = training_dataset.batch(32) epochs = 3 for epoch in range(epochs): reset_metrics() for inputs_batch, targets_batch in training_dataset: logs = train_step(inputs_batch, targets_batch) print(f"Results at the end of epoch {epoch}") for key, value in logs.items(): print(f"...{key}: {value:.4f}") # + [markdown] id="W0qbU6zgQTBF" # **Writing a step-by-step evaluation loop** # + id="TE4nuOyeQTBF" def test_step(inputs, targets): predictions = model(inputs, training=False) loss = loss_fn(targets, predictions) logs = {} for metric in metrics: metric.update_state(targets, predictions) logs["val_" + metric.name] = metric.result() loss_tracking_metric.update_state(loss) logs["val_loss"] = loss_tracking_metric.result() return logs val_dataset = tf.data.Dataset.from_tensor_slices((val_images, val_labels)) val_dataset = val_dataset.batch(32) reset_metrics() for inputs_batch, targets_batch in val_dataset: logs = test_step(inputs_batch, targets_batch) print("Evaluation results:") for key, value in logs.items(): print(f"...{key}: {value:.4f}") # + [markdown] id="0TIs6IwDQTBG" # ### Make it fast with tf.function # + [markdown] id="SriSvXTxQTBG" # **Adding a `tf.function` decorator to our evaluation-step function** # + id="ogNlbmh1QTBG" @tf.function def test_step(inputs, targets): predictions = model(inputs, training=False) loss = loss_fn(targets, predictions) logs = {} for metric in metrics: metric.update_state(targets, predictions) logs["val_" + metric.name] = metric.result() loss_tracking_metric.update_state(loss) logs["val_loss"] = loss_tracking_metric.result() return logs val_dataset = tf.data.Dataset.from_tensor_slices((val_images, val_labels)) val_dataset = val_dataset.batch(32) reset_metrics() for inputs_batch, targets_batch in val_dataset: logs = test_step(inputs_batch, targets_batch) print("Evaluation results:") for key, value in logs.items(): print(f"...{key}: {value:.4f}") # + [markdown] id="iCTfMA4YQTBG" # ### Leveraging fit() with a custom training loop # + [markdown] id="_u0DxrwrQTBG" # **Implementing a custom training step to use with `fit()`** # + id="IYycqTbEQTBG" loss_fn = keras.losses.SparseCategoricalCrossentropy() loss_tracker = keras.metrics.Mean(name="loss") class CustomModel(keras.Model): def train_step(self, data): inputs, targets = data with tf.GradientTape() as tape: predictions = self(inputs, training=True) loss = loss_fn(targets, predictions) gradients = tape.gradient(loss, self.trainable_weights) self.optimizer.apply_gradients(zip(gradients, self.trainable_weights)) loss_tracker.update_state(loss) return {"loss": loss_tracker.result()} @property def metrics(self): return [loss_tracker] # + id="MxgwcBBlQTBH" inputs = keras.Input(shape=(28 * 28,)) features = layers.Dense(512, activation="relu")(inputs) features = layers.Dropout(0.5)(features) outputs = layers.Dense(10, activation="softmax")(features) model = CustomModel(inputs, outputs) model.compile(optimizer=keras.optimizers.RMSprop()) model.fit(train_images, train_labels, epochs=3) # + id="-I-GdnfmQTBH" class CustomModel(keras.Model): def train_step(self, data): inputs, targets = data with tf.GradientTape() as tape: predictions = self(inputs, training=True) loss = self.compiled_loss(targets, predictions) gradients = tape.gradient(loss, self.trainable_weights) self.optimizer.apply_gradients(zip(gradients, self.trainable_weights)) self.compiled_metrics.update_state(targets, predictions) return {m.name: m.result() for m in self.metrics} # + id="7KOsQ3fYQTBH" inputs = keras.Input(shape=(28 * 28,)) features = layers.Dense(512, activation="relu")(inputs) features = layers.Dropout(0.5)(features) outputs = layers.Dense(10, activation="softmax")(features) model = CustomModel(inputs, outputs) model.compile(optimizer=keras.optimizers.RMSprop(), loss=keras.losses.SparseCategoricalCrossentropy(), metrics=[keras.metrics.SparseCategoricalAccuracy()]) model.fit(train_images, train_labels, epochs=3) # + [markdown] id="z_j2YXuqQTBI" # ## Summary
chapter07_working-with-keras.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/R-Owino/ELECTRIC-CAR-USAGE-ANALYSIS-II/blob/hypothesis-tests/Moringa_Data_Science_Core_W4_Independent_Project_2022_03_Rehema_Owino.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="s6Hm9rK92rO3" # #1. Defining the question # # + [markdown] id="W-ROcphV21ps" # ### i. Specifying the question # # Investigate a claim about bluecars by identifying some areas and periods of interest via sampling. # + [markdown] id="s3nofkEB3dX7" # ### ii. Setting the hypotheses # Hypothesis: The average number of bluecars taken from postal code 75015 is greater than that from postal code 75017. # - Null hypothesis:The average number of bluecars taken from postal code 75015 is the same as in postal code 75017 during weekdays. # - Alternative hypothesis: The average number of bluecars taken from postal code 75015 is not the same as in postal code 75017 during weekdays. # + [markdown] id="wXpwqRXc3zGb" # ### iii. Defining the metric for success # This study will be considered a success if we fail to reject the null hypothesis. # + [markdown] id="EicYckLb5An5" # ### iv. Understanding the context # In this problem, we are proving our claim that during weeknds, bluecars do not get picked in area 75017 as much as in area 75015. # + [markdown] id="DqSi9JpI5P4m" # ### v. Experimental design # - Load and read the dataset. # - Perform data wrangling on the dataset. # - Do exploratory data analysis analysis of the bluecars only. # - Perform hypothesis testing. # + [markdown] id="jC_uS0Z-5q0C" # ### vi. Data relevance # The data provided to carry out this study is relevant to the course of study. # + [markdown] id="ipsXvZ1l58jA" # # 2. Find and deal with outliers, anomalies, and missing data within the dataset. # + colab={"base_uri": "https://localhost:8080/"} id="jbE4NsAB10g9" outputId="b5eb947f-ca2e-41fa-fbf6-8e003661f276" # importing the libraries import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from scipy import stats import scipy.stats print('All libraries are imported') # + [markdown] id="h-aFirf77xca" # ### Loading and previewing the datasets # + colab={"base_uri": "https://localhost:8080/", "height": 456} id="cYsgrj2m6i-X" outputId="62b34c9c-a383-447a-9cb9-a19c6c6dba4c" # description of the autolib dataset description = pd.read_excel('http://bit.ly/DSCoreAutolibDatasetGlossary') description # + colab={"base_uri": "https://localhost:8080/", "height": 287} id="IQw6JO6H7YrL" outputId="41d1a4ed-2357-4beb-fb3f-935547e32f9b" # autolib dataset df = pd.read_csv('http://bit.ly/DSCoreAutolibDataset') df.head() # + colab={"base_uri": "https://localhost:8080/", "height": 287} id="YqAr0QSc8xZ6" outputId="0d891564-c80c-4020-babf-2d0ef14f403d" df.tail() # + [markdown] id="ac7AKVqa8-L0" # ### Accessing information about our dataset # + colab={"base_uri": "https://localhost:8080/"} id="zKUc0G5W9C-M" outputId="00da32cb-0547-4994-84a5-3cfc4600993a" # Getting to know more about our dataset by accessing its information df.info() # + colab={"base_uri": "https://localhost:8080/"} id="orgis1X-9ZdN" outputId="48a965a7-8072-4adc-e2f3-9efa0e3b4a74" # Determining the no. of records in our dataset print('Rows are ' + str(df.shape[0]) + ' and columns are ' + str(df.shape[1])) # + [markdown] id="gFi53dHx-E9N" # ### Tidying our dataset # + colab={"base_uri": "https://localhost:8080/"} id="2u3N0Vsi-L8E" outputId="2a3c3144-150b-4b63-e6f3-fb838ed2522a" # Renaming the columns # replacing spaces with _ so that the column names with spaces are one worded and in lower case df.columns = df.columns.str.lower().str.replace(' ', '_') df.columns # + colab={"base_uri": "https://localhost:8080/", "height": 400} id="Db14iTV--Y7A" outputId="a8d18f90-ff70-4fe6-9ef8-a3b45492c600" # Checking for outliers columns = ['n_daily_data_points', 'dayofweek', 'bluecars_taken_sum', 'bluecars_returned_sum', 'utilib_taken_sum'] fig, ax = plt.subplots(ncols = len(columns), figsize = (20, 6)) for i, column in enumerate(columns): sns.boxplot(y = df[column], ax = ax[i]) ax[i].set_title('Boxplot for {}'.format(column)) ax[i].set_xlabel(column) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 400} id="makVmWNsAR4I" outputId="00ce17c6-5e1a-4edc-e9cb-8e976f8f1177" columns = ['utilib_returned_sum', 'utilib_14_taken_sum', 'utilib_14_returned_sum', 'slots_freed_sum', 'slots_taken_sum'] fig, ax = plt.subplots(ncols = len(columns), figsize = (20, 6)) for i, column in enumerate(columns): sns.boxplot(y = df[column], ax = ax[i]) ax[i].set_title('Boxplot for {}'.format(column)) ax[i].set_xlabel(column) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="whbREyy-FyES" outputId="03ed340f-5382-4874-a521-ca408809f48d" # Sum of outliers per column Q1 = df.quantile(0.25) Q3 = df.quantile(0.75) IQR = Q3 - Q1 out_sum = ((df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))).sum() out_sum # + [markdown] id="6evQTrtHENWP" # The outliers are a lot just from the visuals, but could impact the result of the analysis if removed suppose they are viable. # + colab={"base_uri": "https://localhost:8080/"} id="KLPgENF0BmCR" outputId="6c2c961e-f12e-4a3f-8d36-4c4b029cbf94" # Checking for duplicates df.duplicated().any() # + colab={"base_uri": "https://localhost:8080/"} id="lcxQxEk0B9C_" outputId="8d868220-c5e3-4fb5-8c89-9b09ed7283e7" # Checking for missing values df.isnull().any() # + colab={"base_uri": "https://localhost:8080/", "height": 364} id="z1Mdyt42Ceac" outputId="8315c105-fd08-41b4-f7a5-58356fc67cca" # Descriptive analysis of the numerical columns df.describe() # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="HsLdPHuTFnQu" outputId="004beadf-b903-4ada-8361-3d685e3001df" # dropping unnecessary columns autolib = df.drop(['utilib_14_returned_sum', 'utilib_14_taken_sum', 'utilib_returned_sum', 'utilib_taken_sum', 'dayofweek'], axis=1) autolib.head() # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="DJdia-ItOiTj" outputId="5a4d54cd-a4c8-4b36-c2ad-116b278923f1" # changing the date column data type to datetime autolib['date']= pd.to_datetime(autolib['date']) autolib.head() # + colab={"base_uri": "https://localhost:8080/", "height": 250} id="SDtKi6uaO7o0" outputId="18c84208-34fb-4e9b-fcbc-45cea50fdc14" # splitting the date column to month, year and date autolib['day'] = autolib['date'].dt.day autolib['month'] = autolib['date'].dt.month autolib['year'] = autolib['date'].dt.year autolib.head() # + colab={"base_uri": "https://localhost:8080/", "height": 356} id="GU2e92NdPiIn" outputId="bc29ca8d-dd66-474c-a5a4-be49fac3fcde" # naming the months autolib.month.unique() def month(month): if month==1: return 'Jan' elif month==2: return 'Feb' elif month==3: return 'March' elif month == 4: return 'April' elif month == 5: return 'May' elif month==6: return "June" autolib['date_month']=autolib['month'].apply(month) autolib.head() # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="tbv2nbLTQkq3" outputId="dca16bb0-4ac3-4e6f-96b5-1a4ea31fd4b9" auto = autolib.drop(['date', 'month', 'year'], axis = 1) auto.head() # + [markdown] id="HmMm9DkGLapV" # # 3. Exploratory data analysis # + [markdown] id="ZKureE4oLzUZ" # ### Univariate analysis # + [markdown] id="P6FHtLAXNWJA" # Mean, mode and median of bluecars taken # + colab={"base_uri": "https://localhost:8080/"} id="aLjQlXMnLZ9B" outputId="ec2447f4-92c2-4843-a1cf-fc174341eb58" print("The mean: ",auto.bluecars_taken_sum.mean()) print("The median: ",auto.bluecars_taken_sum.median()) print("The mode: ",auto.bluecars_taken_sum.mode()) # + [markdown] id="lImXHPTuNEVB" # Standard deviation, variance, kurtosis and skewness of bluecars taken # + colab={"base_uri": "https://localhost:8080/"} id="pGh4ovW8M6DL" outputId="be68fb43-30ce-4a92-9fe9-e9da08c22613" print("The Standard Deviation: ",auto.bluecars_taken_sum.std()) print("The Variance: ",auto.bluecars_taken_sum.var()) print("The Kurtosis: ",auto.bluecars_taken_sum.kurt()) print("The Skewness: ",auto.bluecars_taken_sum.skew()) # + [markdown] id="pfLinQH1N-x5" # Mean, mode and median of bluecars returned # + colab={"base_uri": "https://localhost:8080/"} id="WotCgK-7OKei" outputId="074489be-0cf8-486f-ad7e-c071248b8412" print("The mean: ",auto.bluecars_returned_sum.mean()) print("The median: ",auto.bluecars_returned_sum.median()) print("The mode: ",auto.bluecars_returned_sum.mode()) # + [markdown] id="aYtMp9tmOFwc" # Standard deviation, variance, kurtosis and skewness of bluecars returned # + colab={"base_uri": "https://localhost:8080/"} id="2MuLs-jwOdFn" outputId="d289435b-bd89-4239-8eef-32bb2c0f4076" print("The Standard Deviation: ",auto.bluecars_returned_sum.std()) print("The Variance: ",auto.bluecars_returned_sum.var()) print("The Kurtosis: ",auto.bluecars_returned_sum.kurt()) print("The Skewness: ",auto.bluecars_returned_sum.skew()) # + colab={"base_uri": "https://localhost:8080/", "height": 285} id="OkULZJpJQRZn" outputId="9d5f5009-c699-41aa-efb4-089cdfad469f" # Histogram for bluecars taken sns.histplot(data=auto, x='bluecars_taken_sum', bins = 20, kde = True) sns.set(rc={'figure.figsize':(10,6)}) # + colab={"base_uri": "https://localhost:8080/", "height": 339} id="yvxQ-YyqRFem" outputId="9ddf8476-4ea6-41dd-d8c9-81d3d75e7940" # Histogram for bluecars returned sns.histplot(data=auto, x='bluecars_returned_sum', bins = 20, kde = True) sns.set(rc={'figure.figsize':(10,4)}) # + [markdown] id="jFQtAlj3Rys9" # Univariate analysis conclusions: # - Kurtosis for both columns show that the data is heavily tailed more than for a normal distribution. # - Both the taken and returned columns look very much alike. # # + [markdown] id="T_D1-LEAScuE" # ### Bivariate analysis # + colab={"base_uri": "https://localhost:8080/", "height": 530} id="HAkwv-2NSlKT" outputId="9e7fb569-8e41-4a03-e5e8-606e2540061b" # Plotting a correlation matrix corr_ = auto.corr() sns.heatmap(corr_, cmap="YlGnBu", annot=True) sns.set(rc = {'figure.figsize':(15,15)}) plt.title('Correlation matrix for the numerical columns') # + colab={"base_uri": "https://localhost:8080/", "height": 704} id="PV0N-qgTUe1M" outputId="ba3ff423-cbed-4349-b2f8-f8b6ec126836" # the frequency distribution of the bluecars taken and bluecars returned columns col_names = ['bluecars_taken_sum', 'bluecars_returned_sum'] fig, ax = plt.subplots(len(col_names), figsize=(10,10)) for i, col_val in enumerate(col_names): sns.distplot(auto[col_val], hist=True, ax=ax[i], color='magenta') ax[i].set_xlabel(col_val, fontsize=12) ax[i].set_ylabel(col_val, fontsize=12) plt.show() # + [markdown] id="E9iyxYw5W-RE" # Bivariate analysis conclusions: # - There is a high correlation between bluecars taken and bluecars returned. # - Both columns, bluecars taken and bluecars returned are normally distributed even though they are right-skewed. # + [markdown] id="rval8aLtZzfB" # ### Data sampling # + colab={"base_uri": "https://localhost:8080/", "height": 437} id="8m4bhnbGJL1C" outputId="75b3c5a0-f0df-478e-ee5e-966b8e77c17a" # The number of bluecars taken by month fig, ax=plt.subplots(figsize=(8,6)) plt.suptitle('Number of bluecars per month') sns.barplot(x='date_month',y='bluecars_taken_sum',palette='Set2',data=auto) for p in ax.patches: ax.annotate(format(p.get_height(), '.2f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points') # + [markdown] id="Ow3mUPjjXHeU" # June had the highest number of taken bluecars. # + colab={"base_uri": "https://localhost:8080/", "height": 375} id="TaD5X6QrYhev" outputId="775b6ed3-dd83-4e46-8d6c-c9e4113df294" # The number od bluecars taken by day type (weekday or weekend) fig, ax=plt.subplots(figsize=(5,5)) plt.suptitle('The total number of bluecars per day t') sns.barplot(x='day_type',y='bluecars_taken_sum',palette='Set2',data = auto) for p in ax.patches: ax.annotate(format(p.get_height(), '.2f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points') # + [markdown] id="AvbET4wKY_6S" # Most bluecars were taken during weekends. # + colab={"base_uri": "https://localhost:8080/", "height": 394} id="tLtVAdAUXQ3y" outputId="e1c0968a-4f59-4413-c105-ee8b821e8ac0" # The number of bluecars taken by postal code postal_code=auto.pivot_table(values=['bluecars_taken_sum'],index=['postal_code'],aggfunc='sum').sort_values(by='bluecars_taken_sum',ascending=0) postal_code.head(10) # + [markdown] id="2It2wZIjZKqC" # The most popular postal code where bluecars were being picked was 75015. # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="CpeocxbwZ5hu" outputId="197cb911-a506-4932-dae4-e50d97d56ab5" # Selecting only weekdays to work with that period weekday = auto[auto['day_type']=='weekday'] weekday.head() # + [markdown] id="Bu8jcJX6a67J" # Simple random sampling is used as the method of sampling. This is because random samples are the best method of selecting a sample from the population of interest. The advantages are that the sample represents the target population and eliminates sampling bias. # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="JlmuvFincWlk" outputId="b52521e0-ab3d-4885-e127-cb2c84a2711e" # applying stratified data sampling on the date_month month_samp = weekday.sample(n = 1500,replace='False') month_samp.head() # + colab={"base_uri": "https://localhost:8080/"} id="t--q8VuMc48a" outputId="30a1f877-59a4-494d-f638-8633129d5367" # shape of our sample data print('Rows are ' + str(month_samp.shape[0]) + ' and columns are ' + str(month_samp.shape[1])) # + colab={"base_uri": "https://localhost:8080/"} id="Ne00uPoPJlwu" outputId="c9f7438a-97c3-4287-e4eb-47da41a7f7f4" # the number of values in each month month_samp['date_month'].value_counts() # + [markdown] id="DI5CVjzSXi-_" # #4. Hypothesis testing # + [markdown] id="hXuliKCuYQ78" # Hypothesis: The number of bluecars taken from postal code 75015 is greater than that from postal code 75017. # - Null hypothesis: The number of bluecars taken from postal code 75015 is the same as in postal code 75017 during weekends. # - Alternative hypothesis: The number of bluecars taken from postal code 75015 is not the same as in postal code 75017 during weekends. # + [markdown] id="dlQ0iTc2lX4U" # Selecting the statistical test: # - A t-test will be used # - The confidence level is set at 95% # - The alpha value is 0.05 # + colab={"base_uri": "https://localhost:8080/"} id="f5wm-mA7XmSi" outputId="ab1c8a26-112d-46d3-f1b3-9c7eafd1d18c" # mean of the sample for the taken blue cars avg = month_samp['bluecars_taken_sum'].mean() avg # + colab={"base_uri": "https://localhost:8080/"} id="J2nfSrKKYENM" outputId="4715b14e-4c1b-4a37-f3f7-401e04d6ce2b" # standard deviation for the taken blue cars stdev = month_samp['bluecars_taken_sum'].std() stdev # + [markdown] id="Br76t-E7wDEQ" # The sample data meets the requirements to perform a t-test, that is: # - The sample size is less than 30 # - The data is normally distributed # - The samples are independent of each other # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="EbAqMCyuvtI4" outputId="f66f2bb9-63c8-41af-9f33-2929f198fa1e" area_75015 = month_samp[(month_samp.postal_code == 75015)] area_75015.head() # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="_7kdtJyCZBPh" outputId="2411494e-5a19-4436-cbf7-5a8e9d676b60" area_75017 = month_samp[(month_samp.postal_code == 75017)] area_75017.head() # + [markdown] id="Pbt4WHVkZsm6" # Mean of the population = 125.92695057506994 # # Sample size = 1000 # # Sample mean = 116.452 # # Standard deviation of the sample = 166.44208304193452 # # Confidence interval = 0.05 # # # + colab={"base_uri": "https://localhost:8080/"} id="U_JelXqEaOjA" outputId="925035a9-a236-488f-a4b0-81b0a6c42bd1" # Calculating the z score zscore = (116.452 - 125.92695057506994)/ 166.44208304193452 zscore # + colab={"base_uri": "https://localhost:8080/"} id="0qIt0_9Ea6P8" outputId="c1fd8f5d-7866-4b9c-8067-ce2e58970d80" # calculating the p value p_value = stats.norm.cdf(zscore) print(p_value) # + [markdown] id="rNezzLhDbAIr" # ### Conclusion # + colab={"base_uri": "https://localhost:8080/"} id="x8NBuckgbD1V" outputId="4a9e19e7-051e-4f9b-c08b-4188893c4e7d" if p_value < 0.05: print('Reject the null hypothesis,the study is significant') else: print('Fail to reject the null hypothesis')
Moringa_Data_Science_Core_W4_Independent_Project_2022_03_Rehema_Owino.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 # --- # # Incremental Principal component analysis # This code template is for Incremental Principal Component Analysis(IncrementalPCA) in python for dimensionality reduction technique. It is used to decompose a multivariate dataset into a set of successive orthogonal components that explain a maximum amount of the variance, keeping only the most significant singular vectors to project the data to a lower dimensional space. # ### Required Packages import warnings import itertools import numpy as np import pandas as pd import seaborn as se import matplotlib.pyplot as plt from mpl_toolkits import mplot3d from sklearn.decomposition import IncrementalPCA from sklearn.preprocessing import LabelEncoder warnings.filterwarnings('ignore') # ### Initialization # # Filepath of CSV file #filepath file_path= "" # List of features which are required for model training . #x_values features=[] # Target feature for prediction. #y_value target='' # ### Data Fetching # # Pandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools. # # We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. df=pd.read_csv(file_path) df.head() # ### Feature Selections # # It is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model. # # We will assign all the required input features to X and target/outcome to Y. X = df[features] Y = df[target] # ### Data Preprocessing # # Since the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes. # def NullClearner(df): if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])): df.fillna(df.mean(),inplace=True) return df elif(isinstance(df, pd.Series)): df.fillna(df.mode()[0],inplace=True) return df else:return df def EncodeX(df): return pd.get_dummies(df) x=X.columns.to_list() for i in x: X[i]=NullClearner(X[i]) X=EncodeX(X) Y=NullClearner(Y) X.head() # #### Correlation Map # # In order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. f,ax = plt.subplots(figsize=(18, 18)) matrix = np.triu(X.corr()) se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix) plt.show() # ### Choosing the number of components # # A vital part of using Incremental PCA in practice is the ability to estimate how many components are needed to describe the data. This can be determined by looking at the cumulative explained variance ratio as a function of the number of components. # # This curve quantifies how much of the total, dimensional variance is contained within the first N components. ipcaComponents = IncrementalPCA().fit(X) plt.plot(np.cumsum(ipcaComponents.explained_variance_ratio_)) plt.xlabel('number of components') plt.ylabel('cumulative explained variance'); # #### Scree plot # The scree plot helps you to determine the optimal number of components. The eigenvalue of each component in the initial solution is plotted. Generally, you want to extract the components on the steep slope. The components on the shallow slope contribute little to the solution. IPC_values = np.arange(ipcaComponents.n_components_) + 1 plt.plot(IPC_values, ipcaComponents.explained_variance_ratio_, 'ro-', linewidth=2) plt.title('Scree Plot') plt.xlabel('Principal Component') plt.ylabel('Proportion of Variance Explained') plt.show() # # Model # # Incremental principal components analysis (IPCA) allows for linear dimensionality reduction using Singular Value Decomposition of the data, keeping only the most significant singular vectors to project the data to a lower dimensional space. The input data is centered but not scaled for each feature before applying the SVD. # # Incremental principal component analysis (IPCA) is typically used as a replacement for principal component analysis (PCA) when the dataset to be decomposed is too large to fit in memory. # # #### Tunning parameters reference : # [API](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.IncrementalPCA.html) ipca = IncrementalPCA(n_components=5) ipcaX = pd.DataFrame(data = ipca.fit_transform(X)) # #### Output Dataframe finalDf = pd.concat([ipcaX, Y], axis = 1) finalDf.head() # #### Creator: <NAME> , Github: [Profile](https://github.com/SaharshLaud) #
Dimensionality Reduction/PCA/IncrementalPCA.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.13 64-bit (''tensorflow'': conda)' # language: python # name: python3 # --- import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize # + # stopwords are words that are common in many languages and are not useful for our purposes # - example_sentence = "This is an example showing off stop word filtration." stop_words = set(stopwords.words("english")) # predefined by NLTK. Can add your own, but it's a lot of work print(stop_words) words = word_tokenize(example_sentence) filtered_sentence = [] for w in words: if w not in stop_words: filtered_sentence.append(w) # filtered_sentence = [w for w in words if w not in stop_words] print(filtered_sentence)
nltk_stopwords.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: bayesian # language: python # name: bayesian # --- # + import pandas as pd import numpy as np import matplotlib.pyplot as plt import pymc3 as pm # %matplotlib inline # - df = pd.read_csv('datasets/mlb_2013-2016.csv') df.head() df.plot(kind='scatter', x='R', y='Winning %') import seaborn as sns # df.plot(kind='scatter', x='Season', y='Team Salary') sns.violinplot(x='Season', y='Team Salary', data=df) df.columns # + # Let's predict 'Winning %' from the rest of the columns. cols = list(df.columns) cols.remove('Season') cols.remove('Team') cols.remove('Team Salary (in millions)') cols.remove('League') cols.remove('Wins') cols.remove('Losses') banned = ['Winning %', 'Wins', 'Losses'] y_cols = ['Winning %'] feat_cols = list(set(cols) - set(y_cols) - set(banned)) # + from sklearn.ensemble import RandomForestRegressor rfr = RandomForestRegressor(n_estimators=50) rfr.fit(df[feat_cols], df[y_cols]) plt.plot(rfr.feature_importances_) # - important_cols = [] threshold = 0.03 impt_idxs = [i for i, k in enumerate(rfr.feature_importances_) if k > threshold] for i in impt_idxs: important_cols.append(feat_cols[i]) important_cols import theano.tensor as tt with pm.Model() as model: weights = pm.Normal('weights', mu=0, sd=100**2, shape=(len(important_cols),)) perc_losses = tt.dot(weights, df[important_cols].T) # weights = pm.Normal('weights', mu=0, sd=100**2, shape=(2,)) # perc_losses = weights[0] * df['Team Salary'] + weights[1] * df['R'] alpha = 1 beta = 1 / perc_losses sd = pm.HalfCauchy('sd', beta=100) # like = pm.Beta('likelihood', alpha=alpha, beta=beta, observed=df[y_cols]) like = pm.Normal('likelihood', mu=perc_losses, sd=sd, observed=df[y_cols]) # like = pm.Beta('likelihood', mu=perc_losses, sd=sd, observed=df[y_cols]) # like = pm.Bernoulli('likelihood', p=perc_losses, observed=df[y_cols]) with model: trace = pm.sample(50000, step=pm.Metropolis()) pm.traceplot(trace) burnin = 30000 pm.traceplot(trace[burnin:])
notebooks/frac-regression-mlb.ipynb
% -*- coding: utf-8 -*- % --- % jupyter: % jupytext: % text_representation: % extension: .m % format_name: light % format_version: '1.5' % jupytext_version: 1.14.4 % kernelspec: % display_name: MATLAB % language: matlab % name: imatlab % --- % # Demo: Prepare training dataset for VCD-Net % Generate patches to feed the VCD-Net model from provided 3D synthetic tubulin images. % % We implement a Matlab GUI for this task, which includes light field simulation and several other pre-processings. Check [this repo](https://github.com/feilab-hust/VCD-Net/tree/main/datapre) for downloading. % % Here we embed the Matlab scripts into Jupyter notebook for more convenient demonstration of our VCD-LFM pipeline. These following codes are using matlab kernel. Please select Matlab as the kernel in Jupyter Notebook if it's not. It requires [MATLAB Engine API for Python](https://www.mathworks.com/help/matlab/matlab_external/install-the-matlab-engine-for-python.html) and [imatlab](https://github.com/imatlab/imatlab) for Jupyter kernel. They should be installed on your computer if you intend to run this notebook locally, although we recommend using the Matlab GUI (/code/datapre/Code/Main.m) for simpler environment setup (where only Matlab is required on your computer). % ## Step1: Rectify and Augment HR data % In this demo, light field reconstruction has a pre-defined depth range, e.g. -30 to 30 microns. % % This step prepares the 3D stacks (high-resolution Ground Truth) for Forward Projection (light field simulation) by cropping each given stack into substack wth certain number of slice, in corresponding to the light field PSF (point spread function) you use. Here the dataset is optionally augmented by rotation and flip. Consult [this repo](https://github.com/feilab-hust/VCD-Net/tree/main/datapre) for parameter definitions. % + addpath('./Code/utils'); addpath('./Code'); %%%%%%%%%%%%%%%%%%%%%%%%% Substacks Parameters%%%%%%%%%%%%%%%%%%%%%%%%%%%%% substack_depth = 61; overlap = 0; z_sampling = 1; dx = 11; Nnum = 11; range_adjust = 0.9; rotation_step = 90; rectification_enable = 1; rotation_enable = 0; complement_stack = 1; flip_x = 0; flip_y = 0; flip_z = 0; save_path = './data/Substacks'; file_path = '../vcdnet/data/raw_data'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% file_name = struct2cell(dir(file_path)); file_name = file_name(1,3:end); if ~iscell(file_name) file_name = {file_name}; end crop_raw_stack(substack_depth, overlap, dx, Nnum, range_adjust, z_sampling, ... rotation_step, rectification_enable, rotation_enable, complement_stack, ... flip_x, flip_y, flip_z, file_path, file_name, save_path); disp('Rectify and Augment HR data ... done'); % - % ### Do some plottings to examine the outputs. % + imatlab_export_fig('print-png') show_some3d(save_path, 3, 1/0.34, 'hot', true, save_path, 'substacks_example.png'); % - % ## Step2: Forward Projection % Now we want to simulate the light field raw image in corresponding to each substack. So we can train the VCD-Net between them. % % This step transforms the substacks (generated in Step 1) into synthetic 2D light-field raw images. A PSF mat file (/code/datapre/PSFmatrix) is required for this step. We use softwares provided in Prevedel, R., <NAME>., <NAME>. et al. Simultaneous whole-animal 3D imaging of neuronal activity using light-field microscopy. Nat Methods 11, 727–730 (2014). https://doi.org/10.1038/nmeth.2964 to compute Light Field PSF. Consult [this repo](https://github.com/feilab-hust/VCD-Net/tree/main/datapre) for parameter definitions. % % **This step takes long time: ~ 20 min.** % + %%%%%%%%%%%%%%%%%%%%%%%%% Projection Parameters%%%%%%%%%%%%%%%%%%%%%%%%%%%%% brightness_adjust = 0.0039; poisson_noise = 0; gaussian_noise = 0; gaussian_sigma = 5e-5; gpu = 0; source_path = './data/Substacks'; save_path = './data/LFforward'; psf_name = 'PSFmatrix_M40NA0.8MLPitch150fml3500from-30to30zspacing1Nnum11lambda580n1.33.mat'; psf_path = './PSFmatrix/'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% forward_projection([psf_path, psf_name], poisson_noise, gaussian_noise, gaussian_sigma,... brightness_adjust, gpu, source_path, save_path); disp(['Forward Projection ... Done']); % - % ### Do some plottings to examine the outputs. show_some2d(save_path, 3, 'hot', true, save_path, 'light_field_example.png'); % ## Step3: Generate Patches % We now generate patch pairs with uniform size to feed the VCD-Net. Consult [this repo](https://github.com/feilab-hust/VCD-Net/tree/main/datapre) for parameter definitions. % + %%%%%%%%%%%%%%%%%%%%%%%%%%Crop Parameter%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% cropped_size = [176,176,substack_depth]; overlap = [0.5,0.5,0]; pixel_threshold = 1e6; var_threshold = 1e1; save_all = 0; source_path_3d = './data/Substacks'; save_path_3d = './data/TrainingPair/WF'; source_path_2d = './data/LFforward'; save_path_2d = './data/TrainingPair/LF'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% generate_patches(cropped_size, overlap, pixel_threshold, var_threshold, ... save_all, source_path_3d, save_path_3d, source_path_2d, save_path_2d) disp('Crop ...Done'); % - % ### Do some plottings to examine the outputs. show_some3d('./data/TrainingPair/WF', 3, 1/0.34, 'hot', true, './data/figs', 'patches_wf_example.png'); show_some2d('./data/TrainingPair/LF', 3, 'hot', true, './data/figs', 'patches_lf_example.png'); % ## What's next % Patches are stored in */results/TrainingPair*. Next we should navigate to the [notebook for VCD-Net training](../vcdnet/train_demo.ipynb) to train the model.
datapre/datapre.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Assignment no. 1 - Unit Testing # ! pip install pylint # + # %%writefile test_prime.py """Let the prime list be empty at first.""" primes = [] for possiblePrime in range(2,200): ISPRIME = True for num in range(2, possiblePrime): if possiblePrime % num == 0: ISPRIME = False if ISPRIME: primes.append(possiblePrime) print(primes) # - # ! pylint "test_prime.py" # + # %%writefile we_test_prime.py """This function tests whether a number is prime or not.""" def is_prime(number): """Return True if number is prime.""" for i in range(2, number): if number % i == 0: return False return True # - # ! pylint "we_test_prime.py" # + # %%writefile final_test_prime.py """This is final test whether a number is prime or not.""" import unittest from we_test_prime import is_prime class PrimesTestCase(unittest.TestCase): """Tests for `primes.py`.""" def test_is_five_prime(self): """Is five successfully determined to be prime?""" self.assertTrue(is_prime(5)) if __name__ == '__main__': unittest.main() # - # ! python final_test_prime.py # # Assignment no 2, Generator Program for Armstrong number print(list(range(1,1000))) def getclose_to_armnum_Gen(list): for num in range(1, 1000): sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: yield num else: yield num + 1 getclose_to_armnum_Gen(list) print(list(getclose_to_armnum_Gen(list)))
55329_Juhi_Kolhekar-_Day_9_Assignment_1_&_2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] _uuid="38c5c5b61a35d55e4b02ddfd8509c430aca423ba" # <a id='start'></a> # # Exploring # # In this Kernel I use part of the functions and methods introduced in previous notebooks; later I present the main graphs that can be done in Python. <br> # There are several libraries that can be used to create graphics in Python, the main ones we will use in this notebook are: <br> # - MatPlotLib: https://matplotlib.org/tutorials/index.html <br> # - Seaborn: https://seaborn.pydata.org/<br> # # <br> # Inside the notebook I will use different datasets; the first one we will use will be the Titanic dataset, on which it will be necessary to make some manipulations before creating the charts. <br> # The notebook is divided into the following parts: <br> # # 1) [Data preparation](#section1)<a href='#section1'></a> # # 2) [Plotting, Visualizing and Analyzing Data](#section2)<a href='#section2'></a>: <br> # - Bar chart # - Histrogram # - 2D Scatter Plot # - 3D Scatter Plot # - Higher Dimensionality Visualizations # 1) Parallel Coordinates # 2) Andrew's Curves # 3) Imshow # # + _uuid="8bf69ac4546e3375fa798c1232896bc96d313cc1" # I'm importing the libraries I'll need in the notebook import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib import math import statistics import seaborn as sns # To build the parallel coordinates from pandas.plotting import parallel_coordinates from pandas.plotting import andrews_curves from sklearn.datasets import load_iris from mpl_toolkits.mplot3d import Axes3D # for 3D charts from numpy import inf from scipy import stats from statistics import median matplotlib.pyplot.style.use('ggplot') # + [markdown] _uuid="d8f8c479fc32aa360677ec60ec8181eaca348656" # <a id='section1'></a> # ## 1) Data preparation # In this section amount the dataset of the Titanic's passengers, I make corrections in order to make the graphical analysis later. # + _kg_hide-input=true _uuid="2193bddc0a65b750786202511b1cd53f7472de69" # We import the training dataset of the titanic train_dataset = pd.read_csv("train.csv") train_dataset.head() # + _uuid="0f41fb8238421c05601d5b30ac0617fffd63d7cc" print ("Matrix row and column dimensions 'train_dataset':", train_dataset.shape) # + [markdown] _uuid="860f162603ce3fde8cbb6d573f2c6e2f9b799b3b" # We count the number of missing values for each attribute of the dataset # + _uuid="9e8a2e736256d4d29440db3a77c84094e5dc89e4" train_dataset.isnull().sum() # + _uuid="1bf184de73324a449595e1abbaf54b6f84add890" print("The", round(train_dataset.Age.isnull().sum()/891,2)*100, "% of records has a missing value in the 'Age'") print("The", round(train_dataset.Cabin.isnull().sum()/891,2)*100, "% of records has a missing value in the 'Cabin'") # + [markdown] _uuid="0b5bd1d44e3e8babe607a55fc830fcb3cfd2d07a" # Since the field 'Cabin' has mostly missing values and it is not possible to reconstruct them, I decide to delete the field from the dataset: # + _uuid="adb5f97636c2b91737de131940ef83a89177f56c" train_dataset = train_dataset.drop(labels=['Cabin'], axis=1) # + [markdown] _uuid="29848870963f2d9230cd406ca6616059f04e8344" # I capture passengers where the 'Age' and 'Embarked' camp is null and void. # - Passenger_AgeNull = train_dataset.loc[train_dataset.Age.isnull()] Passenger_EmbarkedNull = train_dataset.loc[train_dataset.Embarked.isnull()] # we can create the bar graph showing the number of people with the field 'Age' null, who have survived and not: <br> # + _uuid="6d7c8fbf74f00056126da0094cda3c7fcf447ccc" # Let's create the bar chart of people with zero age field # %matplotlib inline # I count the different types of the 'Survived' field, in this case the field can only assume a value of 1 (survived) or 0 (not survived). count = Passenger_AgeNull['Survived'].value_counts() fig = plt.figure(figsize=(5,5)) # define plot area ax = fig.gca() # define axis count.plot.bar() # - # Another way to make a bar chart can be as follows # In this case it is possible to assign names to categories 1, 0 plt.bar(['No survivors', 'Survivors'], count) # It is not possible to delete passengers whose age we do not know because they can help to distinguish between surviving and non surviving passengers; to better understand possible patterns I create histograms in the same area (**FacetGrid**), clustering people's age according to age and gender. <br> # For this chart I use the Seaborn library imported at the beginning of the workbook (https://seaborn.pydata.org/examples/faceted_histogram.html). # + _uuid="9652f4add5478f125c20751636842dde8ead1a80" # Draw a nested histogram to show Age for class and sex sns.set(style="whitegrid") g = sns.FacetGrid(train_dataset, row="Pclass", col="Sex") g.map(plt.hist, "Age", bins=20) # + [markdown] _uuid="4c46b78f4cf05bc79907c8048419253e4c5a574f" # I replace the missing values of the age field by entering the median age of the passengers by gender, class they were travelling in and based on the value assumed by the 'Survived' field. # + _uuid="31a0325e840d8577f17247cfe677fdc3c6bfb537" train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "female") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "female") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "female") & (train_dataset.Survived == 1) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "female") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "female") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "female") & (train_dataset.Survived == 1) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "female") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "female") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "female") & (train_dataset.Survived == 1) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "female") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "female") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "female") & (train_dataset.Survived == 0) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "female") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "female") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "female") & (train_dataset.Survived == 0) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "female") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "female") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "female") & (train_dataset.Survived == 0) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "male") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "male") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "male") & (train_dataset.Survived == 1) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "male") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "male") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "male") & (train_dataset.Survived == 1) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "male") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "male") & (train_dataset.Survived == 1) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "male") & (train_dataset.Survived == 1) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "male") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "male") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 1) & (train_dataset.Sex == "male") & (train_dataset.Survived == 0) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "male") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "male") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 2) & (train_dataset.Sex == "male") & (train_dataset.Survived == 0) ]["Age"].median()) train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "male") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ] = train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "male") & (train_dataset.Survived == 0) & (train_dataset.Age.isnull()), "Age" ].fillna(train_dataset.loc[ (train_dataset.Pclass == 3) & (train_dataset.Sex == "male") & (train_dataset.Survived == 0) ]["Age"].median()) # - # TODO: Can you create a function that does this together? # At this point we just need to fill in the missing values for the 'Embarked' field # + _uuid="f644ea052b36e8072b2f6d9f6c4749d4353ae8d8" train_dataset.isnull().sum() # + _uuid="22e391806eaa3f31a538648cf5884f7894a3e846" Passenger_EmbarkedNull # + [markdown] _uuid="faec5d40fd721f94b6c83c73d534ab3265305107" # To assign the value to the 'Embarked' field we perform further analysis on the dataset # + _uuid="40c66f08332fc4336689d5bd9b75f1608216943c" # We count the people who boarded in the three different locations (S - Southampton, C - Cherbourg, Q - Queenstown) # df = train_dataset # Grouped boxplot sns.set(font_scale = 1.50) sns.set_style("ticks") fig, ax = plt.subplots(figsize=(7, 7)) graph = sns.countplot(y="Embarked", data=df, ax = ax, color="b") #graph.set_xticklabels(graph.get_xticklabels(), rotation='vertical') graph.set_title('Bar Chart of Embarked') # + [markdown] _uuid="e0b388cde6d0a7755fcb162bd52794a790bfa78b" # It seems that most people have embarked from S (Southampton), but where did the first class women mainly embarked from (characteristic of the women we have noticed have the value of the 'Embarked' camp zero)? # + _uuid="4174b0cffee95ff2aa261296fb090a4463c9c519" # Draw a nested barplot to show embarked for class and sex sns.set(style="whitegrid") g = sns.catplot(x="Embarked", hue="Pclass", col="Sex", kind="count", data=train_dataset, palette="muted") # + [markdown] _uuid="f07f0e921f819940a7af8c32d6919a318b001e39" # Looks like most of the women who were in first class left Southampton and Cherbourg. # + _uuid="0925962fc2adfeee647c6181a31d3f6049137e59" FirstClass_Women_S = train_dataset.loc[ (train_dataset.Sex == "female") & (train_dataset.Embarked == "S") & (train_dataset.Pclass == 1), :] print("% of surviving women who stayed in first class and left Southampton:", round((FirstClass_Women_S['Survived'].sum()/FirstClass_Women_S['Survived'].count())*100,2)) # + _uuid="70f6f5e493c28d1c4e55bf9a79d8b3bbc4a3278b" FirstClass_Women_C = train_dataset.loc[ (train_dataset.Sex == "female") & (train_dataset.Embarked == "C") & (train_dataset.Pclass == 1), :] print("% of surviving women who stayed in first class and left Cherbourg.:", round((FirstClass_Women_C['Survived'].sum()/FirstClass_Women_C['Survived'].count())*100,2)) # + [markdown] _uuid="9286855ae781e5ec2bd639479f0ceb769fe8ec7c" # In the light of the above analysis, I assign the 'Embarked' field of the two zero records the value of C, as it represents the point from which the largest number of women who survived and were in first class started. # + _uuid="0aa831ac8fa3896a03850cb960e5007465c17106" # Fill na in Embarked with "C" train_dataset.Embarked = train_dataset.Embarked.fillna('C') # + _uuid="02d87de3f86815f5ae25ac39cadea55b7ca7f33b" train_dataset.isnull().sum() # + [markdown] _uuid="1da275b10c25e201ac0631f721a3d9ea4b918b50" # At this point there are no more zero values. # + [markdown] _uuid="e1271c97fc1823e791e20caa5657f38ec01f128b" # <a id='section2'></a> # ## 2) Plotting, Visualizing and Analyzing Data # - # #### - Bar graph # This type of graph is used especially when we want to count how many times there are different characters represented by the same field of a dataset, for example as we did above, we used the bar graph to count how many people who had the zero age field survived or not on the Titanic. <br> # With the function *value_counts()* we first counted how many times we had the same character of a field (1/0), then we identified the measurements of the graph area, defined the axes with the function (**.gca()**) and then indicated the matrix on which we wanted to "plot" the bar graph (**count.plot.bar()**). # + # Let's create the bar chart of people with zero age field # # I count the different types of the 'Survived' field, in this case the field can only assume a value of 1 (survived) or 0 (not survived). count = Passenger_AgeNull['Survived'].value_counts() fig = plt.figure(figsize=(5,5)) # define plot area ax = fig.gca() # define axis count.plot.bar() # - # The Seaborn library allows to make bar graphs with more details, such as the following graph in which for each class in which the passengers of the Titanic, divided by sex, the probability of survival is identified, thanks to the field "Survived" present in the dataset. # [Link to Seaborn's website](https://seaborn.pydata.org/examples/grouped_barplot.html) # + _uuid="fdaf484f793d2623446925d4e262427f9b1d42ce" g = sns.catplot(x="Pclass", y="Survived", hue="Sex", data=train_dataset, kind = "bar") g.set_ylabels("Survival Probability") g.fig.suptitle("Survival Probability by Sex and Passengers Class") # - # #### - Histogram # Histograms can help you understand the distribution of a given field of the data set. <br> # Usually, histograms are more useful when used with categorical data, in order to investigate how classes in the field are distributed. In fact, if we want to use fields of continuous numeric type we must first create classes that group each value or discretize the continuous values by creating ranges (or classes) of values. To do this, the values of a field are usually divided into a series of consecutive intervals of equal length that do not overlap. These intervals will become the "categories".<br> # To create a histogram with MatPlotLib through Pandas, you need to use the **.plot.hist()** method, which can be used with either a *series* or a *dataframe*. train_dataset.Age.plot.hist() # If you want to consider the relative frequency rather than the absolute frequency, just use the parameter *density=True*. train_dataset.Age.plot.hist(density=True) # There are many parameters that can be assigned to the .plot.hist() function; many can be found at the following [online documentation](https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist). <br> # Knowing how a field is distributed is very useful, because some machine learning models expect the data provided to be distributed in a normal way. <br> # With seaborn there are many ways to create a histogram (*distplot*), at the following [link](https://seaborn.pydata.org/examples/distplot_options.html) you can see some interesting examples. # + _uuid="fc2ff1bb8cd9da561e94005b67e0f7f96459c92b" # Distribution plot of Fares g = sns.distplot(train_dataset["Fare"], bins = 20, kde=False) g.set_title("Distribution plot of Fares") # - # #### - 2D Scatter Plot # Scatter plots are used to identify any correlation between two fields in a dataset. In this case, unlike histograms, both fields shown on the axes (x and y) must be numeric. It is not necessary that they are of a continuous numeric type but it is sufficient that they are of a discrete type that can be ordered since each record will be identified in a point whose coordinates coincide with the values of the two fields used. <br> # From a scatter plot it is possible to show a negative or positive correlation or no correlation at all. <br> # The correlation can be evaluated by observing the trend of the bisector intersecting the axes of the Cartesian plane.<br> # # Positive or negative correlations may also show a linear or non-linear relationship. If you can draw a straight line through the scatter plot and most points stick to it, then you can say with some degree of accuracy that there is a linear relationship between the fields used to create the scatter plot. <br> # Similarly, if it is possible to draw a curve between the points, it is possible to say that there may be a non-linear relationship between the fields. <br> # If neither a curve nor a line seems to suit the overall shape of the plotted points, then it is likely that there is neither a correlation nor a relationship between the elements, or at least there is currently insufficient information to determine the contrary. <br> # # To plot a scatter plot, simply use the **.plot.scatter()** function; the latter can only be used with a *dataframe* and not with a *series*, as at least two fields are required. train_dataset.plot.scatter(x='Age', y='Fare') # From the graph above, there seems to be no relationship between the Age field and Titanic's Fare dataset. # #### - 3D Scatter Plot # 3D scatter plots can be very useful when we want to investigate whether there are linear or non-linear relationships between 3 variables. # + fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlabel('Age') ax.set_ylabel('Fare') ax.set_zlabel('Survived') ax.scatter(train_dataset.Age, train_dataset.Fare, train_dataset.Survived) plt.suptitle('Age x Fare x Survived') # - # #### - Higher Dimensionality Visualizations # In reality datasets often have dozens of fields, if not more; it is therefore insufficient to use 3D scatter plots, or not very intuitive in order to highlight any relationship between the fields. To face these problems it is possible to use the so-called "*Higher Dimensionality Visualizations*", that is graphs that try to represent the relationships between three or more variables at the same time. # **[1) Parallel Coordinates](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.plotting.parallel_coordinates.html)** <br> # The *parallel coordinates* are similar to a scatter plot, but unlike the scatters seen before, there are more vertical and parallel axes in the parallel coordinates. <br> # Each record is represented with a segment that passes through the vertical axes at the points corresponding to the value that characterizes each analyzed field. In doing so, the resulting segment completely describes a record of a dataset, identifying the value of each field observed. <br> # Parallel coordinates can be very useful when we want to represent values of more than three dimensions; however, it is not recommended to use this type of graph for more than 10 dimensions, as it may be difficult to orient between the different vertical axes. <br> # Through the parallel coordinates it is possible to verify which are the records that have a similar behavior on different fields, in this case in fact the various segments of the graph tend to group together. <br> # To use this type of chart with Pandas and MatPlotLib, you need to specify a feature (which can also be non-numeric) for which to group the various fields of the dataset. In this way, each distinct value of that characteristic is assigned a unique color when segments are plotted. <br> # In addition, to make sure that the graph is readable, it is important that the fields that are represented by the paralllel coordinates have a similar range of values, vice versa it is necessary to standardize the values of the fields before representing them on the parallel coordinates. # Below I present an example of parallel coordinates using the dataset of the plant "iris", within which there are the different measures of length and width of the sepal and petal of the different categories of plant *iris* that exist. # Let's load the default Sklearn dataset where there are different parameters (date, features_names, target_names, DESCR) data = load_iris() data # I capture in the dataframe df the data concerning the length and width of the sepals and petals df = pd.DataFrame(data.data, columns=data.feature_names) df.head() # Target names of the different Iris plant species data.target_names # Column indicating with 0, 1, 2 the type of plant for each dataset record data.target # I add the column 'target_names' to the dataset df df['target_names'] = [data.target_names[i] for i in data.target] df.head() plt.figure() parallel_coordinates(df, 'target_names', colormap='Blues') # In this graph we can see how, among the various species of the Iris plant some characteristics have the same behaviour (range of values) as for example the parameter "*sepal width (cm)*". Moreover it is possible to notice how the versicolor and virginica species tend to have *petal lenght (cm)* values closer to each other than those of the silky species. # **[2) Andrew's Curve](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.plotting.andrews_curves.html)** <br> # The Andrews curve, helps to visualize multivariate data, tracing each observation of the dataset as a curve. <br> # For each record, the values of the fields in the dataset act as coefficients of the curve representing the record itself; therefore observations with similar characteristics tend to cluster closer to each other. <br> # For this reason, Andrews' curves can be useful in outlier detection. <br> # As with parallel coordinates graphs, each element drawn must be numeric. <br> # We use the same dataset used for the parallel coordinates but this time we depict an Andrew's Curve: plt.figure() andrews_curves(df, 'target_names', colormap='Blues') # **[3) Imshow](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html)** <br> # The **imshow** command generates an image based on the normalized values stored in a matrix.<br>. # The properties of the generated image will depend on the size and content of the input array: # # - An array size [X, Y] will produce a grayscale image. # - An array size [X, Y, 3] will produce a color image, where: 1 channel will be for red, 1 for green and 1 for blue; # - A size matrix [X, Y, 4] produces a color image as before, with an additional channel for alpha (the color gradient) # # The *.imshow()* method is mainly used when calculating correlations between several variables. Correlation values can vary from -1 to 1, where 1 means that two variables are perfectly correlated positively and have identical slopes for all values; while -1 means that variables are perfectly correlated negatively, and have a negative slope, but still linear. Values closer to 0 mean that there is little or no linear relationship between the two variables. <br> # The correlation matrix is symmetrical because the correlation between two elements X and Y is, of course, identical to that of the elements Y and X. Moreover, the scale is invariant because even if one element is measured in inches and the other in centimeters, the correlation is a measure purified by the unit of measurement of the variables that are taken into account. # The correlation matrix, as well as the covariance matrix, is useful to verify how the variance of a certain characteristic (dataset variable/field) is explained by the variance of another characteristic, and to verify how much new information each characteristic provides. <br> # We provide a practical example, calculating the correlation matrix from a series of random numbers: df_2 = df.loc[:, ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']] df_2.head() df_2.corr() # Looking at the data from the matrix above can be a bit tedious, but you can get around this problem by viewing the correlation matrix by plotting a graph with the .imshow() method: plt.imshow(df_2.corr(), cmap = plt.cm.Blues, interpolation='nearest') plt.colorbar() tick_marks = [i for i in range(len(df_2.columns))] plt.xticks(tick_marks, df_2.columns, rotation='vertical') plt.yticks(tick_marks, df_2.columns) # **Useful Link:** # - [The Art of Effective Visualization of Multi-dimensional Data](https://towardsdatascience.com/the-art-of-effective-visualization-of-multi-dimensional-data-6c7202990c57) # - [Choosing the Best Graph Type](http://sphweb.bumc.bu.edu/otlt/MPH-Modules/BS/DataPresentation/DataPresentation7.html) # [Click here to come back to index](#start)<a id='start'></a>
Italiano/2_data_preprocessing/03_Exploring/Exploring.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import torch import time import copy import os import torchvision from torchvision import datasets, models, transforms import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from torch.utils.data.sampler import SubsetRandomSampler data_dir = r"/home/rashi/Codes/glasses-master/glasses/data" device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # + batch_size = 16 validation_split = 0.2 shuffle_dataset = True random_seed = 21 data_transforms = { 'train': transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) } image_dataset = datasets.ImageFolder(data_dir, transform=data_transforms['train']) print(len(image_dataset)) # - # Dataset was made using this handy function from the second lesson of Fastai Tutorial # # ```javascript # urls = Array.from(document.querySelectorAll('.rg_di .rg_meta')).map(el=>JSON.parse(el.textContent).ou); # window.open('data:text/csv;charset=utf-8,' + escape(urls.join('\n'))); # ``` # + dataset_size = len(image_dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) np.random.seed(random_seed) np.random.shuffle(indices) train_idx, valid_idx = indices[split:], indices[:split] train_sampler = SubsetRandomSampler(train_idx) valid_sampler = SubsetRandomSampler(valid_idx) train_loader = torch.utils.data.DataLoader( image_dataset, batch_size=batch_size, sampler=train_sampler) validation_loader = torch.utils.data.DataLoader( image_dataset, batch_size=batch_size, sampler=valid_sampler) dataloaders = {'train': train_loader, 'val': validation_loader} datasets_sizes = { 'train': len(train_loader) * batch_size, 'val': len(validation_loader) * batch_size } print(datasets_sizes) # + # functions to show an image def imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.axis('off') plt.show() # get some random training images dataiter = iter(train_loader) images, labels = dataiter.next() # show images imshow(torchvision.utils.make_grid(images[:4])) # + resnet50 = models.resnet50(pretrained=True) resnet50 = resnet50.to(device) for param in resnet50.parameters(): param.requires_grad = False resnet50.fc = nn.Sequential( nn.Linear(2048, 256), nn.ReLU(), nn.Linear(256, 2) ) resnet50 = resnet50.to(device) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(resnet50.parameters(), lr=0.001) # - def train_model(model, criterion, optimiser, num_epochs=10): start_time = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_accuracy = 0.0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs -1)) print('-' * 10) for phase in ['train', 'val']: if phase == 'train': model.train() #training model else: model.eval() #evaluating model running_loss = 0.0 running_corrects = 0 for inputs, labels in dataloaders[phase]: inputs = inputs.to(device) labels = labels.to(device) optimiser.zero_grad() with torch.set_grad_enabled(phase == "train"): outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) if phase == 'train': loss.backward() optimiser.step() running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) epoch_loss = running_loss / datasets_sizes[phase] epoch_acc = running_corrects.double() / datasets_sizes[phase] print('{} Loss: {:.4f} Accuracy: {:.4f}'.format( phase, epoch_loss, epoch_acc)) if phase == "val" and epoch_acc > best_accuracy: best_accuracy = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) print() time_consumed = time.time() - start_time print('Training complete in {:.0f}m {:.0f}s'.format( time_consumed // 60, time_consumed % 60)) print('Best val Acc: {:4f}'.format(best_accuracy)) # load best model weights model.load_state_dict(best_model_wts) return model # %time model_ft = train_model(resnet50, criterion, optimizer, num_epochs=20) # + classes = ['glasses', 'no-glasses'] dataiter = iter(validation_loader) images, labels = dataiter.next() imshow(torchvision.utils.make_grid(images[:4])) print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4))) # + output = model_ft(images) _, predicted = torch.max(output, 1) print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4))) # - torch.save(model_ft, r"/home/rashi/Codes/glasses-master/glasses/model.pth") # + # dummy_input = torch.randn(16, 3, 224, 224) # input_names = [ "actual_input_1" ] + [ "learned_%d" % i for i in range(16) ] # output_names = [ "output1" ] # torch.onnx.export(model_ft, dummy_input, "glasses_model", verbose=True, input_names=input_names, output_names=output_names)
glasses.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda root] # language: python # name: conda-root-py # --- # Copyright (c) Microsoft Corporation. All rights reserved. # # Licensed under the MIT License. # # Creating and Updating a Docker Image before Deployment as a Webservice # # This notebook demonstrates how to make changes to an existing docker image, before deploying it as a webservice. # # Knowing how to do this can be helpful, for example if you need to debug the execution script of a webservice you're developing, and debugging it involves several iterations of code changes. In this case it is not an option to deploy your application as a webservice at every iteration, because the time it takes to deploy your service will significantly slow you down. In some cases, it may be easier to simply run the execution script on the command line, but this not an option if your script accumulates data across individual calls. # # **Note:** This code was tested on a Data Science Virtual Machine ([DSVM](https://azure.microsoft.com/en-us/services/virtual-machines/data-science-virtual-machines/)), running Ubuntu Linux 16.04 (Xenial). # ## Configure your Azure Workspace # # We need to set up your workspace, and make sure we have access to it from here. # # This requires that you have downloaded the ***config.json*** configuration file for your azure workspace. # # Follow this [Quickstart](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-get-started) to set up your workspace and to download the config.json file, which contains information about the workspace you just created. Save the file in the same directory as this notebook. # + # %matplotlib inline from azureml.core import Workspace ws = Workspace.from_config() # - # Let's make sure that you have the correction version of the Azure ML SDK installed on your workstation or VM. If you don't have the write version, please follow these [Installation Instructions](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-create-workspace-with-python#install-the-sdk). # + tags=["check version"] import azureml # display the core SDK version number print("Azure ML SDK Version: ", azureml.core.VERSION) if azureml.core.VERSION == '0.1.59': print("Looks like you have the correct version. We are good to go.") else: print("There is a version mismatch, this notebook may not work as expected!") # - # ## Create a Docker image using the Azure ML SDK # ### Create a template execution script for your application # # We are going to start with just an execution script for your webservice that ingests one value at a time and returns a running average. # + # %%writefile score.py import json # we use json in order to interact with the anomaly detection service via a RESTful API # The init function is only run once, when the webservice (or Docker container) is started def init(): global running_avg, curr_n running_avg = 0.0 curr_n = 0 pass # the run function is run everytime we interact with the service def run(raw_data): """ Calculates rolling average according to Welford's online algorithm. https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online :param raw_data: raw_data should be a json query containing a dictionary with the key 'value' :return: runnin_avg (float, json response) """ global running_avg, curr_n value = json.loads(raw_data)['value'] n_arg = 5 # we calculate the average over the last "n" measures curr_n += 1 n = min(curr_n, n_arg) # in case we don't have "n" measures yet running_avg += (value - running_avg) / n return json.dumps(running_avg) # - # ### Create environment file for your Conda environment # # Next, create an environment file (environment.yml) that specifies all the python dependencies of your script. This file is used to ensure that all of those dependencies are installed in the Docker image. Let's assume your Webservice will require ``azureml-sdk``, ``scikit-learn``, and ``pynacl``. # + tags=["set conda dependencies"] from azureml.core.conda_dependencies import CondaDependencies myenv = CondaDependencies() myenv.add_conda_package("scikit-learn") myenv.add_pip_package("pynacl==1.2.1") with open("environment.yml","w") as f: f.write(myenv.serialize_to_string()) # - # Review the content of the `environment.yml` file. with open("environment.yml","r") as f: print(f.read()) # ### Create the initial Docker image # # We use the ``environment.yml`` and ``score.py`` files from above, to create an initial Docker image. # + # %%time from azureml.core.image import ContainerImage # configure the image image_config = ContainerImage.image_configuration(execution_script = "score.py", runtime = "python", conda_file = "environment.yml") # create the docker image. this should take less than 5 minutes image = ContainerImage.create(name = "my-docker-image", image_config = image_config, models = [], workspace = ws) # we wait until the image has been created image.wait_for_creation(show_output=True) # let's save the image location imageLocation = image.serialize()['imageLocation'] # - # ## Test the application by running the Docker container locally # # ### Download the created Docker image from the Azure Container Registry ([ACR](https://azure.microsoft.com/en-us/services/container-registry/)) # # Here we use some [cell magic](https://ipython.readthedocs.io/en/stable/interactive/magics.html) to exchange variables between python and bash. # + magic_args="-s \"$imageLocation\" " language="bash" # # # get the location of the docker image in ACR # imageLocation=$1 # # # extract the address of the repository within ACR # repository=$(echo $imageLocation | cut -f 1 -d ".") # # echo "Attempting to login to repository $repository" # az acr login --name $repository # echo # # echo "Trying to pull image $imageLocation" # docker pull $imageLocation # - # ### Start the docker container # # We use standard Docker commands to start the container locally. # + magic_args="-s \"$imageLocation\"" language="bash" # # # extract image name and tag from imageLocation # image_name=$(echo $1 | cut -f 1 -d ":") # tag=$(echo $1 | cut -f 2 -d ":") # echo "Image name: $image_name, tag: $tag" # # # extract image ID from list of downloaded docker images # image_id=$(docker images $image_name:$tag --format "{{.ID}}")) # echo "Image ID: $image_id" # # # we forward TCP port 5001 of the docker container to local port 8080 for testing # echo "Starting docker container" # docker run -d -p 8080:5001 $image_id # # sleep 1 # - # ### Test the docker container # # We test the docker container, by sending some data to it to see how it responds - just as we would with a Webservice. # + import json import requests import numpy as np import matplotlib.pyplot as plt values = np.random.normal(0,1,100) values = np.cumsum(values) running_avgs = [] for value in values: raw_data = {"value": value} r = requests.post('http://localhost:8080/score', json=raw_data) result = json.loads(r.json()) running_avgs.append(result) plt.plot(values) plt.plot(running_avgs) # - # ## Modifying the container # # Let's make a change to the the execution script: We want to enable an additional input argument to ``score.py`` to set how many previous values to consider in the running average. # + # %%writefile score.py import json # we use json in order to interact with the anomaly detection service via a RESTful API # The init function is only run once, when the webservice (or Docker container) is started def init(): global running_avg, curr_n running_avg = 0.0 curr_n = 0 pass # the run function is run everytime we interact with the service def run(raw_data): """ Calculates rolling average according to Welford's online algorithm. https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online :param raw_data: raw_data should be a json query containing a dictionary with the key 'value' :return: runnin_avg (float, json response) """ global running_avg, curr_n value = json.loads(raw_data)['value'] n_arg = json.loads(raw_data)['n'] # we calculate the average over the last "n" measures curr_n += 1 n = min(curr_n, n_arg) # in case we don't have "n" measures yet running_avg += (value - running_avg) / n return json.dumps(running_avg) # - # ### Update container image # # Copy the changed ``score.py`` into the running docker container and commit the changes to the container image. # + magic_args="-s $imageLocation" language="bash" # # image_location=$1 # # # extract image name and tag from imageLocation # image_name=$(echo $image_location | cut -f 1 -d ":") # tag=$(echo $image_location | cut -f 2 -d ":") # # echo "Image name: $image_name, tag: $tag" # # # extract image id # image_id=$(docker images | grep $image_name | grep " ${tag} " | cut -b 74-85) # # echo "Image ID: $image_id" # # # extract container ID # container_id=$(docker ps | tail -n1 | cut -f 1 -d " ") # echo "Container ID: $container_id" # # # copy modified scoring script again # docker cp score.py $container_id:/var/azureml-app/ # # sleep 1 # # commit changes made in the container to the local copy of the image # docker commit $container_id $image_location # # # let's wait for two seconds here # sleep 1 # # # stop the container # docker restart $container_id # # # - # ### Test the container # # **Note**, you probably have to run the above cell twice for the change to score.py to ahve an effect. # + import json import requests import numpy as np import matplotlib.pyplot as plt n = 2 # set the number of values going into the running avg values = np.random.normal(0,1,100) values = np.cumsum(values) running_avgs = [] for value in values: raw_data = {"value": value, "n": n} r = requests.post('http://localhost:8080/score', json=raw_data) result = json.loads(r.json()) running_avgs.append(result) plt.plot(values) plt.plot(running_avgs) # - # ### Push the updated container to ACR # # **First**, test your Docker container again (run the json query above), to ensure that the changes are having the expected effect. # # **Then** you can push the image into ACR, so that it can be retrieved by the Azure ML SDK when you want to deploy your Webservice. # + magic_args="-s \"$imageLocation\"" language="bash" # # image_location=$1 # # # extract container ID # container_id=$(docker ps | tail -n1 | cut -f 1 -d " ") # echo "Container ID: $container_id" # # sleep 1 # # commit changes made in the container to the local copy of the image # docker commit $container_id $image_location # # docker push $image_location # - # Let's try to deploy the container to ACI, just to make sure everything behaves as expected. # + # %%time from azureml.core.webservice import Webservice from azureml.core.image import ContainerImage from azureml.core.webservice import AciWebservice # create configuration for ACI aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1, tags={"data": "some data", "method" : "machine learning"}, description="Does machine learning on some data") # pull the image image = ContainerImage(ws, name='my-docker-image', tags='1') # deploy webservice service_name = 'my-web-service' service = Webservice.deploy_from_image(deployment_config = aciconfig, image = image, name = service_name, workspace = ws) service.wait_for_deployment(show_output = True) print(service.state) # + import json import requests import numpy as np import matplotlib.pyplot as plt n = 2 # set the number of values going into the running avg values = np.random.normal(0,1,100) values = np.cumsum(values) running_avgs = [] for value in values: raw_data = json.dumps({"value": value, "n": n}) raw_data = bytes(raw_data, encoding = 'utf8') # predict using the deployed model result = json.loads(service.run(input_data=raw_data)) running_avgs.append(result) plt.plot(values) plt.plot(running_avgs) # - # ## Clean up resources # # To keep the resource group and workspace for other tutorials and exploration, you can delete only the ACI deployment using this API call: service.delete() # # The end # Copyright (c) Microsoft Corporation. All rights reserved. # # Licensed under the MIT License.
lab02.4_PM_Debugging/PM_developing_scoring_script.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd i = [i for i in range(2000)] df = pd.DataFrame(i) df.rename(columns={0:'id_user'}, inplace=True) df.sample(5) df.to_csv(index=False, path_or_buf = '../data_base/csv/employers.csv')
data_notebooks/employers.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 # --- # # Time Series Forecasting Demonstration (Stock Market Data)--LSTM -- Data Preparation/Exploratory -- Multiple Input->Output- One Step-Ahead (Sequence to One) # # **--------------------------------------------------------------------------------------------------------------------------** # **--------------------------------------------------------------------------------------------------------------------------** # **--------------------------------------------------------------------------------------------------------------------------** # **---------------------------------------------------** # # # **STRUCTURE** # # *In this work, the use of the LSTM Deep Learning model for 'sequence to one' time series forecasting (stock market dataset) is demonstrated. **Part A** of this project is focused on data preparation/manipulation of the imported dataset features (open,close,high,low and volume stock market values of American Airlines Group Inc.) to apply all necessary data preprocessing/cleaning methods by use of numpy and pandas (i.e. creation of datetime object and use as index, feature engineering to extract datetime categories,mapping,etc.). Moreover, an exploratory analysis is provided in this section to highlight key aspects of the examined time series ('AAL Close Price') with respect to its past observations, so as to get meaningful insights in terms of its distribution,its correlations with the other dataset features and its behavior when grouped at different time periods.* # # *In the second part of this work (**Part B**), the fitting and forecasting capabilities of the LSTM model are investigated. In particular, the LSTM model is trained to forecast the AAL Close Average Weekly price (prediction horizon of 52 Weeks) by creating a time series input sequence of 12 time steps and an output sequence consisting of the AAL Close Price at one-step ahead (X [index 0 to 11], y [index 12]).* # # *In terms of the forecasted outputs, a 'for loop' is created that takes each X test sequence, updates the time series batch and makes the prediction. For the evaluation of the LSTM model training and forecasting performance, plots of the fitted and predicted values against the actual(training and target) AAL Close Average Weekly prices are presented (Performance Metric --> Root Mean Squared Error). In addition, the relative training error (percentage) distribution plot is provided.* # # # # **The Dataset (.csv file format) for this project has been obtained from Kaggle:** # # "*S&P 500 stock data*" -- File: "all_stocks_5yr.csv" -- Source:https://www.kaggle.com/camnugent/sandp500 # # # # Part A # # ***Data Prepararation for Machine Learning - Exploratory Analysis*** # Importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import mean_squared_error import warnings warnings.filterwarnings('ignore') # Importing the S&P 500-Stock Market Dataset dataset=pd.read_csv('all_stocks_5yr.csv',parse_dates=True) # First 5 Entries dataset.head() # Dataset Information regarding a) the data type of each feature and b) total values per feature. Dataset comprises # two 'object',four 'float' and one 'int' data type feature dataset.info() # Creating a copy of the original dataset data=dataset.copy() # This demonstration is focused on the American Airlines Group Inc.(NASDAQ:'AAL') historical stock market data data=data[data['Name']=='AAL'] data.head() # 'Date' column is converted from 'object' data type to 'datetime' data['date'] = pd.to_datetime(data['date']) # Feature Engineering is applied to extract the Days of Week,Months and Years from the 'Date' column data['Week_Day'] = data['date'].apply(lambda date:date.dayofweek) data['Month'] = data['date'].apply(lambda date:date.month) data['Year'] = data['date'].apply(lambda date:date.year) data.head(2) # Mapping to rename the entries of the 'Week_Day' column data['Week_Day'] = data['Week_Day'].map({0:'Monday',1:'Tuesday',2:'Wednesday',3:'Thursday',4:'Friday'}) data.head(2) # + # Boxplots of AAL Open, High, Low, Close & Volume values grouped by Year. As expected, the stock market values of AAL open, # High, Low and Close values are almost identical, due to the strong correlation between each other. With respect to the # AAL Volume, the incease in the AAL volume from 2013 to 2014 was followed by a relative small value decrease over the # next two years(2015 and 2016) and resulted in a significant value decrease in 2017 and 2018. Based on the last boxplot, # the largest median value of AAL Volume is observed on Fridays, whereas for most years the smallest median AAL Volume # value is observed on Mondays. # Note: the AAL stock market Volume boxplot presents all trading volume values <= 0.4E8 to increase the visibility of # the plot by excluding values that are considered outliers (observations that lie a significantly large distance from # the other dataset values --- in this case, the very high trading volume values) fig,axs=plt.subplots(2,2,figsize=(12,8)) plt.rcParams["font.weight"] = "bold" plt.rcParams['font.size']=13 sns.boxplot(x='Year',data=data,y='open',hue='Week_Day',palette='inferno',ax=axs[0,0]) sns.boxplot(x='Year',data=data,y='high',hue='Week_Day',palette='inferno',ax=axs[0,1]) sns.boxplot(x='Year',data=data,y='low',hue='Week_Day',palette='inferno',ax=axs[1,0]) sns.boxplot(x='Year',data=data,y='close',hue='Week_Day',palette='inferno',ax=axs[1,1]) for ax in axs.flat: ax.legend(loc='best',fontsize=8) ax.set_xlabel('Year') ax.figure.tight_layout(pad=4) fig.suptitle("AAL Open, High, Low, Close & Volume Market Values grouped by Year", fontweight='bold',fontsize=18) plt.figure(figsize=(12,6)) sns.boxplot(x='Year',y='volume',hue='Week_Day',palette='inferno',data=data) plt.ylim(0,0.4E8); # + # Boxplots of AAL Open, High, Low, Close & Volume values grouped by Month. As before the stock market values of AAL open, # High, Low and Close values are almost identical. Regarding the AAL market Volume values, January (Month 1) has been the # month with the largest trading volume (boxplot median values) and August (Month 8) the month with the smallest median # trading Volume values for with respect to each Day of Week. fig,axs=plt.subplots(2,2,figsize=(12,8)) plt.rcParams["font.weight"] = "bold" plt.rcParams['font.size']=13 sns.boxplot(x='Month',data=data,y='open',palette='magma',ax=axs[0,0]) sns.boxplot(x='Month',data=data,y='high',palette='magma',ax=axs[0,1]) sns.boxplot(x='Month',data=data,y='low',palette='magma',ax=axs[1,0]) sns.boxplot(x='Month',data=data,y='close',palette='magma',ax=axs[1,1]) for ax in axs.flat: ax.set_xlabel('Month') ax.figure.tight_layout(pad=4) fig.suptitle("AAL Open, High, Low, Close & Volume Market Values grouped by Month", fontweight='bold',fontsize=18) plt.figure(figsize=(12,6)) sns.boxplot(x='Month',y='volume',hue='Week_Day',palette='magma',data=data) plt.ylim(0,0.4E8); # + # AAL Close Price Kernel Density Estimation plot fig,axs=plt.subplots(2,1,figsize=(12,10)) sns.distplot(data['close'],kde=True,hist=False,ax=axs[0]) axs[0].set_title('AAL Close Price - Kernel Density Estimation') # AAL stock market Volume values distribution - Histogram sns.distplot(data['close'],kde=False,bins=10,ax=axs[1]) axs[1].set_title('AAL Close Price Distribution - Histogram') axs[1].set_ylabel('Counts') for ax in axs.flat: plt.rcParams["font.weight"] = "bold" plt.rcParams['font.size']=13 ax.set_xlabel('AAL Close Price') ax.figure.tight_layout(pad=3); # - # Bar plot showing the correlations between the 'AAL Volume' feature and the other dataset variables. plt.figure(figsize=(10,6)) plt.rcParams['font.size']=12 data.corr(method='pearson')['volume'].sort_values().drop(['Year','Month','volume']).plot(kind='bar',color='c') plt.title("Correlations between the AAL 'Low, Close, Open, High' features and the AAL trading Volume "); # + # The 'jointplot' presented in this cell can be used at cases where there is need/requirement to detect/drop outliers. # The outliers can have a negative impact on the training process of the deep learning model. In this demonstration, due to # the strong correlation of these two features (r value very close to 1 and p almost zero --> indicating evidence # of strong relationship between the two variables),there is no need to drop any values import scipy.stats as stats j_plot=sns.jointplot(x=data['open'], y=data['close'],height=7, kind='reg') r, p = stats.pearsonr(data['open'],data['close']) rp, = j_plot.ax_joint.plot([], [], linestyle="", alpha=0) plt.xlabel('AAL Open Price') plt.ylabel('AAL Close Price') j_plot.ax_joint.legend([rp],['r={:f}, p={:f}'.format(r,p)]) plt.show() # - # In this cell, the goal is to determine the percentage of change of AAL Close Price value on a daily(business day) # basis. Therefore, AAL Close prices are shifted by 1, then the shifted values are subtracted from each daily value # and the difference is divided by the previous day value and finally multiplied by 100. # The final array is converted into a pd.dataframe and the column is renamed as presented below. # Negative values indicate a decrease in the AAL Close price with respect to the previous business day perc_close_change=100*((data['close']-data['close'].shift(1))/data['close'].shift(1)) perc_close_change=perc_close_change.dropna() perc_close_change=pd.DataFrame(perc_close_change) perc_close_change.rename(columns={'close':'Close_Businness_Day_Change_%'},inplace=True) perc_close_change.head() # Summary Statistics of the AAL Close Price - Business Day Change % perc_close_change.describe().transpose() # AAL Close Price - Bysiness Day Change % - Kernel Density Estimation plot plt.figure(figsize=(10,6)) plt.xlabel('AAL Close Price Bysiness Day Change %',fontweight='bold') plt.ylabel('Density',fontweight='bold') plt.title('Kernel Density Estimation',fontweight='bold') sns.distplot(perc_close_change,kde=True,hist=False); # # Part B - - Case Study # # ***Time Series Forecasting (Step-Ahead) of the parameter of interest (dependent variable) based on input (independent variables)*** # Setting the 'date' feature as dataset index data=data.set_index('date') data.head() # AAL Close Price past observations (Business Day Freq.) plt.figure(figsize=(10,6)) data['close'].plot() plt.xlabel('Date',fontweight='bold') plt.ylabel('AAL Close Price (Freq=Business Day)',fontweight='bold'); # Dropping the features that are not going to be used as LSTM model inputs data=data.drop(['Week_Day','Month','Year','Name'],axis=1) # Changing the frequency of observations from 'Business Day' to 'Weekly' (AAL Close Average Weekly price) data=data.resample('W').mean() data.shape # The index has been updated (frequency=Week) data.head() # DatetimeIndex: 262 entries, 2013-02-10 to 2018-02-11 data.info() # No presence of missing/'NaN' entries data.isnull().sum() # AAL Close price past observations (Freq=Week.) plt.figure(figsize=(10,6)) data['close'].plot() plt.xlabel('Date',fontweight='bold') plt.ylabel('AAL Close Price (Average Weekly Values)',fontweight='bold'); # + # Function to create the input-output sequence. Each train batch consists of 12 inputs & the corresponding # y_target value (one step-ahead) from numpy import array def set_seq(seq, seq_len): X = [] y = [] for t in range(len(seq)-seq_len): end = t + seq_len # End index is equal to the current index plus the specified number of sequence length if end> len(seq)-1:# if the length of the formed train sequence is greater than the length of the input feature,stop break # for seq_length=12 : X_input seq. ->12 (indices 0-11) past observations, y_target -> 1 observation at one time step ahead # (index 12) Xseq= seq[t:end, :-1] y_target =seq[end, -1] X.append(Xseq) y.append(y_target) return array(X), array(y) #initializing the arrays # - # Defining the inputs and output of the LSTM model so as to create the sequences input_1 =data['open'].values input_2 = data['high'].values input_3 = data['low'].values input_4 = data['volume'].values output_feat = data['close'].values # Reshaping for converting the inputs/output to 2d shape input_1 = input_1.reshape((len(input_1), 1)) input_2 = input_2.reshape((len(input_2), 1)) input_3 = input_3.reshape((len(input_3), 1)) input_4 = input_4.reshape((len(input_4), 1)) output_feat = output_feat.reshape((len(output_feat), 1)) # Use of hstack to put together the input sequence arrays horizontally (column wise) from numpy import hstack df = hstack((input_1, input_2,input_3, input_4)) df[:5] # + # Selecting the length of each sequence and the size of the prediction horizon (forecast_steps) seq_len= 12 pred_horizon=52 # Splitting the dataset into training and test set (y_test -->to compare the LSTM forecasts for given inputs (X_test)) X_train=df[:-pred_horizon] y_train=output_feat[:-pred_horizon] X_test=df[-pred_horizon:] y_test=output_feat[-pred_horizon:] # - # The shape of training and test data print(X_train.shape,y_train.shape) print(X_test.shape,y_test.shape) # MinMaxScaler is used to transform dataset columns by scaling them between 0 & 1.Training samples are first fitted # and then transformed, whereas the test samples are transformed based on the previously fitted training samples in order # to avoid forecasting with a biased ML model. from sklearn.preprocessing import MinMaxScaler scaler=MinMaxScaler() X_train=scaler.fit_transform(X_train) X_test=scaler.transform(X_test) y_train=scaler.fit_transform(y_train) y_test=scaler.transform(y_test) # Use of hstack to put together the train sequence arrays horizontally df_train = hstack((X_train,y_train)) # Creating the training sequences Xtrain_seq,ytrain_seq=set_seq(df_train, seq_len) # Presenting the first two training sequences. As it can be observed, the first 12 input entries (seq_len=12), # i.e. The current index input value at time step 12 and the past 11 observations for each feature, together with the # AAL Close price at time step 13 (one-step ahead),comprise the first sequence. # In the second batch, the sequence is updated by dropping the first input values and appending the next X-y values # at the end of the batch. # As it can be observed, the first two y target values correspond to the y_train values with indices 12 and 13 for # time steps 13 and 14 respectively for t in range(2): print(Xtrain_seq[t], ytrain_seq[t]) print('\r') print('The first two ytrain_seq values correspond to the train target values (y_train) with indexes 12 and 13 : ') print(y_train[12:14]) # The input training data have been converted into 3d shape--> [sample_length,seq_len, number of input features] print(Xtrain_seq.shape) # Defining the number of input features features_num = Xtrain_seq.shape[2] features_num # Reshaping the target train data to be inserted into the LSTM model in the proper dimension ytrain_seq=ytrain_seq.reshape((-1,1)) ytrain_seq.shape # + # Importing the necessary libraries to create/construct the neural network model from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense,LSTM from tensorflow.keras import initializers import tensorflow as tf tf.random.set_seed(0) np.random.seed(0) # Use of the he_uniform initializer to set the initial weights initializer = tf.keras.initializers.he_uniform(seed=0) model = Sequential() # Use of 12 neurons--> equal to the length of an input train sequence model.add(LSTM(12, activation='relu', input_shape=(seq_len, features_num), kernel_initializer=initializer)) # The output layer consists of 1 neuron with a 'linear' activation fuction model.add(Dense(1,activation='linear',kernel_initializer=initializer)) # The model is compiled with selected loss function= 'mse', whereas the selected optimizer is 'adam' with a learning rate # of 0.001, epsilon=1e-8 and with the default values of the exponential decay rates for the first and second moment estimates opt = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8) model.compile(optimizer=opt, loss='mse') # Fitting the LSTM model model.fit( Xtrain_seq, ytrain_seq,epochs=60, batch_size=1, shuffle=False,verbose=0) # - # Training loss plot loss = pd.DataFrame(model.history.history) loss.plot() plt.title('LSTM Training Loss',fontweight='bold') plt.xlabel('Epochs',fontweight='bold') plt.ylabel("Loss-'MSE'",fontweight='bold'); # ***LSTM Predictions - Training Set*** # + # Determining all LSTM training set predictions so as to compare them with the actual AAL Close training values train_lstm_outputs = [] train_batch = Xtrain_seq[0].reshape((1, seq_len, features_num)) for i in range(len(Xtrain_seq[1:])): train_lstm_out = model.predict(train_batch)[0] train_lstm_outputs.append(train_lstm_out) train_batch=Xtrain_seq[1:][i].reshape((1, seq_len, features_num)) #Append train_lstm_output from last train batch train_lstm_outputs.append(model.predict(train_batch)[0]) # - # Last appended input to the final train sequence (train_batch) is X_train[-2]. # The X_train[-1] is to be appended to the input sequence after training to determine the first forecasted value # This is because the model is trained to predict one step ahead print('Final train batch (sequence): \n') print(train_batch) print("\r") print('Last appended input of the final train batch: \n') print(X_train[-2]) # Applying the inverse_transform function to the training_outputs to get their true values step_train_predictions=scaler.inverse_transform(train_lstm_outputs) step_train_predictions=step_train_predictions.reshape((-1,1)) # Length of train sequences len(Xtrain_seq) # Applying the inverse_transform function to the ytrain_seq set ytrain_seq=scaler.inverse_transform(ytrain_seq) # + # # LSTM Training Performance - Actual vs. Predicted Training Set Values for 198 training steps (198 training sequences) plt.figure(figsize=(10,6)) plt.plot(ytrain_seq,marker='o',linestyle='-') plt.plot(step_train_predictions,marker='o',linestyle='dashed') plt.title(' LSTM - Actual vs. Predicted Values (Training Set)',fontweight='bold') plt.legend(('Actual_Train_Values','Predicted_Train_Values')) plt.xlabel('Steps 1-198',fontweight='bold') plt.ylabel('AAL Close - Average Weekly Price',fontweight='bold'); # - # Relative Error Percentage distribution plot (Training Set) step_train_err=abs((ytrain_seq-step_train_predictions)/ytrain_seq)*100 step_train_err=pd.DataFrame(step_train_err,columns=['Training Set Error']) plt.figure(figsize=(10,6)) sns.kdeplot(step_train_err['Training Set Error'],shade=True,color='r',kernel='gau',) plt.xlabel('Percentage of Training Set Relative Error',fontweight='bold') plt.title('Kernel Density Estimation ',fontweight='bold'); # + # Summary statistics of training relative error step_train_err.describe().transpose() # - # Determining the Root Mean Squared Error of the train_predicted values and the actual_train values RMSE=np.sqrt(mean_squared_error(ytrain_seq,step_train_predictions)) RMSE=RMSE.round(2) RMSE # ***Time Series Forecasting & comparison with Test Set*** # Creating the first batch to forecast the first AAL Close price. # First batch consists of the final train batch, where the last X train input (X_train[-1]) is appended first_batch=np.append(train_batch[:,1:,:],[[X_train[-1].reshape((1,1,features_num))]]) first_batch=first_batch.reshape((1, seq_len, features_num)) print(first_batch) X_train[-1] # + # Determining all LSTM predicted values so as to compare them with the actual test values lstm_outputs = [] batch =first_batch # loop to determine all other predictions based on the X_test inputs that are appended to the batch for i in range(len(X_test)): lstm_out = model.predict(batch)[0] lstm_outputs.append(lstm_out) # The first row of the current batch sequence is dropped, and the next X_test input is placed at the end of the batch batch = np.append(batch[:,1:,:],[[X_test[i]]],axis=1) # - # Applying the inverse_transform function to the predicted values to get their true values step_true_predictions=scaler.inverse_transform(lstm_outputs) step_true_predictions # Applying the inverse_transform function to the y_test set y_test=scaler.inverse_transform(y_test) # Plot of the Test vs. Predicted results for a prediction horizon of 52 weeks plt.figure(figsize=(10,6)) plt.plot(y_test,marker='o',linestyle='-') plt.plot(step_true_predictions,marker='o',linestyle='dashed') plt.title('LSTM Forecasting Performance - Actual vs. Forecasted Values',fontweight='bold') plt.legend(('AAL_Test_Values','AAL_Forecast_Values')) plt.xlabel('Test Steps',fontweight='bold') plt.ylabel('AAL Close - Average Weekly Price',fontweight='bold'); # Date index of first y_train value data.index[seq_len] # LSTM training outputs indices step_train_index=pd.date_range(start='2013-05-05',periods=198,freq='W') # Converting the train_predictions from np.ndarray to pandas dataframe step_train_data=pd.DataFrame(data=step_train_predictions,index=step_train_index,columns=['Predicted (Train_Set)']) # Date index of first forecasted value data.index[-pred_horizon] # LSTM forecasted outputs indices step_pred_index=pd.date_range(start='2017-02-19',periods=pred_horizon,freq='W') # Converting the step_true_predictions from np.ndarray to pandas dataframe step_pred_data=pd.DataFrame(data=step_true_predictions,index=step_pred_index,columns=['Forecast']) # + # Final plot comprising all the actual AAL Close values, the LSTM model's predictions on the training set (index 12 to 209) & # the LSTM forecasts from index 210 (time step 211) to 261 (time step 262) ax=data['close'].plot(figsize=(12,8),label='AAL Close Price') ax.fill_between(data.index,0,60 ,where=data.index < step_train_index[0], color='grey', alpha=0.5, transform=ax.get_xaxis_transform()) ax.fill_between(data.index,0,60 ,where=data.index > step_train_index[-1], color='plum', alpha=0.5, transform=ax.get_xaxis_transform()) step_train_data.plot(ax=ax) step_pred_data.plot(ax=ax) plt.legend() plt.xlabel('Date',fontweight='bold') plt.ylabel('AAL Close - Average Weekly Price',fontweight='bold') plt.title('LSTM 52-Weeks One-Step Ahead Predictions',fontweight='bold') plt.show() # - # RMSE of forecasted and test AAL Close prices RMSE=np.sqrt(mean_squared_error(y_test,step_true_predictions)) RMSE=RMSE.round(2) RMSE
LSTM_TimeSeriesForecast_Seq_to_One_Multi-Inp_Output.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/marisbotero/sapiencia/blob/main/Workshop1_Maris.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="88926dc1" import pandas as pd import numpy as np # + [markdown] id="1cedc4ca" # ## Basic python operations # + [markdown] id="5cbcef74" # * https://www.hackerrank.com/challenges/py-if-else/problem?h_r=internal-search # + [markdown] id="4e2a5da1" # * https://www.hackerrank.com/challenges/python-arithmetic-operators/problem # + [markdown] id="4c17747d" # * https://www.hackerrank.com/challenges/python-division/problem # + [markdown] id="fce38653" # * https://www.hackerrank.com/challenges/python-loops/problem # + [markdown] id="bebe62c6" # ## Basic python structures # + [markdown] id="411c2ebf" # * https://www.hackerrank.com/challenges/python-lists/problem # + [markdown] id="6eeea4d0" # * https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem # + [markdown] id="bf4d2376" # * https://www.hackerrank.com/challenges/nested-list/problem # + [markdown] id="c2ae091f" # ## Numpy # + [markdown] id="3a78cc26" # * Create a null vector of size 10 (★☆☆) # + colab={"base_uri": "https://localhost:8080/"} id="b2a32025" outputId="01a586f5-186e-48e4-cce9-44a64f1c6807" x = np.zeros(10) (x) # + [markdown] id="1c00fa44" # * Reverse a vector (first element becomes last) (★☆☆) # + colab={"base_uri": "https://localhost:8080/"} id="3561ca9f" outputId="30541fbc-0143-4b5a-a944-3676d70ad4c2" x = np.arange(12, 38) print("Original vector:") print(x) print("Reverse vector:") x = x[::-1] print(x) # + [markdown] id="5f09a28a" # * Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆) # + id="36ee5a17" colab={"base_uri": "https://localhost:8080/"} outputId="c298b2c2-4df3-46f4-f385-15cf99b08651" x = np.array([1,2,0,0,4,0] ) m =np.nonzero(x) print ("Indices of non zero elements : ", m) # + [markdown] id="61b2d89b" # * Create a 3x3 identity matrix (★☆☆) # + colab={"base_uri": "https://localhost:8080/"} id="c9997739" outputId="dce62bbf-cff1-4091-e446-4e535db721f6" m=np.identity(3) m # + [markdown] id="6a465823" # * Create a 10x10 array with random values and find the minimum and maximum values (★☆☆) # + colab={"base_uri": "https://localhost:8080/"} id="8fff5657" outputId="03e10ffb-45d3-4e92-b58e-1152e8333335" x = np.random.random((10,10)) print("Original :") print(x) xmin, xmax = x.min(), x.max() print("Minimum and Maximum Values:") print(xmin, xmax) # + [markdown] id="855b6698" # ## Pandas # + [markdown] id="fc072f8a" # Consider the following Python dictionary data and Python list labels # + id="9726d8bb" data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'], 'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3], 'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']} labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] # + [markdown] id="322440c8" # * Create a DataFrame df from this dictionary data which has the index labels # + id="5b562000" colab={"base_uri": "https://localhost:8080/"} outputId="1093de06-f370-4054-eb1a-8326760147ed" df = pd.DataFrame(data , index=labels) print(df) # + [markdown] id="6a98124b" # * Display a summary of the basic information about this DataFrame and its data (hint: there is a single method that can be called on the DataFrame 'describe') # + id="bef1b4d7" colab={"base_uri": "https://localhost:8080/", "height": 297} outputId="0dff7bad-3715-4b48-96c9-0f2666303400" #df.info() df.describe() # + [markdown] id="9c101946" # * Return the first 3 rows of the DataFrame df # + id="88d5c97c" colab={"base_uri": "https://localhost:8080/", "height": 142} outputId="3b913802-71d0-423c-c5dc-f2ae3597b28e" df.iloc[:3] # + [markdown] id="4822c294" # * Select just the 'animal' and 'age' columns from the DataFrame df # + id="fbced56d" colab={"base_uri": "https://localhost:8080/", "height": 359} outputId="45c69eb4-a5f6-4cd9-d1c6-a2e2a4653097" df[['animal', 'age']] # + [markdown] id="c648100c" # * Select the rows where the age is missing, i.e. it is NaN. # + id="e914d012" colab={"base_uri": "https://localhost:8080/", "height": 111} outputId="a9b6c32e-45f9-4eff-8cd1-68da24e91121" df[df['age'].isnull()] # + [markdown] id="2ae99f60" # * Calculate the sum of all visits in df (i.e. find the total number of visits) # + id="24682ef9" colab={"base_uri": "https://localhost:8080/"} outputId="f6ace356-5cd9-46b1-bfda-62f19a1c9b2d" df.groupby(['visits']).size()
Workshop1_Maris.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: dl-workshop # language: python # name: dl-workshop # --- # + import jax.numpy as np import numpy.random as npr import matplotlib.pyplot as plt from ipywidgets import interact, FloatSlider # %load_ext autoreload # %autoreload 2 # %matplotlib inline # %config InlineBackend.figure_format = 'retina' # - # # Linear Regression # # Linear regression is foundational to deep learning. It should be a model that everybody has been exposed to before. However, it is important for us to go through this with a view to how we connect linear regression to the neural diagrams that are shown. # ## Discussion # # - In our machine learning toolkit, where do we use linear regression? # - What are its advantages? # - What are its disadvantages? # ## Equation Form # # Linear regression, as a model, is expressed as follows: # # $$y = wx + b$$ # # Here: # # - The **model** is the equation, $y = wx + b$. # - $y$ is the output data. # - $x$ is our input data. # - $w$ is a slope parameter. # - $b$ is our intercept parameter. # - Implicit in the model is the fact that we have transformed $y$ by another function, the "identity" function, $f(x) = x$. # # In this model, $y$ and $x$ are, in a sense, "fixed", because this is the data that we have obtained. On the other hand, $w$ and $b$ are the parameters of interest, and *we are interested in **learning** the parameter values for $w$ and $b$ that let our model best explain the data*. # # I will reveal the punchline early: # # > The **learning** in deep learning is about figuring out parameter values for a given model. # ## Make Simulated Data # # To explore this idea in a bit more depth as applied to a linear regression model, let us start by making some simulated data with a bit of injected noise. # # You can specify a true $w$ and a true $b$ as you wish, or you can just follow along. # ### Exercise # + x = np.linspace(-5, 5, 1000) w_true = _____ # exercise: specify ground truth w. b_true = _____ # exercise: specify ground truth b. def noise(n): return npr.normal(size=(n)) # exercise: write the linear equation down. y = _____ # Plot ground truth data plt.scatter(x, y) plt.xlabel('x') plt.ylabel('y') # - # ### Exercise # # Now, let's plot what would be a very bad estimate of $w$ and $b$. # Plot a very bad estimate w = _____ # exercise: fill in a bad value for w b = _____ # exercise: fill in a bad value for b y_est = _____ # exercise: fill in the equation. plt.plot(x, y_est, color='red', label='bad model') plt.scatter(x, y, label='data') plt.xlabel('x') plt.ylabel('y') plt.legend() # ## Loss Function # # How bad is our model? We can quantify this by looking at a metric called the "mean squared error". The mean squared error is defined as "the average of the sum of squared errors". # # "Mean squared error" is but one of many **loss functions** that are available in deep learning frameworks. It is commonly used for regression tasks. # # Loss functions are designed to quantify how bad our model is in predicting the data. # # ### Exercise # # Let's implement the mean squared error function. # + # Exercise: implement mean squared error function in NumPy code. # It should take in y_true and y_pred as arguments, # and return a scalar. def mse(y_true, y_pred): # Your code here return # Calculate the mean squared error between mse(y, y_est) # - # ### Activity: Optimize model by hand. # # Now, we're going to optimize this model by hand. Use the sliders provided to adjust the model. @interact( w=FloatSlider(min=-10, max=10, step=0.1), b=FloatSlider(min=0, max=30, step=0.1) ) def optimize_plot(w, b): y_est = x * w + b plt.scatter(x, y, alpha=0.3, label='data') plt.plot(x, y_est, color='red', label='model') plt.xlabel('x') plt.ylabel('y') plt.legend() plt.title(f'MSE: {mse(y, y_est):.02f}') # ### Discussion # # As you were optimizing the model, what did you notice about the MSE? score? # # Detour: Gradient-Based Optimization # # Implicit in what you were doing was something we formally call "gradient-based optimization". This is a very important point to understand. If you get this for a linear model, you will understand how this works for more complex models. Hence, we are going to go into a small crash-course detour on what gradient-based optimization is. # # ## Derivatives # # At the risk of ticking off mathematicians for a sloppy definition, for this workshop's purposes, a useful way of defining the derivative is: # # > How much our output changes as we take a small step on the inputs, taken in the limit of going to very small steps. # # If we have a function: # # $$f(w) = w^2 + 3w - 5$$ # # What is the derivative of $f(x)$ with respect to $w$? From first-year undergraduate calculus, we should be able to calculate this: # # $$f'(w) = 2w + 3$$ # # (We will use the apostrophe marks to indicate derivatives. 1 apostrophe mark means first derivative, 2nd apostrophe mark means 2nd derivative.) # ## Minimizing $f(w)$ Analytically # # What is the value of $w$ that minimizes $f(w)$? Again, from undergraduate calculus, we know that at a minima of a function (whether it is a global or local), the first derivative will be equal to zero, i.e. $f'(w) = 0$. By taking advantage of this property, we can analytically solve for the value of $w$ at the minima. # # $$2w + 3 = 0$$ # # Hence, # # $$w = -\frac{3}{2} = 1.5$$ # # To check whether the value of $w$ at the place where $f'(w) = 0$ is a minima or maxima, we can use another piece of knowledge from 1st year undergraduate calculus: The sign of the second derivative will tell us whether this is a minima or maxima. # # - If the second derivative is positive regardless of the value of $w$, then the point is a minima. (Smiley faces are positive!) # - If the second derivative is negative regardless of the value of $w$, then the point is a maxima. (Frowning faces are negative!) # # Hence, # # $$f''(w) = 2$$ # # We can see that $f''(w) > 0$ for all $w$, hence the stationary point we find is going to be a local minima. # ## Minimizing $f(w)$ Computationally # # An alternative way of looking at this is to take advantage of $f'(w)$, the gradient, evaluated at a particular $w$. A known property of the gradient is that if you take steps in the negative direction of the gradient, you will eventually reach a function's minima. If you take small steps in the positive direction of the gradient, you will reach a function's maxima (if it exists). # # ### Exercise # # Let's implement this using the function $f(w)$, done using NumPy. # + # Exercise: Write f(w) as a function. def f(w): """ Note: We don't use this function in this cell. """ return _____ # Exercise: Write df(w) as a function. def df(w): """ Derivative of f with respect to w. """ return _____ # Exercise: Pick a number to start w at. w = _____ # start with a float # Now, adjust the value of w 1000 times, taking small steps in the negative direction of the gradient. for i in range(1000): _____ print(w) # - # Congratulations, you have just implemented **stochastic gradient descent** (SGD)! # # Stochastic gradient descent is an **optimization routine**: a way of programming a computer to do optimization for you so that you don't have to do it by hand. # ## Minimizing $f(w)$ with `jax` # # `jax` is a Python package for automatically computing gradients; it is known as an "automatic differentiation" system. This way, we do not have to specify the gradient function by hand-calculating it; rather, `jax` will know how to automatically take the derivative of a Python function w.r.t. the first argument. With `jax`, our example above is modified in only a slightly different way. # + from jax import grad from tqdm import tqdm_notebook as tqdmn def f(w): return w**2 + 3 * w - 5 # This is what changes: we use autograd's `grad` function to automatically return a gradient function. df = grad(f) # Exercise: Pick a number to start w at. w = _____ # Now, adjust the value of w 1000 times, taking small steps in the negative direction of the gradient. for i in tqdmn(range(1000)): _____ print(w) # - # # Back to Optimizing Linear Regression # # ## What are we optimizing? # # In linear regression, we are minimizing (i.e. optimizing) the loss function w.r.t. the linear regression parameters. # # **Keep in mind:** The loss function is the parallel to the $f(w)$ polynomial function that we were playing around with above. # # ## Ingredients for "Optimizing" a Model # # At this point, we have learned what the ingredients are for optimizing a model: # # 1. A model, which is a function that maps inputs $x$ to outputs $y$, and its parameters of the model. In our linear regression case, this is $w$ and $b$; usually, in the literature, we call this a **parameter set** $\theta$. # 2. Loss function, which tells us how bad our predictions are. # 3. Optimization routine, which tells the computer how to adjust the parameter values to minimize the loss function. # # **Keep note:** Because we are optimizing the loss w.r.t. two parameters, finding the $w$ and $b$ coordinates that minimize the loss is like finding the minima of a bowl. # # The latter point, which is "how to adjust the parameter values to minimize the loss function", is the key point to understand here. # ## Code-Along Exercise # # We are going to write code to tie this all together. In order help you follow along, I will type this in full, but you will only have to fill-in-the-blanks. # + # Exercise: Define the model def model(p, x): _____ return _____ # Initialize values of w and b. # We will store the parameter values in a dictionary. # The dict keys are the name of the parameter, # and the dict values are the parameter values. params = dict() params['w'] = _____ # draw one value from standard normal params['b'] = _____ # FITB # Differentiable loss function w.r.t. 1st argument def mseloss(params, model, x, y): _____ return _____ dmseloss = grad(mseloss) # derivative of loss function # Optimization routine losses = [] for i in tqdmn(range(3000)): # Evaluate the gradient at the given params values. grad_p = _____ # Update the gradient values for each parameter. for k, p in params.items(): _____ # Keep track of losses. losses.append(mseloss(params, model, x, y)) # - # Now, let's plot the loss score over time. It should be going downwards. plt.plot(losses) plt.xlabel('iteration') plt.ylabel('mse') plt.show() # + from pprint import pprint pprint(params) # - # # Recap: Ingredients # # 1. Model specification ("equations", e.g. $y = wx + b$) and the parameters of the model to be optimized ($w$ and $b$, or more generally, $\theta$). # 2. Loss function: tells us how wrong our model parameters are w.r.t. the data ($MSE$) # 3. Opitmization routine (for-loop) # # Linear Regression, Extended # # Thus far, we have shown linear regression using only one-dimensional inputs (i.e. one column of data). Linear regression has been extended to higher dimensional inputs, i.e. two or more columns of data. # # ## In Pictures # # Linear regression can be expressed pictorially, not just in equation form. Here are two ways of visualizing linear regression. # # ### Matrix Form # # Linear regression in one dimension looks like this: # # ![](../figures/linreg-scalar.png) # # Linear regression in higher dimensions looks like thhis: # # ![](../figures/linreg-matrices.png) # # ### Neural Diagram # # We can draw a "neural diagram" based on the matrix view, with the implicit "identity" function included. # # ![](../figures/linreg-neural.png) # # The neural diagram is one that we commonly see in the introductions to deep learning. As you can see here, linear regression, when visualized this way, can be conceptually thought of as the baseline model for understanding deep learning. # # The neural diagram also expresses the "compute graph" that transforms input variables to output variables. # # Break (10 min.) # # Extension beyond Linear Regression # # A key idea from this tutorial is to treat the aforementioned four ingredients as being **modular** components of machine learning. This means that we can swap out the model (and its associated parameters) to fit the problem that we have at hand. # # Logistic Regression # # Logistic regression builds upon linear regression. We use logistic regression to perform **binary classification**, that is, distinguishing between two classes. Typically, we label one of the classes with the integer 0, and the other class with the integer 1. # ## Model in Pictures # # To help you build intuition, let's visualize logistic regression using pictures again. # # ### Matrix Form # # ![](../figures/logreg-matrices.png) # # ### Neural Diagram # # ![](../figures/logreg-neural.png) # # ## Interactive Activity # # As should be evident from the pictures, logistic regression builds upon linear regression simply by **changing the activation function from an "identity" function to a "logistic" function**. In the one-dimensional case, it has the same two parameters as one-dimensional linear regression, $w$ and $b$. Let's use an interactive visualization to visualize how the parameters $w$ and $b$ affect the shape of the curve. # + def logistic(x): return 1 / (1 + np.exp(-x)) @interact( w=FloatSlider(min=-5, max=5, step=0.1, value=1), b=FloatSlider(min=-5, max=5, step=0.1, value=1) ) def plot_logistic(w, b): x = np.linspace(-10, 10, 1000) z = w * x + b # linear transform on x y = logistic(z) plt.plot(x, y) # - # ## Discussion # # 1. What do $w$ and $b$ control, respectively? # 2. Where else do you see logistic-shaped curves? # ## Make simulated data # # In this section, we're going to show that we can optimize a logistic regression model using the same set of ingredients. # # First off, let's start by simulating some data. x = np.linspace(-5, 5, 100) w = 2 b = 1 z = w * x + b + npr.random(size=len(x)) y_true = np.round(logistic(z)) plt.scatter(x, y_true, alpha=0.3) # ## Loss Function # # How would we quantify how good or bad our model is? In this case, we use the logistic loss function, also known as the binary cross entropy loss function. # # Expressed in equation form, it looks like this: # # $$L = -(y \log(p) + (1-y)\log(1-p))$$ # # Here: # # - $y$ is the actual class, namely $1$ or $0$. # - $p$ is the predicted class. # # If you're staring at this equation, and thinking that it looks a lot like the Bernoulli distribution log likelihood, you are right! # # ### Discussion # # Let's think about the loss function for a moment: # # - What happens to the term $y \log(p)$ when $y=0$ and $y=1$? What about the $(1-y)\log(1-p)$ term? # - What happens to both terms when $p \approx 0$ and when $p \approx 1$ (but still bounded between 0 and 1)? # ### Exercise # # Now, let's write down the logistic model. # + # Exercise: Define logistic model def logistic_model(p, x): _____ return # Exercise: Define logistic loss function, using flattened parameters def logistic_loss(p, model, x, y): _____ return # Exercise: Define gradient of loss function. dlogistic_loss = _____ # Exercise: Define parameters, and then flatten them. params = dict() params['w'] = _____ params['b'] = _____ # Exercise: write SGD training loop. losses = [] for i in tqdmn(range(5000)): # Evaluate gradient grad_params = _____ # Update parameters for k, v in params.items(): params[k] _____ # Keep track of losses losses.append(logistic_loss(params, logistic_model, x, y_true)) # - pprint(params) # You'll notice that the values are off from the true value. Why is this so? Partly it's because of the noise that we added, and we also rounded off values. plt.plot(losses) plt.scatter(x, y_true, alpha=0.3) plt.plot(x, logistic_model(params, x), color='red') # ### Exercise # # What if we did not round off the values, and did not add noise to the original data? Try re-running the model without those two. # # Neural Networks # # Neural networks are basically very powerful versions of logistic regressions. Like linear and logistic regression, they also take our data and map it to some output, but does so without ever knowing what the true equation form is. # # That's all a neural network model is: an arbitrarily powerful model. # # ## Feed Forward Neural Networks in Pictures # # To give you an intuition for this, let's see one example of a deep neural network in pictures. # # ### Matrix diagram # # As usual, in a matrix diagram. # # ![](../figures/deepnet_regressor-matrices.png) # # ### Neural diagram # # And for correspondence, let's visualize this in a neural diagram. # # ![](../figures/deepnet_regressor-neural.png) # # ## Discussion # # - When would we want to use a neural network? When would we not want to use a neural network? # ## Real Data # # We are going to try using some real data from the UCI Machine Learning Repository to something related to our work: QSAR modelling! # # With the dataset below, we want to predict whether a compound is biodegradable based on a series of 41 chemical descriptors. # # The dataset was taken from: https://archive.ics.uci.edu/ml/datasets/QSAR+biodegradation#. I have also prepared the data such that it is split into X (the predictors) and Y (the class that we are trying to predict), so that you do not have to worry about manipulating pandas DataFrames. # # Let's read in the data. # + import pandas as pd X = pd.read_csv('../data/biodeg_X.csv', index_col=0) y = pd.read_csv('../data/biodeg_y.csv', index_col=0) # - # Now, let's write a neural network model. This neural network model starts with 41 input nodes, has 1 hidden layer with 20 nodes, and 1 output layer with 1 node. Because this is a classification problem, we will use a logistic activation function right at the end. # + # Exercise: Initialize parameters params = _____ # Exercise: Write model together. def model(p, x): _____ return # We do not need to rewrite the logistic loss; # this is because it has been defined above already! # Exercise: Write training loop. losses = [] for i in tqdmn(range(20000)): grad_p = _____ for k, v in params.items(): params[k] = params[k] - grad_p[k] * 0.01 losses.append(logistic_loss(params, model, X.values, y.values)) # - plt.plot(losses) plt.title(f"final loss: {losses[-1]:.2f}") plt.show() # We can use a confusion matrix to see how "confused" a model was. Read more on [Wikipedia](https://en.wikipedia.org/wiki/Confusion_matrix). # + from sklearn.metrics import confusion_matrix y_pred = model(params, X.values) confusion_matrix(y.values, np.round((y_pred))) # + import seaborn as sns sns.heatmap(confusion_matrix(y, np.round(y_pred))) plt.xlabel('predicted') plt.ylabel('actual') # - # # Recap # # Deep learning, and more generally any modelling, has the following ingredients: # # 1. A model and its associated parameters to be optimized. # 2. A loss function against which we are optimizing parameters. # 3. An optimization routine. # # You have seen these three ingredients at play with 3 different models: a linear regression model, a logistic regression model, and a deep feed forward neural network model. # # ## In Pictures # # ![](../figures/infographic.png) # # ## Caveats of this tutorial # # Deep learning is an active field of research. I have only shown you the basics here. In addition, I have also intentionally omitted certain aspects of machine learning practice, such as # # - splitting our data into training and testing sets, # - performing model selection using cross-validation # - tuning hyperparameters, such as trying out optimizers # - regularizing the model, using L1/L2 regularization or dropout # - etc. # # # Parting Thoughts # # Deep learning is nothing more than optimization of a model with a really large number of parameters. # # In its current state, it is not artificial intelligence. You should not be afraid of it; it is just a really powerful model that maps X to Y.
dl-workshop/notebooks/tutorial-student.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/probml/pyprobml/blob/master/book1/intro/datasets.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="cRiaabSUb5Sz" # # Manipulating datasets # # In this colab, we briefly discuss ways to access and manipulate common datasets that are used in the ML literature. Most of these are used for supervised learning experiments. # # + id="02aUbbJ7d7u-" # Standard Python libraries from __future__ import absolute_import, division, print_function, unicode_literals import os import time import numpy as np import glob import matplotlib.pyplot as plt import PIL import imageio from IPython import display import sklearn import seaborn as sns; sns.set(style="ticks", color_codes=True) import pandas as pd pd.set_option('precision', 2) # 2 decimal places pd.set_option('display.max_rows', 20) pd.set_option('display.max_columns', 30) pd.set_option('display.width', 100) # wide windows # + [markdown] id="3pApO0WqcYLK" # # Tabular datasets # # The [UCI ML repository](https://archive.ics.uci.edu/ml/index.php) contains many smallish datasets, mostly tabular. # # [Kaggle](https://www.kaggle.com/datasets) also hosts many interesting datasets. # # [Sklearn](https://scikit-learn.org/0.16/datasets/index.html) has many small datasets builtin, making them easy to use for prototyping, as we illustrate below. # + colab={"base_uri": "https://localhost:8080/"} id="29RGlnbTeBYk" outputId="849ad93f-72d1-41fb-eb37-9f525229c19d" from sklearn import datasets iris = datasets.load_iris() print(iris.keys()) X = iris['data'] y = iris['target'] # class labels print(X.shape) print(iris['feature_names']) # meaning of each feature print(iris['target_names']) # meaning of each class # + [markdown] id="xX4GSX3Fwt1S" # # Tensorflow datasets # # [TFDS](https://www.tensorflow.org/datasets) is a handy way to handle large datasets as a stream of minibatches, suitable for large scale training and parallel evaluation. It can be used by tensorflow and JAX code, as we illustrate below. (See the [official colab](https://colab.research.google.com/github/tensorflow/datasets/blob/master/docs/overview.ipynb) for details.) # # # # + id="s7H7qrB8xT8J" # Standard Python libraries from __future__ import absolute_import, division, print_function, unicode_literals from typing import Any, Iterator, Mapping, NamedTuple, Sequence, Tuple import os import time import numpy as np import glob import matplotlib.pyplot as plt import PIL import imageio from IPython import display import sklearn # + id="kYPihPWaXaSv" colab={"base_uri": "https://localhost:8080/"} outputId="965efbef-7ab6-4ae4-ae99-f573f84c6ec3" # TensorFlow ≥2.0 is required import tensorflow as tf from tensorflow import keras assert tf.__version__ >= "2.0" import tensorflow_datasets as tfds print("tf version {}".format(tf.__version__)) # + id="cNVBYUoYQPrO" import jax from typing import Any, Callable, Sequence, Optional, Dict, Tuple import jax.numpy as jnp rng = jax.random.PRNGKey(0) # + id="80Ltp1RTqA_K" # Useful type aliases Array = jnp.ndarray PRNGKey = Array Batch = Mapping[str, np.ndarray] OptState = Any # + [markdown] id="ckj0R3UbPDPV" # ## Minibatching without using TFDS # # We first illustrate how to make streams of minibatches using vanilla numpy code. TFDS will then let us eliminate a lot of this boilerplate. As an example, let's package some small labeled datasets into two dictionaries, for train and test. # + colab={"base_uri": "https://localhost:8080/"} id="bOkb5HqSPQfd" outputId="57391c65-d7c3-4ca7-ff27-1435d4616c6e" import sklearn import sklearn.datasets from sklearn.model_selection import train_test_split def get_datasets_iris(): iris = sklearn.datasets.load_iris() X = iris["data"] y = iris["target"] N, D = X.shape # 150, 4 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42) train_ds = {'X': X_train, 'y': y_train} test_ds = {'X': X_test, 'y': y_test} return train_ds, test_ds train_ds, test_ds = get_datasets_iris() print(train_ds['X'].shape) print(train_ds['y'].shape) # + colab={"base_uri": "https://localhost:8080/"} id="xz5fOdLxuIEz" outputId="3e9f6602-f730-4614-a2ba-8aa92211ca64" iris = sklearn.datasets.load_iris() print(iris.feature_names) print(iris.target_names) # + [markdown] id="_GBwrYnGSWjg" # Now we make one pass (epoch) over the data, computing random minibatches of size 30. There are 100 examples total, but with a batch size of 30, # we don't use all the data. We can solve such "boundary effects" later. # + colab={"base_uri": "https://localhost:8080/"} id="4oVJlk5rQIef" outputId="42f4ce69-93bf-4515-89c4-cdfcd2f73a51" def extract_batch(ds, ndx): batch = {k: v[ndx, ...] for k, v in ds.items()} #batch = {'X': ds['X'][ndx,:], 'y': ds['y'][ndx]} return batch def process_epoch(train_ds, batch_size, rng): train_ds_size = len(train_ds['X']) steps_per_epoch = train_ds_size // batch_size perms = jax.random.permutation(rng, len(train_ds['X'])) perms = perms[:steps_per_epoch * batch_size] # skip incomplete batch perms = perms.reshape((steps_per_epoch, batch_size)) # perms[i,:] is list of data indices for step i for step, perm in enumerate(perms): batch = extract_batch(train_ds, perm) print('processing batch {} X shape {}, y shape {}'.format( step, batch['X'].shape, batch['y'].shape)) batch_size = 30 process_epoch(train_ds, batch_size, rng) # + [markdown] id="jo-p6Lr9cnB1" # ## Minibatching with TFDS # # Below we show how to convert a numpy array into a TFDS. # We shuffle the records and convert to minibatches, and then repeat these batches indefinitely to create an infinite stream, # which we can convert to a python iterator. We pass this iterator of batches to our training loop. # # # + colab={"base_uri": "https://localhost:8080/"} id="jzX34Vv4cqUQ" outputId="e711b297-55ff-4f7f-da94-69b236d40b55" def load_dataset_iris(split: str, batch_size: int) -> Iterator[Batch]: train_ds, test_ds = get_datasets_iris() if split == tfds.Split.TRAIN: ds = tf.data.Dataset.from_tensor_slices({"X": train_ds["X"], "y": train_ds["y"]}) elif split == tfds.Split.TEST: ds = tf.data.Dataset.from_tensor_slices({"X": test_ds["X"], "y": test_ds["y"]}) ds = ds.shuffle(buffer_size=1 * batch_size) ds = ds.batch(batch_size) ds = ds.cache() ds = ds.repeat() # make infinite stream of batches return iter(tfds.as_numpy(ds)) # python iterator batch_size = 30 train_ds = load_dataset_iris(tfds.Split.TRAIN, batch_size) valid_ds = load_dataset_iris(tfds.Split.TEST, batch_size) print(train_ds) training_steps = 5 for step in range(training_steps): batch = next(train_ds) print('processing batch {} X shape {}, y shape {}'.format( step, batch['X'].shape, batch['y'].shape)) # + [markdown] id="NfX0AeRpQewX" # ## Preprocessing the data # # We can process the data before creating minibatches. # We can also use pre-fetching to speed things up (see # [this TF tutorial](https://www.tensorflow.org/guide/data_performance) for details.) # We illustrate this below for MNIST. # # + id="V-dJ2J0kQkH4" outputId="fcdadd2d-95a9-4d5b-e78d-539a61b25f3e" colab={"base_uri": "https://localhost:8080/"} def process_record(batch): image = batch['image'] label = batch['label'] # reshape image to standard size, just for fun image = tf.image.resize(image, (32, 32)) # flatten image to vector shape = image.get_shape().as_list() D = np.prod(shape) # no batch dimension image = tf.reshape(image, (D,)) # rescale to -1..+1 image = tf.cast(image, dtype=tf.float32) image = ((image / 255.) - .5) * 2. # convert to standard names return {'X': image, 'y': label} def load_mnist(split, batch_size): dataset, info = tfds.load("mnist", split=split, with_info=True) dataset = dataset.map(process_record) if split=="train": dataset = dataset.shuffle(10*batch_size, seed=0) dataset = dataset.batch(batch_size) dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE) dataset = dataset.cache() dataset = dataset.repeat() dataset = tfds.as_numpy(dataset) # leave TF behind num_examples = info.splits[split].num_examples return iter(dataset), num_examples batch_size = 100 train_iter, num_train = load_mnist("train", batch_size) test_iter, num_test = load_mnist("test", batch_size) num_epochs = 3 num_steps = num_train // batch_size print(f'{num_epochs} epochs with batch size {batch_size} will take {num_steps} steps') batch = next(train_iter) print(batch['X'].shape) print(batch['y'].shape) # + [markdown] id="3w95_gDKij4F" # # Vision datasets # + [markdown] id="NIeQtCs1X6vh" # ## MNIST # # There are many standard versions of MNIST, # some of which are available from https://www.tensorflow.org/datasets. We give some examples below. # # + colab={"base_uri": "https://localhost:8080/"} id="Hr2NWROhhxNf" outputId="94c71f41-584d-481f-fded-f85ef5d29f41" ds, info = tfds.load("binarized_mnist", split=tfds.Split.TRAIN, shuffle_files=True, with_info=True) print(ds) print(info) # + colab={"base_uri": "https://localhost:8080/"} id="zfraK_18jp9q" outputId="74a7112e-a048-4420-9f49-2a05df903e3b" train_ds, info = tfds.load("mnist", split=tfds.Split.TRAIN, shuffle_files=True, with_info=True) print(train_ds) print(info) # + colab={"base_uri": "https://localhost:8080/", "height": 300, "referenced_widgets": ["e7267b0caf0b4567b9f75f2173c01ca9", "aa035dda94174d0291fd317977a79187", "507695c8b55d4d09838718faac6c018d", "36294079f5f34e1bb4aea5b31715e53b", "f26c7e4299b444aa97544068211da32d", "867e98ba8daa4caf8bf632bbce7279cc", "0384f357bfd742e1bad0b037870526a3", "dc9833915c4c4b1e8b48b7afb74acfff"]} id="RMijYNrVrkD8" outputId="2962e10e-81c9-4982-d6a1-c4c8845f07ac" ds = tfds.load('mnist', split='train') print(type(ds)) ds = ds.take(1) # Only take a single example print(type(ds)) for example in ds: # example is `{'image': tf.Tensor, 'label': tf.Tensor}` print(list(example.keys())) image = example["image"] label = example["label"] print(image.shape, label) # + colab={"base_uri": "https://localhost:8080/", "height": 365} id="L758Mpe8tGTC" outputId="5eef6fda-c15c-4b79-fc3e-aa3a7570aef2" ds, info = tfds.load('mnist', split='train', with_info=True) fig = tfds.show_examples(ds, info, rows=2, cols=5) # This function is not well documented. But source code for show_examples is here: # https://github.com/tensorflow/datasets/blob/v4.2.0/tensorflow_datasets/core/visualization/image_visualizer.py # + id="YIcG-dUxNL9d" # + [markdown] id="V1MEEmlJirie" # ## CIFAR # # The CIFAR dataset is commonly used for prototyping. # The CIFAR-10 version consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images. The dataset is divided into five training batches and one test batch, each with 10000 images. There is also a 100 class version. # # An easy way to get this data is to use TFDS, as we show below. # + colab={"base_uri": "https://localhost:8080/", "height": 723, "referenced_widgets": ["d526703337764075a7e6059ac6a46690", "4ee1f2714adb4a5eb67fd098ff132d95", "<KEY>", "1608d59a041340628684dff6e86372cf", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "fea3adfca4394d7d9060c22a8dbb1971", "aa44b7d8111b4153bed9a40f1eace33d", "1404c3c099164e538806ac5eef9a5815", "deb690d31eae453d8534d2d627090bea", "80f5726191294a88be90a395e52b3ba1", "<KEY>", "175e6d0844fe4c24a7c8c375793ccc67", "d8550a6424fd4488ac31925bac69ea68", "ebe231c9d2e8465b8664ec9ab2d9eda3", "<KEY>", "<KEY>", "<KEY>", "2a25e73a769447cc93d9e2265778e32b", "9ae04b505d614ff8876a787de7607d9a", "<KEY>", "3edf0eb13759411899c9c4b47693e6bb", "611ec94216164ec2a4c92c0d2fb46862", "07c8e2f409ff44439e03b495f573c2e7", "<KEY>", "7209f1021c7b4e80bde42ad6403dc68e", "<KEY>", "b0835c04a435434681402c86822ab60b", "e14a614ea2da48ad972fe6a10af26fee", "<KEY>", "16a5c001caf349e6bfe33e785ebc1ae2", "<KEY>", "46291d658720446c8a863518d4f95472", "<KEY>", "893649147aa843aba91d85095561a2f0", "7e888e157bcc4fa4b2ca7c7ee6b55e05", "8ce3827639e54bee92d3aa55b3870d12", "17a7de6d743d4c9abaa7c0d0d4d2abc5", "<KEY>", "0f0a111781ea4745a41b912a78a7c728", "86bdb3ead122406581645f8b44826b57", "c20e6ed8a0e54598adcc6c450e530deb", "<KEY>", "<KEY>", "1c46e7f22fa74117802e32a6aec2a7db", "c19ed67332bd49b692c93add9e93456a", "0f52e93d3cae404493d8d06792ecc3c4", "<KEY>", "ef7fc697c1da4d218ea17e96e1834c36", "6d66709ce91d47a2bb7c01cec6893d4e", "7e020206852440ecab58892b51df895a", "9825bd31ea6644bda8e61e4588e30510", "66c5cf8d45c54a019a18ce85fb1d6308"]} id="u4IAzN4xwD8h" outputId="bd882907-de4f-4651-fb0f-18e479c4a8cf" ds, info = tfds.load('cifar10', split='train', with_info=True) fig = tfds.show_examples(ds, info, rows=2, cols=5) # + [markdown] id="mvIhzkmlh0r5" # ## Imagenet # # A lot of vision experiments use the Imagenet dataset, with 1000 classes and ~1M images. # However, this takes a long time to download and process. # The FastAI team made a smaller version called [ImageNette](https://github.com/fastai/imagenette), that only has 10 classes of size 160 or 320 pixels (largest dimension). This is good for prototyping, and the images tend to be easier to interpret that CIFAR. A version of the raw data, in a more convenient format (all images 224x224, no dependence on FastAI library) can be found [here](https://github.com/thunderInfy/imagenette). It is also bundled into TFDS, as we show below. # + colab={"base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": ["1ce46b8c30574a118dcd0150e6820cdc", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "c57e5d63e7f749aa938199a1ec1c7515", "<KEY>", "be0074f3f9f440fc8fd9f401c041f0e5", "f1a5873f03324f79a88671eba289ede0", "aad163d9632e4548a74ffe77c1261db9", "c16eb024010a4d9eba894f4e1dfc423d", "d7e3322442514f698d23a7e12b703e18", "33c5387c4f494eb1963346c3f8a299bc", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "a79d8122071f4a8fa4ee4c885927daff", "<KEY>", "<KEY>", "<KEY>", "e484951ed5ff4e8098676658547014a3", "457e762b546e462d94a4665db9f3bc39", "dfd7a3c95e064fa3a0ca2095dc9ba0bf", "<KEY>", "1def96be1b814c5b95a49459d0502d1a", "<KEY>", "97256ad1f9074e158216e532518579e7", "<KEY>", "688bbd80b2ec419b83a12dd9d12dc917", "4a76833d453d447facd4eb3ea41f1829", "955dea391d3c4387b361ef6bdcc3a853", "e3eb7a31bbe647a3a8520b268b236034", "8c41324381944a05aee3db1184a9dfba", "05d868c646524b228e745e66ce0a58ba", "<KEY>", "<KEY>", "1de21984c33e468c9f76ac322e41953e", "<KEY>", "c6be09e3ae8245c687e8cf6ea2528f70", "b8a556fec1844be9a615603faa101ace", "<KEY>", "daf15971b6b74adf87fc79b334a93964", "26807ca2840a4a34b69d0e50aafccadf", "fa5c188ccb2349e38205e5840a899700", "f87fb78be8e04977a7684df39528b86e", "d27e8f7b15964d498055ce8639d7ffee", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>"]} id="z-UVh5ZWkBzw" outputId="5a6c114f-74a5-42a0-e212-b606d67ab2ca" import tensorflow_datasets as tfds imagenette_builder = tfds.builder("imagenette/full-size") imagenette_info = imagenette_builder.info print(imagenette_info) imagenette_builder.download_and_prepare() # + id="Rl2GabIAlEM9" datasets = imagenette_builder.as_dataset(as_supervised=True) # + colab={"base_uri": "https://localhost:8080/"} id="mn0QiyH6ka2X" outputId="9992352e-f6c6-4657-c30e-615d5c25df97" train_examples = imagenette_info.splits['train'].num_examples validation_examples = imagenette_info.splits['validation'].num_examples print('ntrain', train_examples, 'nvalidation', validation_examples) train, test = datasets['train'], datasets['validation'] import tensorflow as tf batch_size = 32 train_batch = train.map( lambda image, label: (tf.image.resize(image, (448, 448)), label)).shuffle(100).batch(batch_size).repeat() validation_batch = test.map( lambda image, label: (tf.image.resize(image, (448, 448)), label) ).shuffle(100).batch(batch_size).repeat() # + colab={"base_uri": "https://localhost:8080/"} id="XwZfF8scljgI" outputId="8630e466-07e2-47f1-c73e-a6aea38f7980" i = 0 for X, y in train_batch: #print(b) #X = b['image'] #y = b['label'] print('image {}, X shape {}, y shape {}'.format(i, X.shape, y.shape)) i += 1 if i > 1: break # + colab={"base_uri": "https://localhost:8080/", "height": 357} id="vNPXpR2Fmqu9" outputId="d875a486-ad80-4888-e21f-1250af08881c" fig = tfds.show_examples(train, imagenette_info, rows=2, cols=5) # + [markdown] id="z4E9okpEoTTD" # # Language datasets # # Various datasets are used in the natural language processing (NLP) communities. # # TODO: fill in. # + [markdown] id="fUu0R4_rSJ6O" # # Graveyard # # Here we store some scratch code that you can ignore, # + id="ZtLBfzVM5hVd" def get_datasets_mnist(): ds_builder = tfds.builder('mnist') ds_builder.download_and_prepare() train_ds_all = tfds.as_numpy(ds_builder.as_dataset(split='train', batch_size=-1)) test_ds_all = tfds.as_numpy(ds_builder.as_dataset(split='test', batch_size=-1)) num_train = len(train_ds_all['image']) train_ds['X'] = jnp.reshape(jnp.float32(train_ds_all['image']) / 255., (num_train, -1)) train_ds['y'] = train_ds_all['label'] num_test = len(test_ds_all['image']) test_ds['X'] = jnp.reshape(jnp.float32(test_ds['image']) / 255., (num_test, -1)) test_ds['y'] = test_ds_all['label'] return train_ds, test_ds # + colab={"base_uri": "https://localhost:8080/"} id="kaMqUR3ggBlx" outputId="7e091b7a-2729-4404-a2c0-127cd1ecd109" dataset = load_dataset_iris(tfds.Split.TRAIN, 30) batches = dataset.repeat().batch(batch_size) step = 0 num_minibatches = 5 for batch in batches: if step >= num_minibatches: break X, y = batch['image'], batch['label'] print('processing batch {} X shape {}, y shape {}'.format( step, X.shape, y.shape)) step = step + 1 # + colab={"base_uri": "https://localhost:8080/"} id="fFBvntfOgYpy" outputId="ff4eafed-1998-4751-f348-4e954d3df98d" print('batchified version v2') batch_stream = batches.as_numpy_iterator() for step in range(num_minibatches): batch = batch_stream.next() X, y = batch['image'], batch['label'] # convert to canonical names print('processing batch {} X shape {}, y shape {}'.format( step, X.shape, y.shape)) step = step + 1 # + id="H7QpYkxsgs6r" ds=tfds.as_numpy(train_ds) print(ds) for i, batch in enumerate(ds): print(type(batch)) X = batch['image'] y = batch['label'] print(X.shape) print(y.shape) i += 1 if i > 2: break ds = tfds.load('mnist', split='train') ds = ds.take(100) #ds = tfds.as_numpy(ds) batches = ds.repeat(2).batch(batch_size) print(type(batches)) print(batches) batch_stream = batches.as_numpy_iterator() print(type(batch_stream)) print(batch_stream) b = next(batch_stream) print(type(b)) print(b['image'].shape) b = batch_stream.next() print(type(b)) print(b['image'].shape) ds = tfds.load('mnist', split='train') batches = ds.repeat().batch(batch_size) batch_stream = batches.as_numpy_iterator() def process_stream(stream): b = next(stream) X = b['image'] y = b['label'] d = {'X': X, 'y': y} yield d my_stream = process_stream(batch_stream) b = next(my_stream) print(type(b)) print(b['X'].shape) b = my_stream.next() print(type(b)) print(b['X'].shape) # + id="4jmj_K2KSLwh" def sample_categorical(N, C): p = (1/C)*np.ones(C); y = np.random.choice(C, size=N, p=p); return y def get_datasets_rnd(): Ntrain = 1000; Ntest = 1000; D = 5; C = 10; train_ds = {'X': np.random.randn(Ntrain, D), 'y': sample_categorical(Ntrain, C)} test_ds = {'X': np.random.randn(Ntest, D), 'y': sample_categorical(Ntest, C)} return train_ds, test_ds def get_datasets_logreg(key): Ntrain = 1000; Ntest = 1000; D = 5; C = 10; W = jax.random.normal(key, (D,C)) Xtrain = jax.random.normal(key, (Ntrain, D)) logits = jnp.dot(Xtrain, W) ytrain = jax.random.categorical(key, logits) Xtest = jax.random.normal(key, (Ntest, D)) logits = jnp.dot(Xtest, W) ytest = jax.random.categorical(key, logits) train_ds = {'X': Xtrain, 'y': ytrain} test_ds = {'X': Xtest, 'y': ytest} return train_ds, test_ds
notebooks/datasets.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 # --- # + # #!pip3 install tweet-preprocessor # - import pandas as pd import re import nltk import preprocessor as pre words = set(nltk.corpus.words.words()) # # Only call the clean_tweets() function def helper_clean(text): ''' Helper function for tweet preprocessor to also remove &amp from tweet text. This function is intended for use with clean_tweets() and not independently. ''' return pre.clean(text).replace('&amp', '') def frac_nonenglish(text, frac=1): ''' Calculates fraction of nonenglish words in a given text. This function is intended for use with clean_tweets() and not independently. Can use smaller frac (e.g. 0.1) for faster clean_tweets() results but then the nonenglish words ratio will be calculated on a smaller fraction of text. ''' tokenizer = nltk.RegexpTokenizer(r'\w+') small_text = text[:round(len(text) * frac)] tokens = tokenizer.tokenize(small_text) word_count = len(tokens) nonenglish_count = 0 words = set(nltk.corpus.words.words()) for word in tokens: if word.lower() not in words: nonenglish_count += 1 return round(nonenglish_count/word_count, 4) def clean_tweets(df, frac=1): ''' Takes in a DataFrame object with 'text' column. Cleans the tweets by removing URLs, emojis, smileys and mentions. Stores the cleaned text in clean_text column. Calculates fraction of nonenglish words and stores the value in foreign_frac column. Can remove pre.OPT.EMOJI from options if we want to keep emojis. Returns a modified version of the input DataFrame. ''' pre.set_options(pre.OPT.URL, pre.OPT.EMOJI, pre.OPT.SMILEY, pre.OPT.MENTION) df['clean_text'] = df['text'].apply(helper_clean) df['foreign_frac'] = df['clean_text'].apply(frac_nonenglish) return df #RAW_CSV_PATH = df = pd.read_csv(RAW_CSV_PATH) cleaned_tweets = clean_tweets(df) cleaned_tweets.to_csv('cleaned_tweets.csv')
File_Processing/clean_tweets.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <a href="https://colab.research.google.com/github/davemlz/eemont/blob/master/tutorials/027-Panchromatic-Sharpening.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # # Panchromatic Sharpening # # _Tutorial created by_ [<NAME>](https://github.com/aazuspan) # - GitHub Repo: [https://github.com/davemlz/eemont](https://github.com/davemlz/eemont) # - PyPI link: [https://pypi.org/project/eemont/](https://pypi.org/project/eemont/) # - Conda-forge: [https://anaconda.org/conda-forge/eemont](https://anaconda.org/conda-forge/eemont) # - Documentation: [https://eemont.readthedocs.io/](https://eemont.readthedocs.io/) # - More tutorials: [https://github.com/davemlz/eemont/tree/master/tutorials](https://github.com/davemlz/eemont/tree/master/tutorials) # + [markdown] id="CD7h0hbi92Er" # ## Let's start! # + [markdown] id="E0rc6Cya92Es" # If required, please uncomment: # + id="NYzyvKtk92Es" # # !pip install eemont # # !pip install geemap # - # Import the required packges. # + id="H0C9S_Hh92Et" import ee, eemont, geemap # + [markdown] id="k1sdX2p592Eu" # Authenticate and Initialize Earth Engine and geemap. # + id="7QDXqVwy8Oef" Map = geemap.Map() # - # Some image platforms capture high resolution panchromatic data that can be used to increase the resolution of multispectral bands. Using eemont, supported `ee.Image` and `ee.ImageCollection` platforms can be sharpened using the `panSharpen()` method. # # __NOTE__: Supported platforms are TOA and raw reflectance products from Landsat 7 and Landsat 8. Unfortunately, surface reflectance products do not contain panchromatic bands and cannot be sharpened. # ## Sharpening a Landsat Image # Let's sharpen a single Landsat 8 image. First, we'll look at the original image at 30m resolution. # + img = ee.Image("LANDSAT/LC08/C01/T1_TOA/LC08_047027_20160819") Map.addLayer(img, dict(min=0, max=0.35, bands=["B4", "B3", "B2"]), "Landsat 8 - Original") pt = ee.Geometry.Point([-122.4100625, 47.2686875]) Map.centerObject(pt, zoom=15) Map # - # Now we'll use the `panSharpen()` method to increase the resolution of all sharpenable bands, creating a 15m resolution image. By toggling the sharpened image on and off, you can see how detail is added by pan-sharpening. sharp = img.panSharpen() Map.addLayer(sharp, dict(min=0, max=0.35, bands=["B4", "B3", "B2"]), "Landsat 8 - Sharp") Map # __NOTE__: eemont automatically filters out bands that don't support sharpening such as thermal, bitmasks, and the panchromatic band itself. The `panSharpen` method leaves only the sharpenable bands in the visible, NIR, and SWIR spectrums. # ## Sharpening Methods # There are many different algorithms that can be used to pan-sharpen imagery. `SFIM` (Smoothing Filter-based Intensity Modulation) is the default algorithm in eemont because it produces high quality output images, runs efficiently in GEE, and is tolerant of different band combinations, but users can experiment with other methods—`HPFA` (high-pass filter addition), `SM` (simple mean), and `PCS` (principal component substitution)—by setting the `method` argument. # ### HPFA # HPFA is similarly efficient to SFIM but generally produces less realistic sharpening. Try comparing the previous sharpened images (created with SFIM) to images sharpened with HFPA below. sharp = img.panSharpen(method="HPFA") Map.addLayer(sharp, dict(min=0, max=0.35, bands=["B4", "B3", "B2"]), "Landsat 8 - Sharp HPFA") Map # ### SM # SM is very fast, but it generally produces more spectral distortion than SFIM or HPFA due to its simplicity. sharp = img.panSharpen(method="SM") Map.addLayer(sharp, dict(min=0, max=0.35, bands=["B4", "B3", "B2"]), "Landsat 8 - Sharp SM") Map # ### PCS # PCS (sometimes referred to as PCA) is slower than other methods and may produce poor results depending on the image and band combinations. PCS requires calculating image statistics using the `ee.Image.reduceRegion` method, so additional keyword arguments can be passed through `panSharpen`. In this case, we'll pass a `maxPixels` argument to ensure statistics can be computed throughout the entire image, but we could also pass arguments like `geometry`, `scale`, `bestEffort`, etc. sharp = img.panSharpen(method="PCS", maxPixels=1e13) Map.addLayer(sharp, dict(min=0, max=0.35, bands=["B4", "B3", "B2"]), "Landsat 8 - Sharp PCS") Map # ## Sharpening Image Collections # Sharpening Image Collections is the same as sharpening Images. For example, let's sharpen a subset of the Landsat 8 collection. # Create a fresh map. Map = geemap.Map() # Add the first image of the unsharpened collection. # + img_collection = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA").filterBounds(pt).filterDate("2016", "2017") Map.addLayer(img_collection.first(), dict(min=0, max=0.35, bands=["B4", "B3", "B2"]), "Landsat 8 Collection - Original") pt = ee.Geometry.Point([-122.4100625, 47.2686875]) Map.centerObject(pt, zoom=15) Map # - # Now we'll sharpen the whole collection and visualize the first sharpened image. sharp_collection = img_collection.panSharpen() Map.addLayer(sharp_collection.first(), dict(min=0, max=0.35, bands=["B4", "B3", "B2"]), "Landsat 8 Collection - Sharp") Map # ## Quality Assessments # Image quality assessments (QA) measure the amount of spectral distortion caused by pan-sharpening and can help to select the best sharpening method. There are a wide variety of QA metrics for different applications. In eemont, QA metrics are calculated within the `panSharpen` method by passing a list of names to the `qa` argument. Results are added as properties to the sharpened image. # # Below, we'll re-sharpen the original image and calculate a variety of QA metrics at the same time. QA metrics calculate image statistics, so additional arguments may be needed that will be passed to `ee.Image.reduceRegion`. In the example below, we'll specify `maxPixels`. # # __NOTE__: By default, QA metrics are calculated throughout the entire image. To speed up calculation or avoid memory issues you can specify a `geometry` parameter to calculate image statistics within. # + metrics = ["RASE", "UIQI"] img = ee.Image("LANDSAT/LC08/C01/T1_TOA/LC08_047027_20160819") sharp = img.panSharpen(qa=metrics, maxPixels=1e13) # - # Calculated QA metrics can be retrieved from the sharpened image like any property. The property names always follow the format "eemont:{QA name}". Below, we see the `RASE` (Relative Average Spectral Error) value for the image sharpened with the default `SFIM` method. The ideal value for RASE is 0. sharp.get("eemont:RASE").getInfo() # Let's see how `RASE` compares when using `SM` sharpening. sharp_sm = img.panSharpen(method="SM", qa=metrics, maxPixels=1e13) sharp_sm.get("eemont:RASE").getInfo() # The higher `RASE` value in the `SM` image suggests more spectral distortion, so `SFIM` performed better. # ### Image-wise and Band-wise QA # `RASE` is an image-wise QA metric because it returns one value calculated for all bands together. Other QA metrics are band-wise and return one number for each band. Below, we'll see that the Universal Image Quality Index (`UIQI`) returns a quality value for each band. The ideal value for `UIQI` is 1. sharp.get("eemont:UIQI").getInfo() # Let's see how `UIQI` compares when using `SM` sharpening. sharp_sm.get("eemont:UIQI").getInfo() # Notice how `SM` performs similarly to `SFIM` in the visible spectrum (B2, B3, and B4), but performs much worse in the infrared spectrum (B5, B6, and B7) # ### Metrics # The list below describes all QA metrics available through eemont. # | Name | Full Name | Ideal Value | Axis | # |:-------|:--------------------------------------------------|-------------|-------| # | MSE | Mean Square Error | 0 | Band | # | RMSE | Root-Mean Square Error | 0 | Band | # | RASE | Relative Average Spectral Error | 0 | Image | # | ERGAS | Dimensionless Global Relative Error of Synthesis | 0 | Image | # | DIV | Difference in Variance | 0 | Band | # | bias | Bias | 0 | Band | # | CC | Correlation Coefficient | 1 | Band | # | CML | Change in Mean Luminance | 1 | Band | # | CMC | Change in Mean Contrast | 1 | Band | # | UIQI | Universal Image Quality Index | 1 | Band |
tutorials/027-Panchromatic-Sharpening.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: python3 # --- # ## Movie Reviews Sentiment Analysis # # **Outline** # # * [Introduction and dataset](#data) # * [Feature/Model variations](#model) # * [M1 - Unigrams (absence/presence)](#uni) # * [M2 - Unigrams with frequency count](#uni_multi) # * [M3 - Unigrams (only adjectives/adverbs)](#adjadv) # * [M4 - Unigrams (sublinear tf-idf), apply stopword removal](#tfidf) # * [tf-idf introduction](#tfidf_deets) # * [M5 - Bigrams (absence/presence)](#bigram) # * [Model learnings](#summary) # * [References](#ref) # + import os, glob import numpy as np import string, re from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer #leaving only the word stem from nltk import pos_tag from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.feature_extraction import text from sklearn.model_selection import cross_val_score from sklearn.metrics import classification_report, accuracy_score, make_scorer # - # ## <a id="data">Introduction and Dataset</a> # # The goal of this project is to classify moview review sentiments (positive or negative) using multinomial Naive Bayes, experiment with different language models and techniques along th way to evaluate performances and compare pros and cons of different methods. # # **Steps included:** # * Data read in # * Split into train/test before vectorization # * Clean corpus based on language model specs and apply additional techniques such as stop word removal, lemmatization as needed for best performance # * Train model and predict on test set # * Calculate accuracy score and compare # # Here's a graph from [Text Analytics for NLTK Beginners](https://www.datacamp.com/community/tutorials/text-analytics-beginners-nltk) that help illustrate the process: # ![Text Classification Process Flow](img/ta_flow_chart.png) # **Data Readin** # + # read a pos/neg dir # each document is a review corpus_folder = './data/review_polarity/txt_sentoken/' # Function to read one document def readFile(file_path): with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: tokenzied_words = f.read().split() return tokenzied_words def readDir(senti_folder, pattern, top_doc_num): """This funtion reads in data from the respective folder until filname starts with top_doc_num. Args: senti_folder: filepath to the corpus pattern: file name pattern top_doc_num: number included in file name to stop data read in Returns: Returns a list of the corpus. """ file_list = [] path_pattern = os.path.join(corpus_folder, senti_folder, pattern + '*.txt') all_txt_paths = glob.glob(path_pattern) for file_path in all_txt_paths[:top_doc_num]: # print(file_path) word_List = readFile(file_path) # print(word_List) file_list.append(word_List) return file_list #Read in train, test lists for pos and neg reviews, create train and test labels train_pos_file_list = readDir('pos', 'cv[0-8]', top_doc_num = 900) train_neg_file_list = readDir('neg', 'cv[0-8]', top_doc_num = 900) train_pos_labels = [1 for i in range(len(train_pos_file_list))] train_neg_labels = [0 for i in range(len(train_neg_file_list))] test_pos_file_list = readDir('pos', 'cv9', top_doc_num = 1000) test_neg_file_list = readDir('neg', 'cv9', top_doc_num = 1000) test_pos_labels = [1 for i in range(len(test_pos_file_list))] test_neg_labels = [0 for i in range(len(test_neg_file_list))] train_file_list = train_pos_file_list + train_neg_file_list test_file_list = test_pos_file_list + test_neg_file_list train_labels = train_pos_labels + train_neg_labels test_labels = test_pos_labels + test_neg_labels # - # ## <a id="model">Feature/Model variations</a> # **M1 - Unigrams (absence/presence)/Bernoulli Naive Bayes** # * training corpus: tokenized set of unique words that appeared in training corpus # * technique: Stop words removal, Porter Stemmer # # **M2 - Unigrams with frequency count** # * training corpus: tokenized entire vocabulary # * technique: Porter Stemmer # # **M3 - Unigrams (only adjectives/adverbs)** # * training corpus for training: set of tagged adjectives and adverbs only # * technique: Part of Speech (POS) Tagging # # **M4 - Unigrams (sublinear tf-idf), apply stopword removal** # * training corpus: tokenized entire vocabulary # * technique: Porter Stemmer # # **M5 - Bigrams (absence/presence)** # * training corpus: tokenized entire vocabulary # * technique: Porter Stemmer def clean_corpus(tokenized, model): """This funtion reads in data from each individual review in the training corpora and keeps words/features based on model specification Args: tokenized: individual review in training corpora (list of reviews) model: model type Returns: Returns a list of the corpus under model spec. """ #tokenize each document in training corpora punctuation_free = [x for x in tokenized if not re.fullmatch('[' + string.punctuation + ']+', x)] #Apply porter stemmer to selected models to only keep word stem ps = PorterStemmer() stemmed = [ps.stem(word) for word in punctuation_free] #unigrams with absence/presence if model == "m1": unique_stemmed = set(stemmed) return ' '.join(unique_stemmed) #Unigrams with only adjectives/adverbs elif model == "m3": #else: tags = ['JJ', 'JJR', 'JJS', 'RB', 'RBR', 'RBS'] all_tags = pos_tag(punctuation_free) result = [word[0] for word in all_tags if word[1] in tags] result2 = ' '.join(result) #print("output results for m3") return result2 #Unigrams with frequency count elif model == "m2" or "m4" or "m5": #print("output results for m2/4") return ' '.join(stemmed) def model_train_predict(train_clean, test_clean): #update list of stop words to include film, movie, etc that doesn't give signals to sentiment my_stop_words = text.ENGLISH_STOP_WORDS.union(["movie", "film", "movi", "hi"]) #Create features vectorizer = CountVectorizer(lowercase=True,stop_words=my_stop_words) #count word frequency train_features = vectorizer.fit_transform([doc for doc in train_file_list_clean]) test_features = vectorizer.transform([doc for doc in test_file_list_clean]) nb_clf = MultinomialNB() # Fit model and predict on test features nb_clf.fit(train_features, train_labels) predictions = nb_clf.predict(test_features) accuracy = accuracy_score(test_labels, predictions) return vectorizer, nb_clf, accuracy def show_most_informative_features(vectorizer, classifier, n=5): class_labels = classifier.classes_ feature_names = vectorizer.get_feature_names() topn_pos_class = sorted(zip(classifier.feature_count_[1], feature_names),reverse=True)[:n] topn_neg_class = sorted(zip(classifier.feature_count_[0], feature_names),reverse=True)[:n] print("Important words in positive reviews") for coef, feature in topn_pos_class: print(class_labels[1], coef, feature) print("-----------------------------------------") print("Important words in negative reviews") for coef, feature in topn_neg_class: print(class_labels[0], coef, feature) # ## <a id="uni">M1 - Unigrams (absence/presence)</a> # + # cleans each individual review and keeps word features based on model specification train_file_list_clean = [clean_corpus(doc, "m1") for doc in train_file_list] test_file_list_clean = [clean_corpus(doc,"m1") for doc in test_file_list] m1_vector = model_train_predict(train_file_list_clean, test_file_list_clean)[0] m1 = model_train_predict(train_file_list_clean, test_file_list_clean)[1] m1_accuracy = model_train_predict(train_file_list_clean, test_file_list_clean)[2] # - print("m1_accuracy is: ",m1_accuracy,) show_most_informative_features(m1_vector, m1) # ## <a id="uni_multi">M2 - Unigrams with frequency count</a> # + # cleans each individual review and keeps word features based on model specification train_file_list_clean = [clean_corpus(doc, "m2") for doc in train_file_list] test_file_list_clean = [clean_corpus(doc,"m2") for doc in test_file_list] m2_vector = model_train_predict(train_file_list_clean, test_file_list_clean)[0] m2 = model_train_predict(train_file_list_clean, test_file_list_clean)[1] m2_accuracy = model_train_predict(train_file_list_clean, test_file_list_clean)[2] # + print(m2_accuracy) show_most_informative_features(m2_vector, m2) # - # ## <a id="adjadv">M3 - Unigrams (only adjectives/adverbs)</a> # + # cleans each individual review and keeps word features based on model specification train_file_list_clean = [clean_corpus(doc, "m3") for doc in train_file_list] test_file_list_clean = [clean_corpus(doc,"m3") for doc in test_file_list] m3_vector = model_train_predict(train_file_list_clean, test_file_list_clean)[0] m3 = model_train_predict(train_file_list_clean, test_file_list_clean)[1] m3_accuracy = model_train_predict(train_file_list_clean, test_file_list_clean)[2] # + print(m3_accuracy) show_most_informative_features(m3_vector, m3) # - # ## <a id="tfidf">M4 - Unigrams (sublinear tf-idf), apply stopword removal</a> # + train_file_list_clean = [clean_corpus(doc, "m4") for doc in train_file_list] test_file_list_clean = [clean_corpus(doc,"m4") for doc in test_file_list] #update list of stop words to include film, movie, etc that doesn't give signals to sentiment my_stop_words = text.ENGLISH_STOP_WORDS.union(["movie", "film", "movi", "hi"]) # Create features for TF-IDF # min_df: ignore terms that have a document frequency strictly lower than defined, default=1 # max_df: ignore terms that have appear in more than 80% of the documents, default=1 vectorizer = TfidfVectorizer(min_df = 2, max_df = 0.8, stop_words=my_stop_words, sublinear_tf=True) train_features = vectorizer.fit_transform([doc for doc in train_file_list_clean]) test_features = vectorizer.transform([doc for doc in test_file_list_clean]) nb_clf = MultinomialNB() # Fit model and predict on test features nb_clf.fit(train_features, train_labels) predictions = nb_clf.predict(test_features) # + accuracy = accuracy_score(test_labels, predictions) print(accuracy) show_most_informative_features(vectorizer, nb_clf) # - # ## <a id="tfidf_deets">tf-idf introduction</a> # # **What is [Tf-idf](tfidf.come)?** # # Tf-idf stands for term frequency-inverse document frequency, and the tf-idf weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus. # # Variations of the tf-idf weighting scheme are often used by search engines as a central tool in scoring and ranking a document's relevance given a user query. # # **TF: Term Frequency** # TF measures how frequently a term occurs in a document. Since every document is different in length, it is possible that a term would appear many more times in long documents than shorter ones. Thus, the term frequency is often divided by the document length (aka. the total number of terms in the document) as a way of normalization. # # $$TF(t) = (NumberOfTimes_Term_t_AppearsInDoc)/(DocWordCount)$$ # # IDF: Inverse Document Frequency, which measures how important a term is. While computing TF, all terms are considered equally important. However it is known that certain terms, such as "is", "of", and "that", may appear a lot of times but have little importance. Thus we need to weigh down the frequent terms while scale up the rare ones, by computing the following: # # $$IDF(t) = log_e(TotalNumberOfDocs / NumberOfDocs_Term_t_AppearsIn)$$ # # **Example** # # Consider a document containing 100 words wherein the word **cat** appears 3 times: $tf=(3 / 100) = 0.03$ # # we have 10 million documents and the word **cat** appears in 1000 of these: $idf=log(10,000,000 / 1,000) = 4$ # # Thus, the Tf-idf weight is the product of these quantities: 0.03 * 4 = 0.12. # ## <a id="bigram">M5 - Bigrams (absence/presence)</a> # + # cleans each individual review and keeps word features based on model specification train_file_list_clean = [clean_corpus(doc, "m5") for doc in train_file_list] test_file_list_clean = [clean_corpus(doc,"m5") for doc in test_file_list] #Create features vectorizer = CountVectorizer(lowercase=True,ngram_range = (2,2), binary = True) #count word frequency train_features = vectorizer.fit_transform([doc for doc in train_file_list_clean]) test_features = vectorizer.transform([doc for doc in test_file_list_clean]) nb_clf = MultinomialNB() # Fit model and predict on test features nb_clf.fit(train_features, train_labels) predictions = nb_clf.predict(test_features) # + accuracy = accuracy_score(test_labels, predictions) print(accuracy) show_most_informative_features(vectorizer, nb_clf) # - # ## <a id="summary">Model learnings</a> # In this case, based on accuracy, the best performing model is **M1 Unigram absense/presence model with Porter Stemmer applied** with 86.5% in accuracy. The model is essentially a Bernoulli Naive Bayes model representing the feture vectors in a document with binary elements, in other words, whether a word in the vocabulary is present or not (1 or 0). # # Followed by **M5 Bigram with Porter Stemmer applied** with 85.5% in accuracy. # Followed by **M3 Unigram with adj/adv** with 85% in accuracy. # # The reason these these models performed the best could be that M1 only considers the absence or presence of each word therefore it does not weight more to words that appear the most frequent (M2, which was performed the worst). M2 uses bigram to create feature vectors, the phrases consisted of two words could give more signal to sentiments. M3 only considers the count of adjectives and adverbs that often more indicative of the sentiment of a review and therefore helps with precision. # ## <a id="ref">References</a> # * [Tf-idf](http://www.tfidf.com/) # * [Text Analytics for NLTK Beginners](https://www.datacamp.com/community/tutorials/text-analytics-beginners-nltk)
Text Analytics/MovieReviewSentimentAnalysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .coco # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Coconut [conda env:text-data-class] # language: coconut # name: conda-env-text-data-class-coconut # --- # %cat dvc.yaml # %cat params.yaml # %cat metrics.json !dvc exp diff exp-1fbbd # %cat multiclass_pipe.py
homework/hw2-goals-approaches/example/multiclass-example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import argparse import copy import json import os import sys try: import apex except: print("No APEX!") import numpy as np import torch from torch import nn import yaml from det3d import torchie from det3d.datasets import build_dataloader, build_dataset from det3d.models import build_detector from det3d.torchie import Config from det3d.torchie.apis import ( batch_processor, build_optimizer, get_root_logger, init_dist, set_random_seed, train_detector, example_to_device, ) from det3d.torchie.trainer import load_checkpoint import pickle import time from matplotlib import pyplot as plt from det3d.torchie.parallel import collate, collate_kitti from torch.utils.data import DataLoader import matplotlib.cm as cm import subprocess import cv2 from tools.demo_utils import visual from collections import defaultdict from det3d.torchie.trainer.utils import all_gather, synchronize from pathlib import PosixPath import glob # - def convert_box(info): boxes = info["gt_boxes"].astype(np.float32) names = info["gt_names"] assert len(boxes) == len(names) detection = {} detection['box3d_lidar'] = boxes # dummy value detection['label_preds'] = np.zeros(len(boxes)) detection['scores'] = np.ones(len(boxes)) return detection # + cfg = Config.fromfile('configs/nusc/pp/nusc_centerpoint_pp_02voxel_two_pfn_10sweep_demo_mini.py') model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg) dataset = build_dataset(cfg.data.val) data_loader = DataLoader( dataset, batch_size=1, sampler=None, shuffle=False, num_workers=8, collate_fn=collate_kitti, pin_memory=False, ) # + checkpoint = load_checkpoint(model, './latest.pth', map_location="cpu") model.eval() model = model.cuda() gpu_device = torch.device("cuda") cpu_device = torch.device("cpu") points_list = [] gt_annos = [] detections = {} detections_for_draw = [] points_list = [] token_list = [] # - # # Inference on nuScenes Mini dataset # + for i, data_batch in enumerate(data_loader): token = data_batch['metadata'][0]['token'] token_list.append(token) # save points data for tensorrt data_batch["points"].cpu().numpy()[:,1:].astype(np.float32).tofile( \ "./tensorrt/data/centerpoint/points/%s.bin"%token) # points_list for visulize points = data_batch['points'][:, 1:4].cpu().numpy() points_list.append(points.T) with torch.no_grad(): outputs = batch_processor( model, data_batch, train_mode=False, local_rank=0 ) info = dataset._nusc_infos[i] gt_annos.append(convert_box(info)) for output in outputs: token = output["metadata"]["token"] for k, v in output.items(): if k not in [ "metadata", ]: output[k] = v.to(cpu_device) detections_for_draw.append(output) detections.update( {token: output,} ) all_predictions = all_gather(detections) predictions = {} for p in all_predictions: predictions.update(p) result_dict, _ = dataset.evaluation(copy.deepcopy(predictions), output_dir="./", testset=False) if result_dict is not None: for k, v in result_dict["results"].items(): print(f"Evaluation {k}: {v}") # - # # Visualize Pytorch Results # + print('Done model inference. Please wait a minute, the matplotlib is a little slow...') vis_num = 10 draw_num = min(vis_num, len(points_list)) for i in range(draw_num): visual(points_list[i], gt_annos[i], detections_for_draw[i], i, save_path="demo/torch_demo") print("Rendered Image {}".format(i)) # - # # Evaluete TensorRT Result # 1. copy the ./tensorrt/data/centerpoint/points to <TensorRT root directory\>/data/centerpoint # 2. run the <TensorRT root directory\>/bin/centerpoint to get the tensorrt outputs. # 3. copy the <TensorRT root directory\>/data/centerpoint back the CenterPoint/tensorrt/data # 4. run the following python code to do evaluation and visualiza tensorrt result def read_trt_result(path): token = path.split("/")[-1].split(".")[0] trt_pred = {} with open(path) as f: trt_res = f.readlines() boxs = [] box3d = [] score = [] cls = [] for line in trt_res: box3d += [np.array([float(it) for it in line.strip().split(" ")[:9]])] score += [np.array([float(line.strip().split(" ")[-2])])] cls += [np.array([int(line.strip().split(" ")[-1])])] trt_pred["box3d_lidar"] = torch.from_numpy(np.array(box3d)) trt_pred["scores"] = torch.from_numpy(np.array(score)) trt_pred["label_preds"] = torch.from_numpy(np.array(cls,np.int32)) trt_pred["metadata"] = {} trt_pred["metadata"]["num_point_features"] = 5 trt_pred["metadata"]["token"] = token return trt_pred, token points_dict = {} points_list = [] gt_annos_dict = {} for i, data_batch in enumerate(data_loader): token = data_batch['metadata'][0]['token'] points = data_batch['points'][:, 1:4].cpu().numpy() points_dict[token] = points.T info = dataset._nusc_infos[i] gt_annos_dict[token] = convert_box(info) # + trt_pred = {} detections = {} detections_for_draw = [] gt_annos = [] res_path_list = glob.glob("./tensorrt/data/centerpoint/results/*.txt") output_dict = {} for path in res_path_list: output, token = read_trt_result(path) output_dict[token] = output for token in token_list: points_list.append(points_dict[token]) gt_annos.append(gt_annos_dict[token]) output = output_dict[token] for k, v in output.items(): if k not in [ "metadata", ]: output[k] = v detections_for_draw.append(output) detections.update( {token: output,} ) all_predictions = all_gather(detections) predictions = {} for p in all_predictions: predictions.update(p) result_dict, _ = dataset.evaluation(copy.deepcopy(predictions), output_dir="./", testset=False) if result_dict is not None: for k, v in result_dict["results"].items(): print(f"Evaluation {k}: {v}") # - # # Visualize TensorRT Result print('Done model inference. Please wait a minute, the matplotlib is a little slow...') vis_num = 10 draw_num = min(vis_num, len(points_list)) for i in range(draw_num): visual(points_list[i], gt_annos[i], detections_for_draw[i], i, save_path="demo/trt_demo") print("Rendered Image {}".format(i))
TensorRT_Visualize.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 # --- # # Optimization algorithms # # ## Stochastic Gradient Descent (SGD) # # ### Gradient update equation # # $$ # \hat{g} \leftarrow \frac{1}{m} \nabla_{\theta} \left( \sum_i L(f(x^{(i)}); \theta), y^{(i)} \right)\\ # \theta \leftarrow \theta - \epsilon \hat{g} # $$ # # ### Why stochastic? # # Batch gradient descent requires computing the gradients for the entire dataset at each iteration (e.g., setting the sum in the above equation to $N$, where $N$ is the number of samples in the dataset). This has a very high computational cost with large datasets. Conversely, we can compute gradients is to approximate it using a single sample at a time and update the model parameters $\theta$ based on this gradient. However, by doing this we might be "throwing away" computational resources, as it's often more efficient to compute gradients for a few samples in parallel (using matrix-matrix operations instead of matrix-vector operations). # # Minibatch stochastic gradient descent (mostly called just stochastic gradient descent nowadays) explores the tradeoff between using larger batches to get more accurate gradient estimates and explore parallelism, while not needing to compute the output for the entire dataset for a single parameter update. Often the minibatch size is chosen considering hardware characteristics (e.g., GPUs have better performance when using power of two minibatch sizes due to the way matrix multiplies is performed). # ## Learning rate decay # # Due to the noisy gradients obtained by SGD, we often cannot use a fixed learning rate to update the parameters of our model. A common practice is to start with a given learning rate and then decay it exponentially at every epoch until it reaches an arbitrary minimum, or keep it fixed for a few epochs before decreasing it. On Keras, learning rate decay is implemented as a callback (`keras.callbacks.LearningRateScheduler`), which gets as an argument a Python function `f(epoch)` which returns the learning rate to be used for that epoch. # ## Momentum # # Momentum introduces a *velocity* variable which makes the parameters keep moving at the direction gradients from previous iterations pointed to: # # $$ # v \leftarrow \alpha v - \epsilon \frac{1}{m} \nabla_{\theta} \left( \sum_i L(f(x^{(i)}); \theta), y^{(i)} \right)\\ # \theta \leftarrow \theta - \epsilon \hat{g} # $$ # # where $ 0 \leq \alpha < 1$ controls how quickly the contributions of previous gradients exponentially decay. # # There are two algorithms which incorporate momentum: standard and Nesterov momentum. The difference between Nesterov momentum and standard momentum is where the gradient is evaluated: with Nesterov momentum, the gradient is computed at an interim point (the point we would go to if we did not update the velocity), while with standard momentum the gradient is computed at the current point (as shown in the equations above). # ## Adaptive learning rate # # Learning rate is one of the most important hyperparameters to set for training a DNN as it has a significant impact on model performance. Also, often the choice of a single learning rate for all parameters in our model is not the best, as different parameters have different sensitivities. The adaptive learning rate approach uses separate learning rates for each parameter, and automaticallty adapts these rates during training (as it would be insane trying to find optimal values for each parameter on your own!). # # Keras includes several adaptive learning rate algorithms: # # - RMSprop # - Adagrad # - Adadelta # - Adam # - Nadam # # If in doubt, RMSprop and Adam with the default parameters are often a good starting point. # ## References # # - [Intro to gradient descent](http://cs231n.github.io/optimization-1/) # - [Nice blog post about the "evolution" of optimizers and their characteristics](http://sebastianruder.com/optimizing-gradient-descent/index.html) # - [Chapter 8 of the Deep Learning Book - Optimization for Training Deep Models](http://www.deeplearningbook.org/contents/optimization.html)
notebooks/4 - Optimization algorithms.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 # --- # [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/luisar/tweets-retrieval-tweepy/blob/main/get_tweets.ipynb) # + [markdown] id="23graN93DDgR" # # Get Tweets # # This script gets all tweets of whichever hashtag is given to it. It only retrieves the tweets from the current day (today) and yesterday. It is then saved into a .csv file. # # This is done using the `tweepy` library. The `twitter_config.py` file is not included but should be created in the same directory of this file, in order to access the Twitter API. # # In order to access it via Google Colab, you need to define a variable with the path location and then call `sys.path.append(os.path.abspath(fileLocaltion)`. # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 3721, "status": "ok", "timestamp": 1648396475233, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="P5FDifAVBIaH" outputId="8630ad4b-d2ce-4241-b5be-3a01ba1450a1" from google.colab import drive drive.mount('/content/drive', force_remount=True) # + id="gj5AbuMID2an" # !pip install tweepy # + executionInfo={"elapsed": 363, "status": "ok", "timestamp": 1648397692104, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="MezFRua_ExRi" import tweepy import os, sys, datetime import pandas as pd # + executionInfo={"elapsed": 307, "status": "ok", "timestamp": 1648396416642, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="Ajjt0osIEYBs" py_file_location = "path/to/colab" sys.path.append(os.path.abspath(py_file_location)) # + executionInfo={"elapsed": 409, "status": "ok", "timestamp": 1648396476410, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="sDhKwsjuDAsB" from twitter_config import * # + [markdown] id="4G8dmXtSFyBM" # # Setup a Connection # + executionInfo={"elapsed": 298, "status": "ok", "timestamp": 1648396576809, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="DC7k2Wj3Fxcd" auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET) auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True) # + [markdown] id="oG1rn6KPGLjr" # # Create Variables + Search Tweets # # Tweets are searched with the the [Cursor()](https://docs.tweepy.org/en/v3.8.0/cursor_tutorial.html) function. # # Basically the api.search param is passed to Cursor() to do its magic. From the docs, these are some of the available params: # # * from: Get a specific user profile # * since: From where should the search start (date) # * until: Until when should the search go (date) # # Alongside this, other params can be used like `language` (self explanatory) and `tweet_mode = extended` which means it'll return the whole tweet instead of just the first 140 chars. # # You can also do `api.user_timeline` instead of `api.search` to get a particular timeline. # # You can also be specific about the location by doing (taken from [Twitter Docs](https://developer.twitter.com/en/docs/tutorials/filtering-tweets-by-location): # # * place - the place name or the place ID # * place_country - the country code. See here to see the country code # * point_radius - the circular geographic area within which to search for # * bounding_box - the 4 sided geographic area, within which to search for # # Like: # # ``` # place = 'Mexico' # tweets_list = tweepy.Cursor(api.search, q="place: " + place,tweet_mode='extended', lang='es').items() # ``` # + executionInfo={"elapsed": 2, "status": "ok", "timestamp": 1648398145828, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="54daYke-F7Rg" today = datetime.date.today() yesterday= today - datetime.timedelta(days = 1) hashtag = "#covid" userHandle = "finkd" # + executionInfo={"elapsed": 3, "status": "ok", "timestamp": 1648398148173, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="XoCl3OxeG-Ex" tweets_list = tweepy.Cursor(api.search, q = hashtag, since = str(yesterday), until = str(today), tweet_mode='extended', lang='es').items() #id = "<user_id>" #verify = False #tweets_list = tweepy.Cursor(api.search, q="from: " + userHandle, tweet_mode = 'extended', lang = 'en').items() # + [markdown] id="Y2MhROljJaug" # # Scanning the Tweets # # Simply do a `for in` loop over the list of tweets and, out of each, extract the text, date, number of retweets, and favorite count. # # Everything is stored in a new list called `to_write`. # + id="oeDeLJS8JX9I" to_write = [] for tweet in tweets_list: text = tweet._json["full_text"] print(text) favourite_count = tweet.favorite_count retweet_count = tweet.retweet_count created_at = tweet.created_at line = {'text' : text, 'favourite_count' : favourite_count, 'retweet_count' : retweet_count, 'created_at' : created_at} to_write.append(line) # + [markdown] id="0Zhxje2DKNFF" # # Pandas and Save # # Finally convert the list to a Pandas DataFrame and save the output. # + executionInfo={"elapsed": 242, "status": "ok", "timestamp": 1648398200184, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="yufbIMDEKSys" df = pd.DataFrame(to_write) # + colab={"base_uri": "https://localhost:8080/", "height": 363} executionInfo={"elapsed": 11, "status": "ok", "timestamp": 1648398201146, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="nxvcYlEPKbFA" outputId="079f257a-ac27-4e90-8097-a2fd7b9465ca" df.head(10) # + executionInfo={"elapsed": 238, "status": "ok", "timestamp": 1648398208808, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgbyPbIOkknlF2HfyB-_6wt2Lyut2LHBti3K80kKFc=s64", "userId": "12434900024241330662"}, "user_tz": -120} id="EmAP63FTKflV" df.to_csv(py_file_location + 'tweets.csv', mode='a', header=False)
get_tweets.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 # --- # + # %matplotlib inline import gzip import json import os import matplotlib import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import figure from matplotlib.ticker import FuncFormatter import collections as c; Release = c.namedtuple('Release', ['tag', 'sections', 'percentage_sections']) GOLDEN = (1 + 5 ** 0.5) / 2 URL = "https://github.com/udoprog/kernelstats" def load_stats(d): out = [] for n in sorted(os.listdir(d)): with gzip.open(os.path.join(d, n)) as f: data = json.load(f) v = tuple(map(int, data['tag'][1:].split('.'))) out.append((v, data)) return list(v[1] for v in sorted(out, key=lambda v: v[0])) def millions(x, pos): return '%1.1fM' % (x * 1e-6) def percentages(x, pos): return '%d%%' % (x * 100) # + stats = load_stats("stats") lang_filter = set([ 'Assembly', 'C', 'CHeader', 'Makefile', 'Cpp', 'CppHeader', 'Sh', 'Python', 'Perl', 'Ruby', ]) separate_set = set([ "drivers", "fs", "net", "drivers/gpu", "drivers/net", "drivers/media", ]) important_set = set([]) important_name = ", ".join(sorted(important_set)) ignored = set([ 'Documentation', 'scripts', 'lib', ]) arch_whitelist = set([ 'i386', 'x86', 'x86_64', ]) arch_whitelist_name = "arch/x86" keys = set() releases = [] def section_name(parts): """ Calculate a section name from a set of parts. """ # not a directory if len(parts) <= 2: return None name = parts[1] if name == "arch": if len(parts) >= 3: arch = parts[2] if arch in arch_whitelist: return arch_whitelist_name else: return "arch/other" raise Exception("bad arch: " + repr(parts)) if name == "drivers": if len(parts) >= 3: sub_name = name + '/' + parts[2] if sub_name in separate_set: return sub_name return name if name in separate_set: return name if name in important_set: return important_name return "other" for s in stats: sections = c.defaultdict(int) for (lang, data) in s['all'].items(): file_s_array = data['reports'] if 'reports' in data else data['stats'] for file_s in file_s_array: parts = file_s['name'].split('/') name = section_name(parts) if name is None: continue if lang not in lang_filter: continue if 'code' in file_s: # legacy format sections[name] += file_s['code'] else: sections[name] += file_s['stats']['code'] + file_s['stats']['blanks'] + file_s['stats']['comments'] keys.add(name) percentage_sections = dict() total = sum(s for s in sections.values()) for (name, value) in sections.items(): percentage_sections[name] = value / total releases.append(Release( tag=s['tag'], sections=sections, percentage_sections=percentage_sections, )) legends = [] datasets = [] percentage_datasets = [] tags = [r.tag for r in releases] for key in sorted(keys): if key in ignored: continue values = [] percentage_values = [] for r in releases: try: lines = r.sections[key] except KeyError: lines = 0 values.append(lines) try: percentage_lines = r.percentage_sections[key] except KeyError: percentage_lines = 0 percentage_values.append(percentage_lines) datasets.append(values) percentage_datasets.append(percentage_values) legends.append(key) # - def stack_plot(legends, datasets, width=16, formatter=millions, styles=[]): with plt.style.context(['seaborn-muted'] + styles): figure(num=None, figsize=(width * GOLDEN, width), dpi=80, facecolor='w', edgecolor='k') plt.gca().yaxis.set_major_formatter(FuncFormatter(formatter)) width = 0.6 plt.grid(True, axis='y') bottom = None for dataset in datasets: kw = dict() if bottom is None: bottom = dataset else: kw['bottom'] = list(bottom) # calculate next bottom. bottom = [a + b for (a, b) in zip(bottom, dataset)] plt.bar(tags, dataset, width, **kw) plt.title("Lines of code in the Linux kernel\nGenerated using {}".format(URL)) plt.legend(legends, loc='upper left') plt.xticks(rotation=45) stack_plot(legends, datasets, width=20, formatter=millions, styles=['tableau-colorblind10']) plt.savefig('kernelstats-millions.png') stack_plot(legends, percentage_datasets, width=20, formatter=percentages, styles=['tableau-colorblind10']) plt.savefig('kernelstats-percentages.png')
Plot Kernel Stats.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 # --- # + """ Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? """ """ This seems to be Ulam's Spiral. https://oeis.org/search?q=1%2C3%2C5%2C7%2C9%2C13%2C17%2C21%2C25%2C31%2C37&sort=&language=english&go=Search Formula (c) <NAME>: a(n) = floor_(n*(n+2)/4) + floor_(n(mod 4)/3) + 1 n = math.floor(n*(n+2)/4) + math.floor((n%4)/3) + 1 also: For k>=0, the sequence is all numbers of the following three forms: (2k+1)^2, 4*k^2+1 and k^2+k+1. When k>=1, all values of a(n) are uniquely generated by these three forms. When k>=1 and n>=2, a(n) is: 1. (2k+1)^2 when n==1(mod 4); 2. 4*k^2+1 when n==3(mod 4); and 3 k^2+k+1 when n is even. Anyway, seems easier to do (n+2) every 4 times """ # + from math import floor n=2 while n < 50: n = floor(n*(n+2)/4) + floor((n%4)/3) + 1 print(n) # -
Project_Euler-Problem_18-Number_spiral_diagonals.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 scipy import signal import matplotlib.pyplot as plt import matplotlib as mpl import glob, os # + def angleCorloredTrajectory(x_gauss, y_gauss, circ_r, angle): plt.style.use('default') fig = plt.figure() ax = plt.gca() ax.set_facecolor('black') c1 = plt.Circle((0, 0), circ_r, facecolor='linen', alpha = 0.7, edgecolor='none', zorder = -3) ax.add_artist(c1) plt.scatter(x_gauss, y_gauss, s=7 , c = angle, cmap = plt.cm.cool, zorder = 1) ax.set_aspect('equal', adjustable = 'datalim') ax.tick_params(axis = 'both', which = 'both', bottom = False, left = False, labelbottom = False, labelleft = False) # add this line for representative plots # ax.set_ylim(-0.5,2.5) cbar = plt.colorbar() return(fig) def angleColoredSweepCurves(r_gauss, circ_r, angle): fig = plt.figure(figsize = (5,5)) ax = plt.gca() t0 = np.arange(len(r_gauss))*1/100 plt.scatter(t0, r_gauss, s = 10, c = angle, cmap = plt.cm.jet) # add these lines for representative plots # plt.xlim(-circ_r*2.5, circ_r*2.5) # plt.ylim(-circ_r*2.5, circ_r*2.5) cbar = plt.colorbar() return(fig) # - visitnum = ['FirstVisit/','Later7thVisit/' ,'LaterVisit/', 'LastVisit/'] for visit in visitnum[1:2]: direc = os.path.join(r"../dataFolders/PaperPipelineOutput/RadiusAndAngle_v2/", visit) datalist = glob.glob(direc + '*.csv') outpath = os.path.join('../dataFolders/PaperPipelineOutput/Figures/v2/AngleAndRadius', visit) try: os.mkdir(outpath) except OSError: print('oops') circ_parameters_path = glob.glob('../dataFolders/PaperPipelineOutput/CircleParameters/' + '*.csv') circ_parameters = pd.read_csv(circ_parameters_path[0]) full_name = circ_parameters.name.str.split('_', expand = True) circ_parameters['mothID'] = full_name[0] + '_' + full_name[1] # + for file in datalist: _,moth = os.path.split(file) name = moth[:-19] # matched = [n for n in circ_parameters.name if name in n] circ_r = circ_parameters.loc[circ_parameters.mothID == name, 'circ_radii'].values df = pd.read_csv(file) x = df.loc[:, 'x_centered'].values y = df.loc[:, 'y_centered'].values r = df.loc[:,'radial_distance_normalized'] angle = df.loc[:,'angle'].values f1 = angleCorloredTrajectory(x, y, circ_r, angle) f2 = angleColoredSweepCurves(r, circ_r, angle) f1.savefig(outpath + name + '_AngleColoredTrajectory_' + visit[:-1] + '.png') f2.savefig(outpath + name + '_AngleColoredRadialDistance_' + visit[:-1] + '.png') plt.close('all') # - df.head() # # draw representative plots names_first = ['c-1_m17', 'c-2_m23', 'c-3_m10', 'c-10_m11'] names_last = ['c-1_m14', 'c-2_m12', 'c-3_m10', 'c-10_m11'] names = [names_first, names_last] # + # f1, ax = plt.subplots(1,4, figsize = (15,4), sharex = True, sharey = True) # ax = ax.ravel() ii = 0 for visit, n in zip(visitnum, names): print(visit) direc = os.path.join(r"../dataFolders/PaperPipelineOutput/RadiusAndAngle_v2/", visit) datalist = glob.glob(direc + '*.csv') for name in n: print(name) data = [f for f in datalist if name in f][0] df = pd.read_csv(data) circ_r = circ_parameters.loc[circ_parameters.mothID == name, 'circ_radii'].values x = df.loc[:, 'x_centered'].values y = df.loc[:, 'y_centered'].values r = df.loc[:,'radial_distance_normalized'] angle = df.loc[:,'angle'].values f1 = angleCorloredTrajectory(x, y, circ_r, angle) ax1 = f1.gca() ax1.set_xlim(-circ_r*2.5, circ_r*2.5) ax1.set_ylim(-circ_r*2.5, circ_r*2.5) plt.savefig('../dataFolders/PaperPipelineOutput/Figures/v2/projectionOnFlower_forTalk_' + visit[:-1] + '_' + name + '.png') f2 = angleColoredSweepCurves(r, circ_r, angle) ax2 = f2.gca() ax2.set_ylim(-0.05, 2.5) namef2 = '../dataFolders/PaperPipelineOutput/Figures/v2/sweeps_forTalk_' + visit[:-1] + '_' + name + '.png' plt.savefig(namef2) # plt.savefig('../dataFolders/PaperPipelineOutput/Figures/v2/projectionOnFlower_forTalk_' + visit[:-1] + '_' + name + '.png', f1) # -
PaperPinelineCodes/3-DrawFigures.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/jegun19/predictive_maintenance/blob/main/train_forecasting.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="mdLqHkr3S2n0" # # Prerequisites # ## Required steps: # <ol type="I"> # <li>Install Kaggle API in Colab Environment</li> # <li>Upload API token from Kaggle in .json file </li> # <li>Download dataset from Kaggle</li> # # --- # + [markdown] id="hzkrdQvSVa-g" # ## Connect to Kaggle # ### First, install the Kaggle API in our environment and upload the API token file in form of .json file. Refer to this [link](https://www.kaggle.com/general/51898) # + id="dhateS_nOnx3" # !pip install -q kaggle # + id="n_OcKMRYRJRu" from google.colab import files files.upload() # + [markdown] id="mhoUeGj2Y6Hi" # ## Prepare local environment # ### Second, create directory in our environment to allow access to kaggle dataset. # + id="o4qy5j41RNM1" # !mkdir ~/.kaggle # + id="qt07FNX_RR52" # !cp kaggle.json ~/.kaggle/ # + id="0-qxcHBnRSeF" # !chmod 600 ~/.kaggle/kaggle.json # + [markdown] id="NrB6Ttw2aBPY" # If everything goes well, we should be able to see list of datasets available # + colab={"base_uri": "https://localhost:8080/"} id="b34S7nSDRUI0" outputId="b202c070-4f01-4b26-8e24-8b86791b556d" # !kaggle datasets list # + [markdown] id="tsyLtpIUaHz8" # Then, we can use the following command to download the dataset that we are going to use # + colab={"base_uri": "https://localhost:8080/"} id="P_NQ9QzBRV21" outputId="1d293d1c-6643-4c15-b452-e96ed9f07b61" # !kaggle datasets download -d arnabbiswas1/microsoft-azure-predictive-maintenance # + id="0Hu-QN7lSn9f" # !mkdir pdm_data # + colab={"base_uri": "https://localhost:8080/"} id="5UZPCtKlSqBU" outputId="e1cbf5a3-c20b-42ae-c2e9-46f8b4272f59" # !unzip microsoft-azure-predictive-maintenance.zip -d pdm_data # + [markdown] id="6hCA6JpEz8st" # # # --- # # # # Data Exploration # # + [markdown] id="OOteJJR72RkO" # ## Select one machine # In this step, we will take a look at the overall characteristic of the data, and then select one machine that we want to analyze and use for doing the predictive maintenance task. # + id="RX1kQLmgruzB" # Load all csv datas using pandas import os import pandas as pd WORKING_DIR = os.getcwd() df_tele = pd.read_csv(WORKING_DIR + '/pdm_data/PdM_telemetry.csv') df_fail = pd.read_csv(WORKING_DIR + '/pdm_data/PdM_failures.csv') df_err = pd.read_csv(WORKING_DIR + '/pdm_data/PdM_errors.csv') df_maint = pd.read_csv(WORKING_DIR + '/pdm_data/PdM_maint.csv') # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="6k9WNzPvwiqR" outputId="5f0e2e46-524d-43f3-de71-6c3b986a100b" # print the top 5 rows from the failure dataframe df_fail.head(n=5) # + [markdown] id="-h9jOb3tiCts" # For simplicity purpose, we will select a single machine that we are going to use for analysis. In this notebook, we will select machine number 11. # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="EvXf66ztjKH-" outputId="a905ce0a-130d-4be0-b84e-f1e7616ee0c7" df_sel = df_tele.loc[df_tele['machineID'] == 11].reset_index(drop=True) df_sel.head(n=5) # + [markdown] id="trcykf7_lL7C" # Then, we will look into the error and failure record and then filter it only to show records belonging to machine number 11. # + colab={"base_uri": "https://localhost:8080/", "height": 238} id="Rkv3-o-plLHf" outputId="fb5383b7-be2e-49b8-ecf2-57af8db64342" # Check failure record of machine 11 sel_fail = df_fail.loc[df_fail['machineID'] == 11] pd.DataFrame(sel_fail) # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="kJjsv5YvmbcP" outputId="053a4271-7682-4b14-f9b5-04a1c25df458" # Check error record of machine 11 sel_err = df_err.loc[df_err['machineID'] == 11] pd.DataFrame(sel_err).head() # + [markdown] id="Y2V0ctzU5uj-" # From the explanation regarding the difference between failure and error in Kaggle, it is described that error refers to non-breaking events while failure refers to events that cause the machine to fail. Then, we will see in chronological plot how does the two events relate to each other. # + colab={"base_uri": "https://localhost:8080/", "height": 303} id="DvgZHmPJo9dq" outputId="0c354ef6-d94a-46ed-8946-2a9994f2e0dd" import matplotlib.pyplot as plt import matplotlib.dates as mdates fig, ax = plt.subplots() # For a simpler plot, we will use two different values in the y-axis to differentiate between error and failure y_category = list() for iter in range(0, len(sel_fail)): y_category.append('Failure') for iter in range(0, len(sel_err)): y_category.append('Error') # Get timestamp from error and selected failure df_timestamp = pd.concat([sel_fail['datetime'], sel_err['datetime']], ignore_index=True, axis=0) df_plot = pd.DataFrame({"timestamp": df_timestamp, "category": y_category}) df_plot.loc[:, 'timestamp'] = pd.to_datetime(df_plot.loc[:, 'timestamp']) df_plot.sort_values(by=['timestamp'], inplace=True, ignore_index=True) # Plot the data with timestamp as x-axis ax.scatter('timestamp', 'category', data = df_plot) yearfmt = mdates.DateFormatter('%Y-%m-%d') ax.xaxis.set_major_formatter(yearfmt) ax.tick_params(axis='x', rotation=45) ax.grid() # + [markdown] id="C4xm9S6frtQB" # From the plot above, we can see that failures are oftentimes preceded by error in the machine. However, not all error result in immediate failures. Some time may passes before the failure in machine occurs. Thus, in the next step, we are going to focus on the failure data and check which feature is affected by machine's failure. # + [markdown] id="UvOmc0UJ2cr1" # ## Feature check # Here, we will select the time window from the failure record, then plot each feature and check their response in the event of failures. # + colab={"base_uri": "https://localhost:8080/", "height": 334} id="ZWZnU_AgIpAi" outputId="e222d97b-c037-4eb3-f12f-2c6ef9f64f8b" # Change datatype of the timestamp column from object to datetime df_sel.loc[:, 'datetime'] = pd.to_datetime(df_sel.loc[:, 'datetime']) # Select the date to check from failure records st = df_sel.loc[df_sel['datetime'] == "2015-02-19"].index.values[0] # Then, filter the telemetry data by the date and allow 7 days before and after # the error occurs to observe any abnormalities. select = df_sel.loc[st-7*24:st + 7*24,:] # Plot volt and rotation feature fig, ax = plt.subplots(nrows=2, sharex=True) ax[0].plot('datetime', 'volt', data=select) ax[0].set_ylabel("Volt") ax[1].plot('datetime', 'rotate', data=select) ax[1].tick_params(axis='x', rotation=45) ax[1].set_xlabel("Timestamp") ax[1].set_ylabel("Rotation") # + [markdown] id="V9vDO8bd8xKy" # As we observe volt and rotation readings, no noticeable anomalies are shown around the period of 2015-02-19. Then, next we will check both pressure and vibration features by plotting them. # + colab={"base_uri": "https://localhost:8080/", "height": 338} id="P6hQiqWM7O5_" outputId="0dce06ce-6f1f-4072-e34d-61d7b519a0a4" # Plot pressure and vibration feature fig, ax = plt.subplots(nrows=2, sharex=True) ax[0].plot('datetime', 'pressure', data=select) ax[0].set_ylabel("Pressure") ax[1].plot('datetime', 'vibration', data=select) ax[1].tick_params(axis='x', rotation=45) ax[1].set_xlabel("Timestamp") ax[1].set_ylabel("Vibration") # + [markdown] id="T7futjFH4bQP" # Between pressure and vibration, abnormality around the period of 2015-02-19 is more noticeable. Thus, in the next step, we will use <font color='red'>**pressure**</font> as feature and predictor. # + [markdown] id="iVtbSdTxTERQ" # ## Check autocorrelation and partial autocorrelation # In time-series data, it is beneficial to check the autocorrelation and partial autocorrelation function of the data that will influence our model selection and parameter selection. # + colab={"base_uri": "https://localhost:8080/", "height": 336} id="8R-czbawE5Qc" outputId="53ed966f-c773-4a9d-e9d0-f076f0ef855d" # Import plotting function from statsmodels.graphics.tsaplots import plot_acf, plot_pacf # Autocorrelation plot plot_acf(df_sel['pressure'], lags = 40) plt.show() # + [markdown] id="HB5tuKHwUJcT" # From the autocorrelation plot, we can see that the data is positively correlated up to lags of 40, where the autocorrelation value itself is quite low, indicating that the data does not have a strong autocorrelation properties. # + colab={"base_uri": "https://localhost:8080/", "height": 281} id="EUkV06CvTfYr" outputId="2857a324-b1d9-48ce-9d59-8b61babc8873" # Partial autocorrelation plot plot_pacf(df_sel['pressure'], lags = 40) plt.show() # + [markdown] id="tUD73azOVQre" # From the partial autocorrelation plot, the correlation between values of two different points in time is also quite weak, decaying to zero starting in the 15th lags. This information will be used in determining the lag in the model. # + [markdown] id="7SusXIUbVkbi" # # Model Selection # + [markdown] id="1wTZ59qWVn2j" # ## Prepare data input and output # In this notebook, we will use LSTM model, one of the famous prediction model in time-series forecasting task. To use it, first we need to provide input and output data in the correct format. # + [markdown] id="2Jga826wa2CM" # For our experiment, we will use training data of 1 month containing 2015-02-19 period where failure happened to predict another failure which occurs at 2015-04-20 according to the failure record. The feature used will be the pressure reading and timestamp (one-hot encoded). # + id="UX1IkHxKVNbL" import numpy as np from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split # Select the date to check from failure records st_train = df_sel.loc[df_sel['datetime'] == "2015-02-19"].index.values[0] # Then, filter the data to include approximately one month window start_period = st_train - 14*24 end_period = st_train + 14*24 def create_feature(start, end): # create features from the selected machine pressure = df_sel.loc[start: end, 'pressure'] timestamp = pd.to_datetime(df_sel.loc[start: end, 'datetime']) timestamp_hour = timestamp.map(lambda x: x.hour) timestamp_dow = timestamp.map(lambda x: x.dayofweek) # apply one-hot encode for timestamp data timestamp_hour_onehot = pd.get_dummies(timestamp_hour).to_numpy() # apply min-max scaler to numerical data scaler = MinMaxScaler() pressure = scaler.fit_transform(np.array(pressure).reshape(-1,1)) # combine features into one feature = np.concatenate([pressure, timestamp_hour_onehot], axis=1) X = feature[:-1] y = np.array(feature[5:,0]).reshape(-1,1) return X, y, scaler X, y, pres_scaler = create_feature(start_period, end_period) # + [markdown] id="Y4yPsCrTcJiz" # Then, we need to shape the input further into a sequence (3-dimensional numpy array). We will use a function to return input and output sequence where each input sequence consists of 5-points observation. Simply put, observations of the <font color='red'>**past five hours**</font> will be used to predict the sensor reading for the next <font color='red'>**one hour**</font> . # + colab={"base_uri": "https://localhost:8080/"} id="MFpn0B0ZcI_B" outputId="ec062d54-3dc4-4eb1-aa77-62adcd73b180" def shape_sequence(arr, step, start): out = list() for i in range(start, arr.shape[0]): low_lim = i up_lim = low_lim + step out.append(arr[low_lim: up_lim]) if up_lim == arr.shape[0]: # print(i) break out_seq = np.array(out) return out_seq # Shape the sequence according to the length specified X_seq = shape_sequence(X, 5, 0) y_seq = shape_sequence(y, 1, 0) # Separate the input and output for train and validation X_train, X_val, y_train, y_val = train_test_split(X_seq, y_seq, test_size=0.2, shuffle=False) print("Training data shape = ", X_train.shape) print("Validation data shape = ", X_val.shape) # + [markdown] id="7IvtcbnQkeyx" # ## Create prediction model # + [markdown] id="6m0eu4O0ySq2" # Create a simple 2-layer LSTM model with input shape matching the shape of the data sequence provided. # + colab={"base_uri": "https://localhost:8080/"} id="XZFYZu2Zh3zd" outputId="e7ba2701-551c-4a89-f56c-e9da0d9a4721" from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout from tensorflow.keras.optimizers import Adam from tensorflow.keras.losses import MeanSquaredError from tensorflow.keras.callbacks import ModelCheckpoint import tensorflow.keras.losses as loss def create_model(X_train, y_train): shape = X_train.shape[1] feat_length = X_train.shape[2] model = Sequential() model.add(LSTM(shape, activation='tanh', input_shape=(shape, feat_length), return_sequences=True)) model.add(LSTM(shape, activation='tanh', input_shape=(shape, feat_length), return_sequences=False)) model.add(Dense(shape, activation='relu')) model.add(Dense(1, activation='linear')) model.compile(optimizer=Adam(lr=0.035), loss=loss.mean_squared_error) model.fit(X_train, y_train, verbose=1, epochs=500) return model model = create_model(X_train, y_train) # + [markdown] id="JfzoaV9kqll8" # ## Check validation result # We will check the model's performance with validation data. # + colab={"base_uri": "https://localhost:8080/", "height": 312} id="M7xe62ibi_QE" outputId="00ccaa46-8308-45ff-818e-3d42bbbea876" # Predict validation data using the trained model y_pred = model.predict(X_val) mse = MeanSquaredError() val_err = mse(y_val.reshape(-1,1), y_pred) print("Validation error = ", val_err.numpy()) # Return the value using inverse transform to allow better observation plt.plot(pres_scaler.inverse_transform(y_val.reshape(-1,1)), 'k', label='Original') plt.plot(pres_scaler.inverse_transform(y_pred.reshape(-1,1)), 'r', label='Prediction') plt.ylabel("Pressure") plt.xlabel("Datapoint") plt.title("Validation data prediction") plt.legend() plt.show() # + [markdown] id="2Lw3GJS1qs9r" # ## Check test result # # From the plot, we can see that some of the data points are inaccurate, which can be caused by the highly fluctuating nature of the hourly data points. Next, we will see whether the model can predict the sensor reading correctly in the event of anomalies. We are going to pick another date where failure occurred (2015-04-20). # + id="MUkbr6ARCFxh" outputId="15b96715-8b9a-4789-c58a-7c1f1da00f7a" colab={"base_uri": "https://localhost:8080/", "height": 296} # Select the date where another failure occurred st_test = df_sel.loc[df_sel['datetime'] == "2015-04-20"].index.values[0] # Then, filter the data to include approximately two-weeks window start_period_test = st_test - 7*24 end_period_test = st_test + 7*24 X_test, y_test, test_scaler = create_feature(start_period_test, end_period_test) # Shape the sequence X_test_seq = shape_sequence(X_test, 5, 0) y_test_seq = shape_sequence(y_test, 1, 0) # Predict the testing data y_pred_test = model.predict(X_test_seq) test_err = mse(y_test_seq.reshape(-1,1), y_pred_test) print("Testing error = ", test_err.numpy()) # Select first 200 datapoints to allow for better plotting # Return the value using inverse transform to allow better observation plt.plot(test_scaler.inverse_transform(y_pred_test[:200].reshape(-1, 1)), 'r', label='Prediction') plt.plot(test_scaler.inverse_transform(y_test_seq[:200].reshape(-1, 1)), 'k', label='Original') plt.ylabel("Pressure") plt.xlabel("Datapoints") plt.legend() plt.show() # + [markdown] id="HmDTThCG5ylv" # We observe that the model can predict the sensor reading even in the event of machine failure. The key here is to make sure that the training data that we use to train include past failure event as well. # + [markdown] id="uEEwRbIq2Scs" # # Further Steps # Now that we know how to construct a time-series forecasting model to predict anomalies, there are several possible steps on how to develop a complete predictive maintenance solution: # * Develop machine learning / deep learning model to predict the chance of machine breakdown by feeding it prediction results from our developed time-series forecasting model. # * Look into signal processing algorithm to smoothen the signal before feeding it to time-series forecasting model, which could improve model's performance. # * Use bigger subset of data in training process and check how does the model change, better or worse? # * Do hyperparameter optimization to further optimize the performance of time-series forecasting model. # + [markdown] id="rlhcdt8J0sFJ" # # Conclusion # In this notebook, we have looked into an example predictive maintenance data from Kaggle, do some prior analysis on it, and construct a time-series forecasting model that will predict sensor reading values in the future. Hopefully, this notebook could provide some insights regarding how to implement time-series forecasting with deep learning in predictive maintenance.
train_forecasting.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] tags=["remove_cell"] # <h1 style="font-size:35px; # color:black; # ">Lab 5 Scalable Shor’s Algorithm </h1> # - # Prerequisites: # - [Ch.3.7 Shor's Algorithm](https://qiskit.org/textbook/ch-algorithms/shor.html) # # Other relevant materials: # - [Experimental demonstration of Shor’s algorithm with quantum entanglement](https://arxiv.org/pdf/0705.1398.pdf) # - [Realization of a scalable Shor algorithm](https://arxiv.org/pdf/1507.08852.pdf) from qiskit import * import numpy as np from qiskit.visualization import plot_histogram import qiskit.tools.jupyter import matplotlib.pyplot as plt sim = Aer.get_backend('qasm_simulator') shots = 20000 # <h2 style="font-size:24px;">Part 1: Quantum circuit for Shor's algorithm</h2> # # # <br> # <div style="background: #E8E7EB; border-radius: 5px; # -moz-border-radius: 5px;"> # <p style="background: #800080; # border-radius: 5px 5px 0px 0px; # padding: 10px 0px 10px 10px; # font-size:18px; # color:white; # "><b>Goal</b></p> # <p style=" padding: 0px 0px 10px 10px; # font-size:16px;">Construct a compiled version of quantum circuit for Shor's algorithm.</p> # </div> # # Shor's algorithm consists of the following steps; choose a co-prime $a$, where $a \in [2, N-1]$ and the greatest common divisor of $a$ and $N$ is 1, find the order of $a$ modulo $N$, the smallest integer $r$ such that $a^{r}modN = 1$, and then obtain the factor of $N$ by computing the greatst common divisor of $a^{r/2} \pm 1$ and $N$. In this procedure, the second step, finding the order of $a$ modulo $N$, is the only quantum part, *quantum order-finding*. # # In [Ch.3.9 Shor's Algorithm](https://qiskit.org/textbook/ch-algorithms/shor.html), we built a quantum circuit to find the order for $a=7$ and $N=15$. However, as we are very well aware by now that such a large depth circuit is not practical to run on near-term quantum systems due to the presence of noise. Here in part 1 of this lab, we construct a practical quantum circuit for the same example, which could generate a meaningful solution when executed on today's quantum computers. # In general, the quantum order-finding circuit to factorize the number $N$ requires $m = [log_{2}(N)]$ qubits in the computational ( auxiliary ) register and $2m (=t)$qubit in the period ( counting ) registers .i.e. total $3m$ qubits, at minimum. Therefore, 12 qubits were used in the quantum circuit to factorize the number 15 in [Ch.3.9 Shor's Algorithm](https://qiskit.org/textbook/ch-algorithms/shor.html). In addition, the cotrolled unitary operator for the modular function, $f(x) = a^xmodN$ was applied in casecade manner as shown in the figure below to produce the highly entangled state $\Sigma^{2^m-1}_{x=0}|x\rangle|a^xmodN>$, which increseas the circuit depth substantially. However the size of the circuit can be reduced based on several observations. # ![](image/L5_Circ_gen.svg) # <h3 style="font-size: 20px">1. Remove redundancy.</h3> # <h4 style="font-size: 17px">Step A. Run the following cell to create the gate <code>U</code> for the function <code>7mod15</code>.</h4> # The unitary operator $U$ is defined as $U|x\rangle \equiv |7x(mod15)\rangle$. # + ## Create 7mod15 gate N = 15 m = int(np.ceil(np.log2(N))) U_qc = QuantumCircuit(m) U_qc.x(range(m)) U_qc.swap(1, 2) U_qc.swap(2, 3) U_qc.swap(0, 3) U = U_qc.to_gate() U.name ='{}Mod{}'.format(7, N) # - # &#128211; Confirm if the unitary operator $U$ works properly by creating a quantum circuit with $m$ qubits. Prepare the input state representing any integer between 0 and 15 such as $|1\rangle (=|0001\rangle), |5\rangle (=|0011\rangle), |13\rangle (=|1101\rangle)$ etc, and apply $U$ gate on it. Check if the circuit produces the expected outcomes for several inputs. The outcome state for the input $|1\rangle$ should be $|7\rangle (=|0111>$) and $|1\rangle$ for the input $|13\rangle$, for example. # + ### your code goes here # - # <h4 style="font-size: 17px">&#128211;Step B. Create a quantum circuit with $m$ qubits implementing $U$ gate $4(=2^{2})$ times and run it on the <code>unitary_simulator</code> to obtain the matrix resprentation of the gates in the circuit. Verify $U^{2^{2}} = I $ </h4> # As shown in the above figure, modular exponentiation is realized by implementing the controlled unitary operator $U$ on each qubit $2^{n}$ times in series when $n$ goes from 0 to 7 for our example. However, we will find out that whole sets of operations are redundant when $n > 1$ for `7mod15` case, hence the redundant operation can be removed from the circuit. # + ### your code goes here # - # <h4 style="font-size: 17px">Step C. Run the cells below to see the reduced circuit, <code>shor_QPE</code>, and execute it on the <code>qasm_simulator</code> to check if it reproduce the estimated phases in the Qiskit textbook Ch.3.9. </h4> def cU_multi(k): circ = QuantumCircuit(m) for _ in range(2**k): circ.append(U, range(m)) U_multi = circ.to_gate() U_multi.name = '7Mod15_[2^{}]'.format(k) cU_multi = U_multi.control() return cU_multi def qft(n): """Creates an n-qubit QFT circuit""" circuit = QuantumCircuit(n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(np.pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # + # QPE circuit for Shor t = 3 shor_QPE = QuantumCircuit(t+m, t) shor_QPE.h(range(t)) shor_QPE.x(t) for idx in range(t-1): shor_QPE.append(cU_multi(idx), [idx]+ list(range(t,t+m))) qft_dag = qft(t).inverse() qft_dag.name = 'QFT+' shor_QPE.append(qft_dag, range(t)) shor_QPE.measure(range(t), range(t)) shor_QPE.draw() # - count_QPE = execute(shor_QPE, sim, shots=shots).result().get_counts() key_new = [str(int(key,2)/2**3) for key in count_QPE.keys()] count_new_QPE = dict(zip(key_new, count_QPE.values())) plot_histogram(count_new_QPE) # <h3 style="font-size: 20px">2. Implement Iterative Phase Esitmation (IPE) algorithm.</h3> # The circuit above, `shor_QPE` can be optimized further by implementing IPE algorithm as we learned in the previous lab, `Lab4 Iterative Phase Estimation Algorithm`. # <h4 style="font-size: 17px">&#128211; Create the circuit <code>shor_IPE</code> by modifying the above circuit (<code>shor_QPE</code>) with a single period (counting) qubit register and check its result through <code>qasm_simulator</code>. </h4> # + ### your code goes here # - # <h2 style="font-size:24px;">Part 2: Noise simulation of the quantum order-finding circuits.</h2> # # # <br> # <div style="background: #E8E7EB; border-radius: 5px; # -moz-border-radius: 5px;"> # <p style="background: #800080; # border-radius: 5px 5px 0px 0px; # padding: 10px 0px 10px 10px; # font-size:18px; # color:white; # "><b>Goal</b></p> # <p style=" padding: 0px 0px 10px 10px; # font-size:16px;">Perform the noise simulaton of all three quantum order-finding circuits: the one in Qiskit textbook, compiled version of QPE circuit in the first section of Part1 , compiled version of IPE circuit in Part 1. Compare their results. </p> # </div> # # In part 1, we constructed the compiled version of the circuit for shor's algorithm; removed the redundant gates and optimized it further by implementing IPE algorithm that we learned in the previous lab, Lab4. In part 2, we inspect how each optimization plays a role to improved the outcomes by comparing their noise simulation results. # Run the following cells to construct the shor's circuit in Qiskit texbook [Ch.3.9 Shor's Algorithm](https://qiskit.org/textbook/ch-algorithms/shor.html), 'shor_Orig',and to obtain its simulation result. # + t = 2*m shor_Orig = QuantumCircuit(t+m, t) shor_Orig.h(range(t)) shor_Orig.x(t) for idx in range(t): shor_Orig.append(cU_multi(idx), [idx]+ list(range(t,t+m))) qft_dag = qft(t).inverse() qft_dag.name = 'QFT+' shor_Orig.append(qft_dag, range(t)) shor_Orig.measure(range(t), range(t)) shor_Orig.draw() # - count_Orig = execute(shor_Orig, sim, shots=shots).result().get_counts() key_new = [str(int(key,2)/2**t) for key in count_Orig.keys()] count_new_Orig = dict(zip(key_new, count_Orig.values())) plot_histogram(count_new_Orig, title='textbook circuit simulation result No noise') # <h4 style="font-size: 17px">Perform the noise simulations of all three circuits, <code>shor_Orig</code>, <code>shor_QPE</code>, <code>shor_IPE</code> on the backend <code>FakeMelbourne</code> and plot their noise simulation results together with ones without noise for comparison.</h4> # Run the following cell. from qiskit.test.mock import FakeMelbourne backend = FakeMelbourne() shots=8192 # The comparison plot of the simulation results with/without noise for the textbook circuit `shor_Orig` is given below. The code is there to show how the result is generated but not recommended to run as it takes for long time. # + # shorOrig_trans = transpile(shor_Orig, backend, optimization_level=3) # count_shorOrig_noise = execute(shor_Orig, backend, shots=shots).result().get_counts() # + # key_new = [str(np.round(int(key,2)/2**t,3)) for key in count_shorOrig_noise.keys()] # count_new_Orig_noise = dict(zip(key_new, count_shorOrig_noise.values())) # + # fig, ax = plt.subplots(2,1, figsize=(30,13)) # fig.suptitle('Simulation results for the order finding circuit of $7^{r} mod 15 = 1$', fontsize=23) # plot_histogram(count_new_Orig, ax=ax[0]) # plot_histogram(count_new_Orig_noise, ax=ax[1]) # ax[0].set_title('sim No noise', fontsize=16) # ax[1].set_title('sim on Melbourne', fontsize=16) # plt.show() # - # ![](image/L5_textbook_result.png) # &#128211; Carry out the same task for the circuits, `shor_QPE` and `shor_IPE`. # + ### your code goes here
content/ch-labs/Lab05_Scalable_Shor_Algorithm.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 molmap.model import RegressionEstimator, MultiClassEstimator, MultiLabelEstimator from sklearn.preprocessing import StandardScaler, MinMaxScaler from chembench import dataset from sklearn.utils import shuffle import matplotlib.pyplot as plt import numpy as np import pandas as pd from molmap import MolMap from molmap import feature def Rdsplit(df, random_state = 888, split_size = [0.8, 0.1, 0.1]): base_indices = np.arange(len(df)) base_indices = shuffle(base_indices, random_state = random_state) nb_test = int(len(base_indices) * split_size[2]) nb_val = int(len(base_indices) * split_size[1]) test_idx = base_indices[0:nb_test] valid_idx = base_indices[(nb_test):(nb_test+nb_val)] train_idx = base_indices[(nb_test+nb_val):len(base_indices)] print(len(train_idx), len(valid_idx), len(test_idx)) return train_idx, valid_idx, test_idx # - data = dataset.load_FreeSolv() # ## Pre-fit your molmap object mp1 = MolMap(ftype='descriptor',metric='cosine',) mp1.fit(verbose=0, method='umap', min_dist=0.1, n_neighbors=15,) bitsinfo = feature.fingerprint.Extraction().bitsinfo flist = bitsinfo[bitsinfo.Subtypes.isin(['PubChemFP', 'MACCSFP', 'PharmacoErGFP'])].IDs.tolist() mp2 = MolMap(ftype = 'fingerprint', fmap_type = 'scatter', flist = flist) # mp2.fit(method = 'umap', min_dist = 0.1, n_neighbors = 15, verbose = 0) # ## Extract Fmaps X1 = mp1.batch_transform(data.x) X2 = mp2.batch_transform(data.x) Y = data.y # + train_idx, valid_idx, test_idx = Rdsplit(data.df, random_state = 123) trainX = (X1[train_idx], X2[train_idx]) validX = (X1[valid_idx], X2[valid_idx]) testX = (X1[test_idx], X2[test_idx]) trainY = Y[train_idx] validY = Y[valid_idx] testY = Y[test_idx] # - # define your model clf = RegressionEstimator(n_outputs=trainY.shape[1], fmap_shape1 = X1.shape[1:], fmap_shape2 = X2.shape[1:], dense_layers = [128, 64], batch_size = 8, y_scale= None, patience = 20, gpuid = 1) # fit your model clf.fit(trainX, trainY, validX, validY) pd.DataFrame(clf.history.history).plot() print('Best epochs: %.2f, Best MSE: %.2f' % (clf._performance.best_epoch, clf._performance.best)) testY_pred = clf.predict(testX) plt.scatter(testY, testY_pred) rmse, r2 = clf._performance.evaluate(testX, testY) rmse, r2 clf.score(testX, testY) clf._performance.evaluate(validX, validY)
molmap/example/02_model_example_freesolv_dual_path.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 # --- # %%HTML <style> code {background-color : pink !important;} </style> # Applying Sobel # === # # + import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import pickle # Read in an image and grayscale it image = mpimg.imread('signs_vehicles_xygrad.png') from thresholds import abs_sobel_thresh # Run the function grad_binary = abs_sobel_thresh(image, orient='x', thresh=(20, 100)) # Plot the result f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9)) f.tight_layout() ax1.imshow(image) ax1.set_title('Original Image', fontsize=50) ax2.imshow(grad_binary, cmap='gray') ax2.set_title('Thresholded Gradient', fontsize=50) plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
HelperProjects/Gradients-and-Color-Spaces/applying-sobel.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline import lzma,json f=lzma.open("ep/ep_meps_current.json.xz") #http://parltrack.euwiki.org/dumps/ep_meps_current.json.xz members=json.loads(f.read()) f=lzma.open("ep/ep_votes.json.xz") #http://parltrack.euwiki.org/dumps/ep_votes.json.xz votes=json.loads(f.read()) hu={} ro={} for j in members: z='Constituencies' w='Groups' if z in j: if j[z][0]['country']=='Hungary': hu[j['UserID']]=j elif j[z][0]['country']=='Romania': ro[j['UserID']]=j elif w in j: if j[w][0]['country']=='Hungary': hu[j['UserID']]=j elif j[w][0]['country']=='Romania': ro[j['UserID']]=j hu_allegiance_people={} ro_allegiance_people={} hu_allegiance_group={} ro_allegiance_group={} hu_allegiance_party={} ro_allegiance_party={} hu_vt=[] ro_vt=[] def get_allegiance(allegiance,voteid,outcome,name): if voteid not in allegiance: allegiance[voteid]={'title':j['title'],'url':j['url'],'ts':j['ts']} if outcome not in allegiance[voteid]: allegiance[voteid][outcome]=[] allegiance[voteid][outcome].append(name) return allegiance for j in votes: ts=j['ts'] for outcome in ['Abstain','For','Against']: if outcome in j: for group in j[outcome]['groups']: for i in group['votes']: if i['ep_id'] in ro: dummy={} dummy['vote']=j['voteid'] dummy['party']='Independent' for k in ro[i['ep_id']]['Constituencies']: if k['start']<ts<k['end']: dummy['party']=k['party'] dummy['name']=ro[i['ep_id']]['Name']['full'] dummy['outcome']=outcome dummy['group']=group['group'] ro_vt.append(dummy) ro_allegiance_people=\ get_allegiance(ro_allegiance_people,j['voteid'],outcome,dummy['name']) ro_allegiance_group=\ get_allegiance(ro_allegiance_group,j['voteid'],outcome,dummy['group']) ro_allegiance_party=\ get_allegiance(ro_allegiance_party,j['voteid'],outcome,dummy['party']) elif i['ep_id'] in hu: dummy={} dummy['vote']=j['voteid'] dummy['party']='Independent' for k in hu[i['ep_id']]['Constituencies']: if k['start']<ts<k['end']: dummy['party']=k['party'] dummy['name']=hu[i['ep_id']]['Name']['full'] dummy['outcome']=outcome dummy['group']=group['group'] dummy['title']=j['title'] dummy['url']=j['url'] dummy['ts']=j['ts'] hu_vt.append(dummy) hu_allegiance_people=\ get_allegiance(hu_allegiance_people,j['voteid'],outcome,dummy['name']) hu_allegiance_group=\ get_allegiance(hu_allegiance_group,j['voteid'],outcome,dummy['group']) hu_allegiance_party=\ get_allegiance(hu_allegiance_party,j['voteid'],outcome,dummy['party']) ro_df=pd.DataFrame(ro_vt)#.join(pd.DataFrame(vt).T,on='vote') hu_df=pd.DataFrame(hu_vt)#.join(pd.DataFrame(vt).T,on='vote') open('ep/ro_vt.json','w').write(json.dumps(ro_vt)) open('ep/hu_vt.json','w').write(json.dumps(hu_vt)) hu_df.to_json("ep/hu_df.json.gz", compression="gzip") ro_df.to_json("ep/ro_df.json.gz", compression="gzip") # Allegiance def get_allegiance_matrix(key,vt,allegiance): allegiance_matrix={} for j1 in vt: outcome=j1['outcome'] if j1[key] not in allegiance_matrix:allegiance_matrix[j1[key]]={} if outcome=='For': for name2 in allegiance[j1['vote']]['For']: if name2 not in allegiance_matrix[j1[key]]: allegiance_matrix[j1[key]][name2]={'Same':0,'Opposite':0,'Total':0} allegiance_matrix[j1[key]][name2]['Total']+=1 allegiance_matrix[j1[key]][name2]['Same']+=1 if 'Against' in allegiance[j1['vote']]: for name2 in allegiance[j1['vote']]['Against']: if name2 not in allegiance_matrix[j1[key]]: allegiance_matrix[j1[key]][name2]={'Same':0,'Opposite':0,'Total':0} allegiance_matrix[j1[key]][name2]['Total']+=1 allegiance_matrix[j1[key]][name2]['Opposite']+=1 elif outcome=='Against': for name2 in allegiance[j1['vote']]['Against']: if name2 not in allegiance_matrix[j1[key]]: allegiance_matrix[j1[key]][name2]={'Same':0,'Opposite':0,'Total':0} allegiance_matrix[j1[key]][name2]['Total']+=1 allegiance_matrix[j1[key]][name2]['Same']+=1 if 'For' in allegiance[j1['vote']]: for name2 in allegiance[j1['vote']]['For']: if name2 not in allegiance_matrix[j1[key]]: allegiance_matrix[j1[key]][name2]={'Same':0,'Opposite':0,'Total':0} allegiance_matrix[j1[key]][name2]['Total']+=1 allegiance_matrix[j1[key]][name2]['Opposite']+=1 for j in allegiance_matrix: for i in allegiance_matrix[j]: allegiance_matrix[j][i]['Same_perc']=allegiance_matrix[j][i]['Same']/allegiance_matrix[j][i]['Total'] allegiance_matrix[j][i]['Opposite_perc']=allegiance_matrix[j][i]['Opposite']/allegiance_matrix[j][i]['Total'] return allegiance_matrix ro_allegiance_matrix_people_by_people=get_allegiance_matrix('name',ro_vt,ro_allegiance_people) hu_allegiance_matrix_people_by_people=get_allegiance_matrix('name',hu_vt,hu_allegiance_people) ro_allegiance_matrix_people_by_group=get_allegiance_matrix('name',ro_vt,ro_allegiance_group) hu_allegiance_matrix_people_by_group=get_allegiance_matrix('name',hu_vt,hu_allegiance_group) ro_allegiance_matrix_people_by_party=get_allegiance_matrix('name',ro_vt,ro_allegiance_party) hu_allegiance_matrix_people_by_party=get_allegiance_matrix('name',hu_vt,hu_allegiance_party) (pd.DataFrame(ro_allegiance_matrix_people_by_people['<NAME>']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(ro_allegiance_matrix_people_by_people['<NAME>']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(ro_allegiance_matrix_people_by_people['<NAME>']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(ro_allegiance_matrix_people_by_people['<NAME>']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(ro_allegiance_matrix_people_by_people['<NAME>']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(hu_allegiance_matrix_people_by_people['<NAME>']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(hu_allegiance_matrix_people_by_people['<NAME>']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(hu_allegiance_matrix_people_by_people['<NAME>']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(ro_allegiance_matrix_people_by_party['Csaba SÓGOR']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(ro_allegiance_matrix_people_by_group['Csaba SÓGOR']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) ro_allegiance_matrix_party_by_people=get_allegiance_matrix('party',ro_vt,ro_allegiance_people) hu_allegiance_matrix_party_by_people=get_allegiance_matrix('party',hu_vt,hu_allegiance_people) ro_allegiance_matrix_party_by_group=get_allegiance_matrix('party',ro_vt,ro_allegiance_group) hu_allegiance_matrix_party_by_group=get_allegiance_matrix('party',hu_vt,hu_allegiance_group) ro_allegiance_matrix_party_by_party=get_allegiance_matrix('party',ro_vt,ro_allegiance_party) hu_allegiance_matrix_party_by_party=get_allegiance_matrix('party',hu_vt,hu_allegiance_party) ro_allegiance_matrix_group_by_people=get_allegiance_matrix('group',ro_vt,ro_allegiance_people) hu_allegiance_matrix_group_by_people=get_allegiance_matrix('group',hu_vt,hu_allegiance_people) ro_allegiance_matrix_group_by_group=get_allegiance_matrix('group',ro_vt,ro_allegiance_group) hu_allegiance_matrix_group_by_group=get_allegiance_matrix('group',hu_vt,hu_allegiance_group) ro_allegiance_matrix_group_by_party=get_allegiance_matrix('group',ro_vt,ro_allegiance_party) hu_allegiance_matrix_group_by_party=get_allegiance_matrix('group',hu_vt,hu_allegiance_party) (pd.DataFrame(ro_allegiance_matrix_group_by_group['PPE']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) ro_allegiance_matrix_party_by_party.keys() (pd.DataFrame(ro_allegiance_matrix_party_by_party['Partidul Social Democrat']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) (pd.DataFrame(ro_allegiance_matrix_party_by_party['Uniunea Democrată Maghiară din România']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) hu_allegiance_matrix_party_by_party.keys() (pd.DataFrame(hu_allegiance_matrix_party_by_party['Fidesz-Magyar Polgári Szövetség-Kereszténydemokrata Néppárt']).T['Same_perc']-0.6).\ sort_values(ascending=False).plot(kind='bar',figsize=(15,9)) from scipy.cluster.hierarchy import dendrogram, linkage import numpy as np def dict_2_matrix(matrix,key): labels=sorted(matrix) #extend to square matrix inner_keys=matrix[sorted(matrix)[0]] inner_keys=sorted(inner_keys[sorted(inner_keys)[0]]) for name1 in labels: for name2 in labels: if name2 not in matrix[name1]: matrix[name1][name2]={i:0 for i in inner_keys} return np.array([[matrix[name1][name2][key] for name2 in sorted(matrix[name1])] for name1 in labels]),labels def dendro(matrix,key='Same_perc'): X,labelList=dict_2_matrix(matrix,key) linked = linkage(X, 'ward') plt.figure(figsize=(14, 7)) dendrogram(linked, orientation='top', labels=labelList, distance_sort='descending', show_leaf_counts=True) ax=plt.gca() plt.setp(ax.get_xticklabels(), rotation=90, fontsize=9) plt.show() dendro(hu_allegiance_matrix_party_by_party) dendro(ro_allegiance_matrix_party_by_party) dendro(ro_allegiance_matrix_group_by_group) dendro(ro_allegiance_matrix_people_by_people) dendro(hu_allegiance_matrix_people_by_people) # multicountry ro_allegiance_matrix_party_by_party.update(hu_allegiance_matrix_party_by_party) dendro(ro_allegiance_matrix_party_by_party) # Matrix 2 adjacency list matrix,labels=dict_2_matrix(hu_allegiance_matrix_party_by_party,'Same_perc') from scipy import sparse row, col = np.where(matrix) coo = np.rec.fromarrays([row, col, matrix[row, col]], names='row col value'.split()) #coo = coo.tolist() row [[labels[i[0]],labels[i[1]],i[2]] for i in coo if [labels[i[0]],labels[i[1]]]
ep/archive/ep_archived.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 # --- # # CMAES : Covariance Matrix Adaptation Evolutionary Strategy # Setup code and utility functions to plot and explore # + import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors from matplotlib import cm from mpl_toolkits.mplot3d import axes3d from numpy.random import multivariate_normal import copy # %matplotlib inline # %config InlineBackend.figure_format = 'retina' try: import seaborn as sns sns.set_style("whitegrid") sns.set_context('talk') #sns.set(font_scale=1.4) except ImportError: plt.style.use('seaborn-whitegrid') # + def range_from_bounds(bounds, resolution): (minx,miny),(maxx,maxy) = bounds x_range = np.arange(minx, maxx, (maxx-minx)/resolution) y_range = np.arange(miny, maxy, (maxy-miny)/resolution) return x_range, y_range def plot_problem_3d(problem, bounds, ax=None, resolution=100., cmap=cm.viridis_r, rstride=10, cstride=10, linewidth=0.15, alpha=0.65): """Plots a given benchmark problem in 3D mesh.""" x_range, y_range = range_from_bounds(bounds, resolution=resolution) X, Y = np.meshgrid(x_range, y_range) Z = problem(X,Y) if not ax: fig = plt.figure(figsize=(11,6)) ax = fig.gca(projection='3d') cset = ax.plot_surface(X, Y, Z, cmap=cmap, rstride=rstride, cstride=cstride, linewidth=linewidth, alpha=alpha) # - def plot_problem_contour(problem, bounds, optimum=None, resolution=100., cmap=cm.viridis_r, alpha=0.45, ax=None): """Plots a given benchmark problem as a countour.""" x_range, y_range = range_from_bounds(bounds, resolution=resolution) X, Y = np.meshgrid(x_range, y_range) Z = problem(X,Y) if not ax: fig = plt.figure(figsize=(6,6)) ax = fig.gca() ax.set_aspect('equal') ax.autoscale(tight=True) cset = ax.contourf(X, Y, Z, cmap=cmap, alpha=alpha) if optimum: ax.plot(optimum[0], optimum[1], 'bx', linewidth=4, markersize=15) def plot_cov_ellipse(pos, cov, volume=.99, ax=None, fc='lightblue', ec='darkblue', alpha=1, lw=1): ''' Plots an ellipse that corresponds to a bivariate normal distribution. Adapted from http://www.nhsilbert.net/source/2014/06/bivariate-normal-ellipse-plotting-in-python/''' from scipy.stats import chi2 from matplotlib.patches import Ellipse def eigsorted(cov): vals, vecs = np.linalg.eigh(cov) order = vals.argsort()[::-1] return vals[order], vecs[:,order] if ax is None: ax = plt.gca() vals, vecs = eigsorted(cov) theta = np.degrees(np.arctan2(*vecs[:,0][::-1])) kwrg = {'facecolor':fc, 'edgecolor':ec, 'alpha':alpha, 'linewidth':lw} # Width and height are "full" widths, not radius width, height = 2 * np.sqrt(chi2.ppf(volume,2)) * np.sqrt(vals) ellip = Ellipse(xy=pos, width=width, height=height, angle=theta, **kwrg) ax.add_artist(ellip) # ## Test functions # # ### Why benchmarks (test) functions? # # In applied mathematics, [test functions](http://en.wikipedia.org/wiki/Test_functions_for_optimization), also known as artificial landscapes, are useful to evaluate characteristics of optimization algorithms, such as: # # * Velocity of convergence. # * Precision. # * Robustness. # * General performance. # # ### [Bohachevsky benchmark problem](http://benchmarkfcns.xyz/benchmarkfcns/bohachevskyn2fcn.html) # # $$\text{minimize } f(\mathbf{x}) = \sum_{i=1}^{N-1}(x_i^2 + 2x_{i+1}^2 - 0.3\cos(3\pi x_i) - 0.4\cos(4\pi x_{i+1}) + 0.7), \mathbf{x}\in \left[-100,100\right]^n,$$ # # > Optimum in $\mathbf{x}=\mathbf{0}$, $f(\mathbf{x})=0$. def _shifted_bohachevsky_impl(x, y, shift_x, shift_y): return (x-shift_x)**2 + 2.0 * (y-shift_y)**2 - 0.3 * np.cos(3.0 * np.pi * (x - shift_x)) - 0.4 * np.cos(4.0 * np.pi* (y - shift_y)) + 0.7 # def bohachevsky(x,y): # return x**2 + 2.0 * y**2 - 0.3 * np.cos(3.0 * np.pi * x) - 0.4 * np.cos(4.0 * np.pi*x) + 0.7 from functools import partial bohachevsky = partial(_shifted_bohachevsky_impl, shift_x = 0.0, shift_y = 0.0) shifted_bohachevsky = partial(_shifted_bohachevsky_impl, shift_x = 2.0, shift_y = 2.0) # ### [Griewank benchmark problem](http://benchmarkfcns.xyz/benchmarkfcns/griewankfcn.html) # # $$\text{minimize } f(\mathbf{x}) = f(x_1, ..., x_n) = 1 + \sum_{i=1}^{n} \frac{x_i^{2}}{4000} - \prod_{i=1}^{n}\cos\left(\frac{2 \cdot x_i}{\sqrt{i}}\right)$$ # # > Optimum in $\mathbf{x}=\mathbf{0}$, $f(\mathbf{x})=0$. # + def _shifted_griewank_impl(x,y,shift_x, shift_y): return 1.0 + ((x-shift_x)**2 + (y-shift_y)**2) / 4000.0 - np.cos(2.0 * (x-shift_x)) * np.cos(2.0 * (y-shift_y) / np.sqrt(2.0)) # def griewank(x,y): # return 1.0 + (x**2 + y**2) / 4000.0 - np.cos(2.0 * x) * np.cos(2.0 * y / np.sqrt(2.0)) # - griewank = partial(_shifted_griewank_impl, shift_x = 0.0, shift_y = 0.0) shifted_griewank = partial(_shifted_griewank_impl, shift_x = 2.0, shift_y = 2.0) current_problem = bohachevsky plot_problem_3d(current_problem, ((-10,-10), (10,10))) # These problems has many local optima. plot_problem_3d(current_problem, ((-2.5,-2.5), (2.5,2.5))) ax = plt.figure(figsize=(8, 5)).gca() plot_problem_contour(current_problem, ((-2.5,-2.5), (2.5,2.5)), optimum=(0,0), ax=ax) ax.set_aspect('equal') # ## Optimizing test functions using CMA-ES # # ### CMA-ES features # # * Adaptation of the covariance matrix amounts to learning a second order model of the underlying objective function. # * This is similar to the approximation of the inverse Hessian matrix in the Quasi-Newton method in classical optimization. # * In contrast to most classical methods, fewer assumptions on the nature of the underlying objective function are made. # * *Only the ranking between candidate solutions is exploited* for learning the sample distribution and neither derivatives nor even the function values themselves are required by the method. # # # ## Let's code up CMA from scratch! # Here are the steps of CMA in chronological order : # $$ # \newcommand{\gv}[1]{\ensuremath{\mbox{\boldmath$ #1 $}}} # \newcommand{\bv}[1]{\ensuremath{\mathbf{#1}}} # \newcommand{\norm}[1]{\left\lVert#1\right\rVert} # \newcommand{\order}[1]{\mathcal O \left( #1 \right)} % order of magnitude # $$ # # ### Initialization # Set $ \mathbf{m} = \mathbf{0}, \mathbf{C} = \mathbf{I}, \sigma = 0.5, \mathbf{p}_c = \mathbf{0}, \mathbf{p}_{\sigma} = \mathbf{0} $ # # ### Sampling # $$ \begin{aligned} # \mathbf{z}_{i} & \sim \mathcal{N}(\mathbf{0}, \mathbf{C}) \\ # \mathbf{x}_{i} &= m+\sigma \mathbf{z}_{i} # \end{aligned} $$ # # ### Selection and recombination # Sort the ppopulation by fitness to get $ \mu $ fit individuals # $$ \begin{aligned} # \langle\mathbf{z}\rangle_{w} &= \displaystyle\sum_{i=1}^{\mu} w_{i} \mathbf{z}_{i : \lambda} \\ # \mathbf{m} &\longleftarrow \mathbf{m}+\sigma\langle\mathbf{z}\rangle_{w} # \end{aligned} $$ # # ### Step size update # $$ \begin{aligned} # \mathbf{p}_{\sigma} &\longleftarrow\left(1-c_{\sigma}\right) # \mathbf{p}_{\sigma}+\sqrt{1-\left(1-c_{\sigma}\right)^{2}} # \sqrt{\frac{1}{\sum_{i=1}^{\mu} w_{i}^{2}}} # \mathbf{C}^{-\frac{1}{2}}\langle\mathbf{z}\rangle_{w} \\ # \sigma &\longleftarrow \sigma # \exp{\left(\frac{c_{\sigma}}{d_{\sigma}}\left(\frac{\left\|p_{\sigma}\right\|}{E\|\mathcal{N}(\mathbf{0}, # \mathbf{I})\|}-1\right)\right)} \\ # \end{aligned} $$ # # # ### Covariance Matrix update # $$ \begin{aligned} # \mathbf{p}_{c} &\longleftarrow \left(1-c_{c}\right) # \mathbf{p}_{c}+\sqrt{1-\left(1-c_{c}\right)^{2}} \sqrt{\frac{1}{\sum_{i=1}^{\mu} # w_{i}^{2}}}\langle\mathbf{z}\rangle_{w} \\ # \mathbf{Z} &= \sum_{i=1}^{\mu} w_{i} \mathbf{z}_{i : \lambda} \mathbf{z}_{i : # \lambda}^{T} \\ # \mu_{c o v}&=\sqrt{\frac{1}{\sum_{i=1}^{\mu} w_{i}^{2}}} \\ # \mathbf{C} &\longleftarrow\left(1-c_{c o v}\right) \mathbf{C}+c_{c o v} # \frac{1}{\mu_{c o v}} \mathbf{p}_{c} \mathbf{p}_{c}^{T}+c_{c o # v}\left(1-\frac{1}{\mu_{c o v}}\right) \mathbf{Z} # \end{aligned} $$ # # Some considerations: # - `centroid` and `mean` are interchangeable. # - `chi_N` is the expectation for the length of a random vector sampled from a multivariate normal distribution with $\mathbf{C} = \mathbf{I}$, and is used in the step-size update above. It can be analytically computed as $ \approx \sqrt{n} \left( 1 - \dfrac{1}{4n} + \dfrac{1}{21n^2} \right)$ # - `mu_eff` $ \mu_{\textrm{eff}} = \left(\displaystyle\sum_{i=1}^{\mu} w_{i}^{2}\right)^{-1} $ is the variance effective selection mass for the mean, as used in the CMA tutorial. Thus $\mu_{\textrm{cov}} = \sqrt{\mu_{\textrm{eff}}}$ # class CMAES: """Naive CMA implementation""" def __init__(self, initial_mean, sigma, popsize, **kwargs): """Please do all the initialization. The reserve space and code for collecting the statistics are already provided.""" # Things that evolve : centroid, sigma, paths etc. self.centroid = """fill""" self.sigma = """fill""" # pc is the path taken by the covariance matrix self.pc = """fill""" # ps is the path taken by sigma / step-size updates self.ps = """fill""" self.C = """fill""" self.B = """fill""" self.diagD = """fill""" # Population size etc. self.popsize = popsize self.mu = """fill""" # Update weights self.weights = """fill""" # Utility variables self.dim = initial_mean.shape[0] # Expectation of a normal distribution self.chiN = np.sqrt(self.dim) * (1.0 - 0.25 / self.dim + 1.0/(21.0 * self.dim**2)) self.mueff = """fill""" self.generations = 0 # Options # Sigma adaptation # cs is short for c_sigma self.cs = """fill""" # ds is short for d_sigma self.ds = """fill""" # Covariance adaptation self.cc = """fill""" self.ccov = """fill""" # If implementing the latest version of CMA according to the tutorial, # these parameters can be useful, if not that avoid self.ccov1 = 0.0 self.ccovmu = 0.0 ### Asserts to guide you on your paths # .--. # ::\`--._,'.::.`._.--'/:: Do or do not. # ::::. ` __::__ ' .:::: There is no try. # ::::::-:.`'..`'.:-:::::: # ::::::::\ `--' /:::::::: -Yoda assert self.dim == 2, "We are dealing with a two-dimensional problem only" assert self.centroid.shape == (2,), "Centroid shape is incorrect, did you tranpose it by mistake?" assert self.sigma > 0.0, "Sigma is not a non-zero positive number!" assert self.pc.shape == (2, ), "pc shape is incorrect, did you tranpose it by mistake?" assert self.ps.shape == (2, ), "ps shape is incorrect, did you tranpose it by mistake?" assert self.C.shape == (2, 2), "C's shape is incorrect, remember C is a matrix!" assert type(self.popsize) == int, "Population size not an integer" assert self.popsize > 0 , "Population size is negative!" assert self.popsize > 2 , "Too little population size, make it >2" # Collect useful statistics self.stats_centroids = [] self.stats_new_centroids = [] self.stats_covs = [] self.stats_new_covs = [] self.stats_offspring = [] self.stats_offspring_weights = [] self.stats_ps = [] def run(self, problem): while (# fill in your termination criterion here): # Sample the population here! # Its convenient to do it as a list of members population = """fill""" # Pass the population to update, which computes all new parameters # while sorting the populatoin self.update(problem, population) # increment generation counter self.generations += 1 else: # returns the best individual at the last generation return population[0] def update(self, problem, population): """Update the current covariance matrix strategy from the *population*. :param population: A list of individuals from which to update the parameters. """ # -- store current state of the algorithm self.stats_centroids.append(copy.deepcopy(self.centroid)) self.stats_covs.append(copy.deepcopy(self.C)) # Sort the population here and work with only the sorted population """FILL : Python code to sort population goes here""" # -- store sorted offspring self.stats_offspring.append(copy.deepcopy(population)) # Store old centroid in-case old_centroid = self.centroid # Update centroid to self.centroid here self.centroid = """FILL : Code to calculate new centroid/mean""" # -- store new centroid self.stats_new_centroids.append(copy.deepcopy(self.centroid)) # Cumulation : update evolution path # Remember to use self.B, self.diagD wihch we store later # See line 142-145 self.ps = """FILL : Code to calculate new sigma path update""" # -- store new evol path self.stats_ps.append(copy.deepcopy(self.ps)) # Cumulation : update evolution path for centroid self.pc = """FILL : Code to calculate new centroid path update""" # Update covariance matrix self.C = """FILL : Code to calculate new covariance matrix """ # -- store new covs self.stats_new_covs.append(copy.deepcopy(self.C)) # Update new sigma in-place, can be done before too self.sigma *= """FILL : Code to calculate update sigma """ # Get the eigen decomposition for the covariance matrix to calculate inverse diagD_squared, self.B = """FILL : Code to calculate eigenvalues and eigenvectors """ self.diagD = """ Fill in D : Do we need to sort it?""" self.B = """ Fill in B : Do we need to sort it?""" def reset(self): """Clears everything to rerun the problem""" pass initial_centroid = np.random.randn(2, ) cma_es = CMAES(initial_centroid, 0.2, 10) cma_es.run(current_problem) # ### Visualizing CMA-ES progress # First some setup code. This visualizes the progress of CMA based on the data we recorded in the class above and plots it in the objective function manifold. normalizer = colors.Normalize(vmin=np.min(cma_es.weights), vmax=np.max(cma_es.weights)) sm = cm.ScalarMappable(norm=normalizer, cmap=plt.get_cmap('gray')) from matplotlib import animation from IPython.display import HTML def animate_cma_es(gen): ax.cla() plot_problem_contour(current_problem, ((-11,-11), (11,11)), optimum=(0,0), ax=ax) plot_cov_ellipse(cma_es.stats_centroids[gen], cma_es.stats_covs[gen], volume=0.99, alpha=0.29, fc='red', ec='darkred', ax=ax) ax.plot(cma_es.stats_centroids[gen][0], cma_es.stats_centroids[gen][1], 'ro', markeredgecolor = 'none', ms=10) plot_cov_ellipse(cma_es.stats_new_centroids[gen], cma_es.stats_new_covs[gen], volume=0.99, alpha=0.29, fc='green', ec='darkgreen', ax=ax) ax.plot(cma_es.stats_new_centroids[gen][0], cma_es.stats_new_centroids[gen][1], 'go', markeredgecolor = 'none', ms=10) for i in range(gen+1): if i == 0: ax.plot((0,cma_es.stats_ps[i][0]), (0,cma_es.stats_ps[i][1]), 'b--') else: ax.plot((cma_es.stats_ps[i-1][0],cma_es.stats_ps[i][0]), (cma_es.stats_ps[i-1][1],cma_es.stats_ps[i][1]),'b--') for i,ind in enumerate(cma_es.stats_offspring[gen]): if i < len(cma_es.weights): color = sm.to_rgba(cma_es.weights[i]) else: color= sm.to_rgba(normalizer.vmin) ax.plot(ind[0], ind[1], 'o', color = color, ms=5, markeredgecolor = 'none') ax.set_ylim((-10,10)) ax.set_xlim((-10,10)) ax.set_title('$generation=$' +str(gen)) return [] fig = plt.figure(figsize=(10,10)) ax = fig.gca() anim = animation.FuncAnimation(fig, animate_cma_es, frames=cma_es.generations, interval=300, blit=True) plt.close() # In the animation below : # * Current centroid and covariance: **red**. # * Updated centroid and covariance: **green**. # * Sampled individuals: **shades of gray representing their corresponding weight**. (White is best) # * Evolution path: **blue line starting in (0,0)**. HTML(anim.to_html5_video())
lectures/03_cma/code/cmaes_questions.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 # --- # # Convexity # # Convexity plays a vital role in the design of optimization algorithms. This is largely due to the fact that it is much easier to analyze and test algorithms in this context. In other words, if the algorithm performs poorly even in the convex setting we should not hope to see great results otherwise. Furthermore, even though the optimization problems in deep learning are generally nonconvex, they often exhibit some properties of convex ones near local minima. This can lead to exciting new optimization variants such as [Stochastic Weight Averaging](https://arxiv.org/abs/1803.05407) by Izmailov et al., 2018. Let's begin with the basics. # # ## Basics # # # ### Sets # # Sets are the basis of convexity. Simply put, a set $X$ in a vector space is convex if for any $a, b \in X$ the line segment connecting $a$ and $b$ is also in $X$. In mathematical terms this means that for all $\lambda \in [0,1]$ we have # # $$\lambda \cdot a + (1-\lambda) \cdot b \in X \text{ whenever } a, b \in X.$$ # # This sounds a bit abstract. Consider the picture below. The first set isn't convex since there are line segments that are not contained in it. The other two sets suffer no such problem. # # ![Three shapes, the left one is nonconvex, the others are convex](../img/pacman.svg) # # Definitions on their own aren't particularly useful unless you can do something with them. In this case we can look at unions and intersections. Assume that $X$ and $Y$ are convex sets. Then $X \cap Y$ is also convex. To see this, consider any $a, b \in X \cap Y$. Since $X$ and $Y$ are convex, the line segments connecting $a$ and $b$ are contained in both $X$ and $Y$. Given that, they also need to be contained in $X \cap Y$, thus proving our first theorem. # # ![The intersection between two convex sets is convex](../img/convex-intersect.svg) # # We can strengthen this result with little effort: given convex sets $X_i$, their intersection $\cap_{i} X_i$ is convex. # To see that the converse is not true, consider two disjoint sets $X \cap Y = \emptyset$. Now pick $a \in X$ and $b \in Y$. The line segment connecting $a$ and $b$ needs to contain some part that is neither in $X$ nor $Y$, since we assumed that $X \cap Y = \emptyset$. Hence the line segment isn't in $X \cup Y$ either, thus proving that in general unions of convex sets need not be convex. # # ![The union of two convex sets need not be convex](../img/nonconvex.svg) # # Typically the problems in deep learning are defined on convex domains. For instance $\mathbb{R}^d$ is a convex set (after all, the line between any two points in $\mathbb{R}^d$ remains in $\mathbb{R}^d$). In some cases we work with variables of bounded length, such as balls of radius $r$ as defined by $\{\mathbf{x} | \mathbf{x} \in \mathbb{R}^d \text{ and } \|\mathbf{x}\|_2 \leq r\}$. # # ### Functions # # Now that we have convex sets we can introduce convex functions $f$. Given a convex set $X$ a function defined on it $f: X \to \mathbb{R}$ is convex if for all $x, x' \in X$ and for all $\lambda \in [0,1]$ we have # # $$\lambda f(x) + (1-\lambda) f(x') \geq f(\lambda x + (1-\lambda) x').$$ # # To illustrate this let's plot a few functions and check which ones satisfy the requirement. We need to import a few libraries. # import sys sys.path.insert(0, '..') # %matplotlib inline import d2l d2l.use_svg_display() from mpl_toolkits import mplot3d import matplotlib.pyplot as plt import numpy as np # Let's define a few functions, both convex and nonconvex. def f(x): return 0.5 * x**2 # convex def g(x): return np.cos(np.pi * x) # nonconvex def h(x): return np.exp(0.5 * x) # convex x, segment = np.arange(-2, 2, 0.01), np.array([-1.5, 1]) _, figarr = d2l.plt.subplots(1, 3, figsize=(9, 3)) for fig, func in zip(figarr, [f, g, h]): fig.plot(x, func(x)) fig.plot(segment, func(segment)) # As expected, the cosine function is nonconvex, whereas the parabola and the exponential function are. Note that the requirement that $X$ is necessary for the condition to make sense. Otherwise the outcome of $f(\lambda x + (1-\lambda) x')$ might not be well defined. Convex functions have a number of desirable properties. # # ### Jensen's Inequality # # One of the most useful tools is Jensen's inequality. It amounts to a generalization of the definition of convexity. # # $$\begin{aligned} # \sum_i \alpha_i f(x_i) & \geq f\left(\sum_i \alpha_i x_i\right) \\ # \text{ and } # \mathbf{E}_x[f(x)] & \geq f\left(\mathbf{E}_x[x]\right) # \end{aligned}$$ # # In other words, the expectation of a convex function is larger than the convex function of an expectation. To prove the first inequality we repeatedly apply the definition of convexity to one term in the sum at a time. The expectation can be proven by taking the limit over finite segments. # # One of the common applications of Jensen's inequality is with regard to the log-likelihood of partially observed random variables. That is, we use # # $$\mathbf{E}_{y \sim p(y)}[-\log p(x|y)] \geq -\log p(x).$$ # # This follows since $\int p(y) p(x|y) dy = p(x)$. # This is used in variational methods. Here $y$ is typically the unobserved random variable, $p(y)$ is the best guess of how it might be distributed and $p(x)$ is the distribution with $y$ integrated out. For instance, in clustering $y$ might be the cluster labels and $p(x|y)$ is the generative model when applying cluster labels. # # # ## Properties # # ### No Local Minima # # In particular, convex functions do not have local minima. Let's assume the contrary and prove it wrong. If $x \in X$ is a local minimum there exists some neighborhood of $x$ for which $f(x)$ is the smallest value. Since $x$ is only a local minimum there has to be another $x' \in X$ for which $f(x') < f(x)$. However, by convexity the function values on the entire *line* $\lambda x + (1-\lambda) x'$ have to be less than $f(x')$ since for $\lambda \in [0, 1)$ # # $$f(x) > \lambda f(x) + (1-\lambda) f(x') \geq f(\lambda x + (1-\lambda) x').$$ # # This contradicts the assumption that $f(x)$ is a local minimum. For instance, the function $f(x) = (x+1) (x-1)^2$ has a local minimum for $x=1$. However, it is not a global minimum. def f(x): return (x-1)**2 * (x+1) d2l.set_figsize() fig, = d2l.plt.plot(x, f(x)) fig, = d2l.plt.plot(segment, f(segment)) # The fact that convex functions have no local minima is very convenient. It means that if we minimize functions we cannot 'get stuck'. Note, though, that this doesn't means that there cannot be more than one global minimum or that there might even exist one. For instance, the function $f(x) = \mathrm{max}(|x|-1, 0)$ attains its minimum value over the interval $[-1, 1]$. Conversely, the function $f(x) = \exp(x)$ does not attain a minimum value on $\mathbb{R}$. For $x \to -\infty$ it asymptotes to $0$, however there is no $x$ for which $f(x) = 0$. # # ### Convex Functions and Sets # # Convex functions define convex sets as *below-sets*. They are defined as # # $$S_b := \{x | x \in X \text{ and } f(x) \leq b\}.$$ # # Such sets are convex. Let's prove this quickly. Remember that for any $x, x' \in S_b$ we need to show that $\lambda x + (1-\lambda) x' \in S_b$ as long as $\lambda \in [0,1]$. But this follows directly from the definition of convexity since $f(\lambda x + (1-\lambda) x') \leq \lambda f(x) + (1-\lambda) f(x') \leq b$. # # Have a look at the function $f(x,y) = 0.5 x^2 + \cos(2 \pi y)$ below. It is clearly nonconvex. The level sets are correspondingly nonconvex. In fact, they're typically composed of disjoint sets. # x, y = np.mgrid[-1: 1: 101j, -1: 1: 101j] z = x**2 + 0.5 * np.cos(2 * np.pi * y) # Plot the 3D surface d2l.set_figsize((6,4)) ax = d2l.plt.figure().add_subplot(111, projection='3d') ax.plot_wireframe(x, y, z, **{'rstride': 2, 'cstride': 2}) ax.contour(x, y, z, offset=-1) ax.set_zlim(-1, 1.5) # Adjust labels for func in [plt.xticks, plt.yticks, ax.set_zticks]: func([-1,0,1]) plt.show() # ### Derivatives and Convexity # # Whenever the second derivative of a function exists it is very easy to check for convexity. All we need to do is check whether $\partial_x^2 f(x) \succeq 0$, i.e. whether all of its eigenvalues are nonnegative. For instance, the function $f(\mathbf{x}) = \frac{1}{2} \|\mathbf{x}\|^2_2$ is convex since $\partial_{\mathbf{x}}^2 f = \mathbf{1}$, i.e. its derivative is the identity matrix. # # The first thing to realize is that we only need to prove this property for one-dimensional functions. After all, in general we can always defing some function $g(z) = f(\mathbf{x} + z \cdot \mathbf{v})$. This function has the first and second derivatives $g' = (\partial_{\mathbf{x}} f)^\top \mathbf{v}$ and $g'' = \mathbf{v}^\top (\partial^2_{\mathbf{x}} f) \mathbf{v}$ respectively. In particular, $g'' \geq 0$ for all $\mathbf{v}$ whenever the Hessian of $f$ is positive semidefinite, i.e. whenever all of its eigenvalues are greater equal than zero. Hence back to the scalar case. # # To see that $f''(x) \geq 0$ for convex functions we use the fact that # # $$\frac{1}{2} f(x + \epsilon) + \frac{1}{2} f(x - \epsilon) \geq f\left(\frac{x + \epsilon}{2} + \frac{x - \epsilon}{2}\right) = f(x)$$ # # Since the second derivative is given by the limit over finite differences it follows that # # $$f''(x) = \lim_{\epsilon \to 0} \frac{f(x+\epsilon) + f(x - \epsilon) - 2f(x)}{\epsilon} \geq 0.$$ # # To see that the converse is true we use the fact that $f'' \geq 0$ implies that $f'$ is a monotonically increasing function. Let $a < x < b$ be three points in $\mathbb{R}$. We use the mean value theorem to express # # $$\begin{aligned} # f(x) - f(a) & = (x-a) f'(\alpha) \text{ for some } \alpha \in [a,x] \text{ and } \\ # f(b) - f(x) & = (b-x) f'(\beta) \text{ for some } \beta \in [x,b]. # \end{aligned}$$ # # By monotonicity $f'(\beta) \geq f'(\alpha)$, hence # # $$\begin{aligned} # f(b) - f(a) & = f(b) - f(x) + f(x) - f(a) \\ # & = (b-x) f'(\beta) + (x-a) f'(\alpha) \\ # & \geq (b-a) f'(\alpha). # \end{aligned}$$ # # By geometry it follows that $f(x)$ is below the line connecting $f(a)$ and $f(b)$, thus proving convexity. We omit a more formal derivation in favor of a graph below. def f(x): return 0.5 * x**2 x, axb, ab = np.arange(-2, 2, 0.01), np.array([-1.5, -0.5, 1]), np.array([-1.5, 1]) d2l.set_figsize() for data in [x, axb, ab]: fig, = d2l.plt.plot(data, f(data)) _ = fig.axes.annotate('a', xy=(-1.5, f(-1.5)), xytext=(-1.5, 1.5), arrowprops=dict(arrowstyle='->')) _ = fig.axes.annotate('b', xy=(1, f(1)), xytext=(1, 1.5), arrowprops=dict(arrowstyle= '->')) _ = fig.axes.annotate('x', xy=(-0.5, f(-0.5)), xytext=(-1.5, f(-0.5)), arrowprops=dict(arrowstyle='->')) # ## Constraints # # One of the nice properties of convex optimization is that it allows us to handle constraints efficiently. That is, it allows us to solve problems of the form: # # $$\begin{aligned} \mathop{\mathrm{minimize~}}_{\mathbf{x}} & f(\mathbf{x}) \\ # \text{ subject to } & c_i(\mathbf{x}) \leq 0 \text{ for all } i \in \{1, \ldots N\} # \end{aligned}$$ # # Here $f$ is the objective and the functions $c_i$ are constraint functions. To see what this does consider the case where $c_1(\mathbf{x}) = \|\mathbf{x}\|_2 - 1$. In this case the parameters $\mathbf{x}$ are constrained to the unit ball. If a second constraint is $c_2(\mathbf{x}) = \mathbf{v}^\top \mathbf{x} + b$, then this corresponds to all $\mathbf{x}$ lying on a halfspace. Satisfying both constraints simultaneously amounts to selecting a slice of a ball as the constraint set. # # ### Lagrange Function # # In general, solving a constrained optimization problem is difficult. One way of addressing it stems from physics with a rather simple intuition. Imagine a ball inside a box. The ball will roll to the place that is lowest and the forces of gravity will be balanced out with the forces that the sides of the box can impose on the ball. In short, the gradient of the objective function (i.e. gravity) will be offset by the gradient of the constraint function (need to remain inside the box by virtue of the walls 'pushing back'). Note that any constraint that is not active (i.e. the ball doesn't touch the wall) will not be able to exert any force on the ball. # # Skipping over the derivation of the Lagrange function $L$ (see e.g. the book by [<NAME>, 2004](https://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf) for details) the above reasoning can be expressed via the following saddlepoint optimization problem: # # $$L(\mathbf{x},\alpha) = f(\mathbf{x}) + \sum_i \alpha_i c_i(\mathbf{x}) \text{ where } \alpha_i \geq 0$$ # # Here the variables $\alpha_i$ are the so-called *Lagrange Multipliers* that ensure that a constraint is properly enforced. They are chosen just large enough to ensure that $c_i(\mathbf{x}) \leq 0$ for all $i$. For instance, for any $\mathbf{x}$ for which $c_i(\mathbf{x}) < 0$ naturally, we'd end up picking $\alpha_i = 0$. Moreover, this is a *saddlepoint* optimization problem where one wants to *maximize* $L$ with respect to $\alpha$ and simultaneously *minimize* it with respect to $\mathbf{x}$. There is a rich body of literature explaining how to arrive at the function $L(\mathbf{x}, \alpha)$. For our purposes it is sufficient to know that the saddlepoint of $L$ is where the original constrained optimization problem is solved optimally. # # ### Penalties # # One way of satisfying constrained optimization problems at least approximately is to adapt the Lagrange function $L$. Rather than satisfying $c_i(\mathbf{x}) \leq 0$ we simply add $\alpha_i c_i(\mathbf{x})$ to the objective function $f(x)$. This ensures that the constraints won't be violated too badly. # # In fact, we've been using this trick all along. Consider [weight-decay regularization](../chapter_multilayer-perceptrons/weight-decay.md). In it we add $\frac{\lambda}{2} \|\mathbf{w}\|^2$ to the objective function to ensure that $\mathbf{w}$ doesn't grow too large. Using the constrained optimization point of view we can see that this will ensure that $\|\mathbf{w}\|^2 - r^2 \leq 0$ for some radius $r$. Adjusting the value of $\lambda$ allows us to vary the size of $\mathbf{w}$. # # In general, adding penalties is a good way of ensuring approximate constraint satisfaction. In practice this turns out to be much more robust than exact satisfaction. Furthermore, for nonconvex problems many of the properties that make the exact approach so appealing in the convex case (e.g. optimality) no longer hold. # # ### Projections # # An alternative strategy for satisfying constraints are projections. Again, we encountered them before, e.g. when dealing with [gradient clipping](../chapter_recurrent-neural-networks/rnn-scratch.md). There we ensured that a gradient has length bounded by $c$ via # # $$\mathbf{g} \leftarrow \mathbf{g} \cdot \mathrm{min}(1, c/\|\mathbf{g}\|).$$ # # This turns out to be a *projection* of $g$ onto the ball of radius $c$. More generally, a projection on a (convex) set $X$ is defined as # # $$\mathrm{Proj}_X(\mathbf{x}) = \mathop{\mathrm{argmin}}_{\mathbf{x}' \in X} \|\mathbf{x} - \mathbf{x}'\|_2$$ # # It is thus the closest point in $X$ to $\mathbf{x}$. This sounds a bit abstract. The figure below explains it somewhat more clearly. In it we have two convex sets, a circle and a diamond. Points inside the set (yellow) remain unchanged. Points outside the set (black) are mapped to the closest point inside the set (red). While for $\ell_2$ balls this leaves the direction unchanged, this need not be the case in general, as can be seen in the case of the diamond. # # ![Convex Projections](../img/projections.svg) # # One of the uses for convex projections is to compute sparse weight vectors. In this case we project $\mathbf{w}$ onto an $\ell_1$ ball (the latter is a generalized version of the diamond in the picture above). # # ## Summary # # In the context of deep learning the main purpose of convex functions is to motivate optimization algorithms and help us understand them in detail. In the following we will see how gradient descent and stochastic gradient descent can be derived accordingly. # # * Intersections of convex sets are convex. Unions are not. # * The expectation of a convex function is larger than the convex function of an expectation (Jensen's inequality). # * A twice-differentiable function is convex if and only if its second derivative has only nonnegative eigenvalues throughout. # * Convex constraints can be added via the Lagrange function. In practice simply add them with a penalty to the objective function. # * Projections map to points in the (convex) set closest to the original point. # # ## Exercises # # 1. Assume that we want to verify convexity of a set by drawing all lines between points within the set and checking whether the lines are contained. # * Prove that it is sufficient to check only the points on the boundary. # * Prove that it is sufficient to check only the vertices of the set. # 1. Denote by $B_p[r] := \{\mathbf{x} | \mathbf{x} \in \mathbb{R}^d \text{ and } \|\mathbf{x}\|_p \leq r\}$ the ball of radius $r$ using the $p$-norm. Prove that $B_p[r]$ is convex for all $p \geq 1$. # 1. Given convex functions $f$ and $g$ show that $\mathrm{max}(f,g)$ is convex, too. Prove that $\mathrm{min}(f,g)$ is not convex. # 1. Prove that the normalization of the softmax function is convex. More specifically prove the convexity of # $f(x) = \log \sum_i \exp(x_i)$. # 1. Prove that linear subspaces are convex sets, i.e. $X = \{\mathbf{x} | \mathbf{W} \mathbf{x} = \mathbf{b}\}$. # 1. Prove that in the case of linear subspaces with $\mathbf{b} = 0$ the projection $\mathrm{Proj}_X$ can be written as $\mathbf{M} \mathbf{x}$ for some matrix $\mathbf{M}$. # 1. Show that for convex twice differentiable functions $f$ we can write $f(x + \epsilon) = f(x) + \epsilon f'(x) + \frac{1}{2} \epsilon^2 f''(x + \xi)$ for some $\xi \in [0, \epsilon]$. # 1. Given a vector $\mathbf{w} \in \mathbb{R}^d$ with $\|\mathbf{w}\|_1 > 1$ compute the projection on the $\ell_1$ unit ball. # * As intermediate step write out the penalized objective $\|\mathbf{w} - \mathbf{w}'\|_2^2 + \lambda \|\mathbf{w}'\|_1$ and compute the solution for a given $\lambda > 0$. # * Can you find the 'right' value of $\lambda$ without a lot of trial and error? # 1. Given a convex set $X$ and two vectors $\mathbf{x}$ and $\mathbf{y}$ prove that projections never increase distances, i.e. $\|\mathbf{x} - \mathbf{y}\| \geq \|\mathrm{Proj}_X(\mathbf{x}) - \mathrm{Proj}_X(\mathbf{y})\|$.
Ch12_Optimization_Algorithms/Convexity.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: PyCharm (dd_1) # language: python # name: pycharm-89f95e86 # --- # ### Lambdas and Sorting # Python has a built-in **sorted** method that can be used to sort any iterable. It will use the default ordering of the particular items, but sometimes you may want to (or need to) specify a different criteria for sorting. # Let's start with a simple list: l = ['a', 'B', 'c', 'D'] sorted(l) # As you can see there is a difference between upper and lower-case characters when sorting strings. # # What if we wanted to make a case-insensitive sort? # # Python's **sorted** function kas a keyword-only argument that allows us to modify the values that are used to sort the list. sorted(l, key=str.upper) # We could have used a lambda here (but you should not, this is just to illustrate using a lambda in this case): sorted(l, key = lambda s: s.upper()) # Let's look at how we might create a sorted list from a dictionary: d = {'def': 300, 'abc': 200, 'ghi': 100} d sorted(d) # What happened here? # # Remember that iterating dictionaries actually iterates the keys - so we ended up with tyhe keys sorted alphabetically. # # What if we want to return the keys sorted by their associated value instead? sorted(d, key=lambda k: d[k]) # Maybe we want to sort complex numbers based on their distance from the origin: def dist(x): return (x.real)**2 + (x.imag)**2 l = [3+3j, 1+1j, 0] # Trying to sort this list directly won't work since Python does not have an ordering defined for complex numbers: sorted(l) # Instead, let's try to specify the key using the distance: sorted(l, key=dist) # Of course, if we're only going to use the **dist** function once, we can just do the same thing this way: sorted(l, key=lambda x: (x.real)**2 + (x.imag)**2) # And here's another example where we want to sort a list of strings based on the **last character** of the string: l = ['Cleese', 'Idle', 'Palin', 'Chapman', 'Gilliam', 'Jones'] sorted(l) sorted(l, key=lambda s: s[-1])
dd_1/Part 1/Section 06 - First-Class Functions/03 - Lambdas and Sorting.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 matplotlib.pyplot as plt from __future__ import print_function from ipywidgets import interact, interactive, fixed import ipywidgets as widgets # - def f(x): print("%s! = %s" % (x, np.math.factorial(x))) interact(f, x=(0, 100)) def plt_array(x, y, title="", color="red", linestyle="dashed"): fig = plt.figure() #maybe make this higher res axes = fig.add_subplot(111) # this makes each of our axis praportinal to eachother sense they are 111 axes.plot(x, y, color=color, linestyle=linestyle) axes.set_title(title) axes.grid() plt.show() plt_array([1,2], [1,5]) # $f(x) = ax^3 + bx^2 + cx + d$ def f(a, b, c, d, **kwargs): x = np.linspace(-10,10, 20) y = a*(x**3) + b*(x**2) + c*x +d title = "$f(x) = (%s)x^{3} + (%s)x^{2} + (%s)x + (%s)$" %(a,b,c,d) plt_array(x,y, title=title, **kwargs) f(3, 4, 2, 1) i = interact(f, a=(-10., 10), b=(-10., 10), c=(-50., 50), d=(-10, 10), color = ["red", "green", "blue", "black"], linestyle=["solid", "dashed"] )
jupyter-notebooks/miscellaneous/IPython Widgets.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- # | [Table of Contents](#table_of_contents) | [Data and model](#data_and_model) | [Modeling](#modeling) | [Residual diagnostics](#residual_diagnostics) | [Fitting summary](#fitting_summary) | [Session info](#session_info) | [References](#references) | # **Authors:** <NAME>, <NAME>, <NAME> <br> *[Faculty of Science](https://www.upjs.sk/en/faculty-of-science/?prefferedLang=EN), P. J. Šafárik University in Košice, Slovakia* <br> emails: [<EMAIL>](mailto:<EMAIL>), [<EMAIL>](mailto:<EMAIL>) # *** # **<font size=6 color=brown> FDSLRM applications - Strikes </font>** # # <font size=5> Number of strikes in the USA </font> # # <a id=table_of_contents></a> # ### Table of Contents # * [Data and model](#data_and_model) - data and model description, estimating parameters, software # * [Modeling](#modeling) - loading R functions and packages, data plot, periodogram # * [Residual diagnostics](#residual_diagnostics) - description of graphical tools, numerical tests # * [Fitting summary](#fitting_summary) - estimated model parameters, fit summary # * [Session info](#session_info) - list of applied R packages in computations # * [References](#references) - list of detailed references for data and applied methods # # **To get back to the contents, use <font color=brown>the Home key</font>.** # *** # <a id=data_and_model></a> # # <font color=brown>Data and model </font> # # # ### Data description # # In this FDSLRM application we model the time series data set, denoted as `strikes`, representing *number of strikes*. The number of time series observations is $n=30$, the correspoding plot with more details is shown in the following section **_Modeling_**. The data was adapted from *<NAME>, 2016*. # # # ### Model description # # The mink trappings data can be succesfully fitted by the FDSLRM of the form: # # $$ Z(t)=\beta_1+\beta_2\cos\left(\tfrac{2\pi t}{30}\right)+\beta_3\sin\left(\tfrac{2\pi t\cdot}{30}\right)+\beta_4\sin\left(\tfrac{2\pi t\cdot 2}{30}\right) # +w(t), \, t\in \mathbb{N},$$ # # where $Z(t)=log(X(t))$ is the logarithmic transformation of the orginal data to make the variance more stable so that we can achieve the better fit. # # ### Computational software # As for numerical calculations, we conducted our computations in _the R statistical computing language_ (https://www.r-project.org; _R Development Core Team, 2019_) and with R functions designed to work with FDSLRM programmed by authors of the Jupyter notebook included in _fdslrm_ (Gajdoš et. al., 2019) package. The complete list of used R libraries is included in **_Session info_**. # >### Important note # >The iterative model building was done analogically as in our extended application examples # >* [Tourism](Tourism.ipynb) # >* [Cyber attacks](Cyberattacks.ipynb) # > # >with more details about modelling procedure, diagnostic tools and technical information. # > # >These two illustrative examples also belong to real data set illustrative examples in our current paper **Hančová et al., 2019** about estimating FDSLRM variance parameters with detailed description of used procedures. # > # >* <NAME>., <NAME>., <NAME>., <NAME>. (2019). [Estimating variance components in time series # linear regression models using empirical BLUPs and convex optimization](https://arxiv.org/abs/1905.07771), https://arxiv.org/, 2019, suplementary materials - software, notebooks at GitHub, https://github.com/fdslrm/EBLUP-NE. # | [Table of Contents](#table_of_contents) | [Data and model](#data_and_model) | [Modeling](#modeling) | [Residual diagnostics](#residual_diagnostics) | [Fitting summary](#fitting_summary) | [Session info](#session_info) | [References](#references) | # *** # <a id=modeling></a> # # <font color=brown>Modeling </font> # ### Loading R functions and packages # use this cell, if you started this notebook locally in your PC library(fdslrm) initialFDSLRM() # use this cell, if you started this notebook in the Binder devtools::source_url("https://github.com/fdslrm/fdslrmAllinOne/blob/master/fdslrmAllinOne.R?raw=TRUE") initialFDSLRM() # ### Read data # # Number of strikes in the USA 1951-1980 (thousands). # reading data x <- ts(as.numeric(read.table("data/strikes.tsm", header = FALSE)[,1]), start = 1951, frequency = 1) # logarithmic transformation of data z <- log(x) # times t <- 1:length(z) # ### Data plot # + # IPython setting for output options(repr.plot.res=120, repr.plot.height=4.5, repr.plot.width=6.5) # plotting data plot(z, type = "o", xlab = "time", ylab = "log strikes") # - # ### Spectral analysis - Periodogram periodo <- spec.pgram(as.numeric(z), log="no") # #### Six most significant frequencies according to values of spectrum in periodogram drawTable(type = "periodogram", periodogram = periodo) # orders k for Fourier frequencies print(round(length(z)*c(0.0333333,0.0666667,0.3333333,0.1333333,0.1666667,0.4666667))) fnames= c("1/30", "$2/30$", "$10/30$", "$4/30$", "$5/30$", "$14/30$") drawTable(type = "periodogram", periodogram = periodo, frequencies = fnames) # | [Table of Contents](#table_of_contents) | [Data and model](#data_and_model) | [Modeling](#modeling) | [Residual diagnostics](#residual_diagnostics) | [Fitting summary](#fitting_summary) | [Session info](#session_info) | [References](#references) | # *** # <a id=residual_diagnostics></a> # # <font color=brown> Residual diagnostics </font> # ### Graphical (exploratory) tools # # > # >|$ $|$\large\mbox{Graphical-tools diagnostic matrix}$|$ $| # |---|------------------------------------------------|---| # | | # |$\mbox{linearity of fixed effects (L)}$| $\mbox{outlying observations (O1)}\hspace{0.75cm}$ | $\mbox{independence of cond. errors (ACF)} $ | # |**stand. marg. residuals vs marg. fitted values**|**stand. marg. residuals vs times**$\hspace{0.75cm}$|**ACF of cond. residuals**| # | | # |$\mbox{homoscedascity of cond. errors (H)}$|$\mbox{outlying observations (O2)}\hspace{0.75cm}$|$\mbox{independence of cond. errors (PACF)} $ | # |**stand. cond. residuals vs cond. predictions**|**stand. cond. residuals vs times**$\hspace{0.75cm}$|**PACF of cond. residuals**| # | | # |$\mbox{normality of cond. errors (N1)}$|$\mbox{normality of cond. errors (N2)}\hspace{0.75cm}$|$\mbox{normality of cond. errors (N3)} $ | # |**histogram of cond. residuals**|**histogram of stand. least conf. residuals**$\hspace{0.75cm}$|**stand. least conf. residuals vs $\mathcal{N}(0,1)$ quantiles**| # + # Fitting the final FDSLRM output <- fitDiagFDSLRM(as.numeric(z), t, c(1/30,2/30), include_fixed_eff = c(1,1,0,1), poly_trend_degree = 0) options(repr.plot.res=600, repr.plot.height=9, repr.plot.width=10) drawDiagPlots("all", output) # - # ### Numerical tests # #### Tests of residual independence print(output$Box_tests_stud_resid) print(output$BoxLjung_test_stud_resid) # #### Test of residual normality print(output$ShapiroWilk_test_raw_resid) print(output$ShapiroWilk_test_stud_resid) # | [Table of Contents](#table_of_contents) | [Data and model](#data_and_model) | [Modeling](#modeling) | [Residual diagnostics](#residual_diagnostics) | [Fitting summary](#fitting_summary) | [Session info](#session_info) | [References](#references) | # *** # <a id=fitting_summary></a> # # <font color=brown> Fitting summary </font> # ### Parameter estimates # #### Estimates of regression coefficients drawTable(type = "fixed", fixed_eff = output$fixed_effects) # #### Estimates of variance parameters output$error_variance # ### Fit summary # #### Graphical summary for the final model # * plot: **time series observations (black), fitted values (blue)** options(repr.plot.res=120, repr.plot.height=5, repr.plot.width=6.5) drawDiagPlots(output$diagnostic_plots_names$FittedTimeSeries, output) # #### Numerical summary for the final model print(output$fit_summary) # | [Table of Contents](#table_of_contents) | [Data and model](#data_and_model) | [Modeling](#modeling) | [Residual diagnostics](#residual_diagnostics) | [Fitting summary](#fitting_summary) | [Session info](#session_info) | [References](#references) | # *** # <a id=session_info></a> # # <font color=brown> Session info </font> print(sessionInfo()) # | [Table of Contents](#table_of_contents) | [Data and model](#data_and_model) | [Modeling](#modeling) | [Residual diagnostics](#residual_diagnostics) | [Fitting summary](#fitting_summary) | [Session info](#session_info) | [References](#references) | # *** # <a id=references></a> # # <font color=brown> References </font> # # # * <NAME>., <NAME>. (2016). [Introduction to Time Series and Forecasting (3rd ed.)](https://www.springer.com/la/book/9783319298528). New York, NY: Springer # # # * <NAME>., <NAME>., <NAME>. (2019), [R package for modeling and prediction of time series using linear mixed models](https://github.com/fdslrm/R-package), GitHub repository https://github.com/fdslrm/R-package # # # * R Core Team (2019). R: A language and environment for statistical computing. R Foundation for # Statistical Computing, Vienna, Austria. URL: https://www.R-project.org/ # | [Table of Contents](#table_of_contents) | [Data and model](#data_and_model) | [Modeling](#modeling) | [Residual diagnostics](#residual_diagnostics) | [Fitting summary](#fitting_summary) | [Session info](#session_info) | [References](#references) |
notebooks/Strikes.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="5juSWKWU_Jj5" colab_type="text" # # **Import** # + id="MCDeokrB_Lg-" colab_type="code" colab={} # !pip install keras-rl # !pip install music21 # + id="eIzEgKuy_MG3" colab_type="code" colab={} from google.colab import files import numpy as np from music21 import stream, converter, instrument, note, chord from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import LSTM from keras.layers import CuDNNLSTM from keras.layers import Activation from keras.utils import np_utils from keras.callbacks import ModelCheckpoint import pickle # + [markdown] id="oEnu0dyzAU9p" colab_type="text" # # **Data Import** # + id="WBjIsYHPAZwR" colab_type="code" colab={} uploaded = files.upload() fileNames = []; for fn in uploaded.keys(): fileNames.append(fn) # + [markdown] id="BC3y6kgR_VC9" colab_type="text" # # **Data Processing** # + id="IfJyORUZ_tu9" colab_type="code" colab={} ''' Parse all notes & chords in songs into strings ''' notes = [] for file in fileNames: midi = converter.parse(file) print("Parsing {}".format(file)) notes_to_parse = None try: # file has instrument s2 = instrument.partitionByInstrument(midi) notes_to_parse = s2.parts[0].recurse() except: # file has notes in a flat structure notes_to_parse = midi.flat.notes offset = 0 for element in notes_to_parse: if isinstance(element, note.Note): #note -> pitch,deltatime,velocity,duration.quarterLength n = ','.join([str(element.pitch), str(element.offset - offset), str(element.volume.velocity), str(element.duration.quarterLength)]) notes.append(n) offset = element.offset elif isinstance(element, chord.Chord): #chord -> note_note_note,deltatime,velocity,duration.quarterLength ns = '_'.join(str(n) for n in element.normalOrder) c = ','.join([ns, str(element.offset - offset), str(element.volume.velocity), str(element.duration.quarterLength)]) notes.append(c) offset = element.offset print(notes) # + id="PYxX9e_sBy3a" colab_type="code" colab={} ''' Create dictionary for notes ''' pitchnames = sorted(set(item for item in notes)) dictionary = dict((note, number) for number,note in enumerate(pitchnames)) print(dictionary) n_vocab = len(dictionary) # + id="r3tl6fxeEuwg" colab_type="code" colab={} ''' Prepare training data ''' WINDOW = 100 X = [] Y = [] for i in range(0, len(notes) - WINDOW, 1): x = notes[i:i + WINDOW] y = notes[i + WINDOW] X.append([dictionary[c] for c in x]) Y.append(dictionary[y]) dataSetSize = len(X) X = np.reshape(X, (dataSetSize, WINDOW, 1)) X = X / float(n_vocab) Y = np_utils.to_categorical(Y) print(X.shape) print(Y.shape) # + [markdown] id="dYxEnIjWGs01" colab_type="text" # # **Model Definition** # + id="6HSMQ84tGu2y" colab_type="code" colab={} model = Sequential() model.add(CuDNNLSTM(512, input_shape=(WINDOW, 1), return_sequences=True)) model.add(Dropout(0.3)) model.add(CuDNNLSTM(512)) model.add(Dense(256)) model.add(Dropout(0.3)) model.add(Dense(n_vocab)) model.add(Activation('softmax')) model.summary() # + [markdown] id="wC77BZszH4kV" colab_type="text" # # **Model Training** # + id="fMhi25A4H6eU" colab_type="code" colab={} model.compile(loss='categorical_crossentropy', optimizer='rmsprop') weights_filename = 'model_weights.h5f' checkpoint = ModelCheckpoint( weights_filename, monitor='loss', verbose=0 ) callbacks = [checkpoint] model.fit( X, Y, epochs=200, batch_size=200, callbacks=callbacks ) # + [markdown] id="b4wo_FFRLDwe" colab_type="text" # # **Music Generation** # + id="_4FNW3OmLFmd" colab_type="code" colab={} ''' Generate song ''' songlength = 500 seed = np.random.randint(0, len(X) - 1) reverse_dictionary = dict((number, note) for number, note in enumerate(pitchnames)) currentSequence = X[seed][:] generatedSong = [] for i in range(songlength): x = np.reshape(currentSequence, (1, len(currentSequence,), 1)) x = x / float(len(dictionary)) p = model.predict(x, verbose=0) index = np.argmax(p) result = reverse_dictionary[index] generatedSong.append(result) currentSequence = np.append(currentSequence, index) currentSequence = currentSequence[1 : len(currentSequence)] # + id="EXlh37HzNJzJ" colab_type="code" colab={} ''' Convert to midi ''' offset = 0 output_notes = [] for sequence in generatedSong: #if sequence is chord if('_' in sequence) or sequence.isdigit(): #chord : note_note_note,deltatime,velocity,duration.quarterLength chord = sequence.split(',') notes_in_chord = chord[0].split('_') deltatime = float(chord[1]) offset += deltatime velocity = float(chord[2]) duration = float(chord[3]) notes = [] for n in notes_in_chord: new_n = note.Note(int(n)) new_n.storedInstrument = instrument.Piano() notes.append(new_n) new_chord = chord.Chord(notes) new_chord.offset = offset new_chord.volume.velocity = velocity new_chord.duration.quarterLength = duration output_notes.append(new_chord) #if sequence is note else: #note : pitch,deltatime,velocity,duration.quarterLength n = sequence.split(',') pitch = n[0] deltatime = float(n[1]) offset += deltatime velocity = float(n[2]) duration = float(n[3]) new_n = note.Note(pitch) new_n.offset = offset new_n.volume.velocity = velocity new_n.duration.quarterLength = duration new_n.storedInstrument = instrument.Piano() output_notes.append(new_n) midi_stream = stream.Stream(output_notes) midi_stream.write('midi', fp='generatedSong/AI_ongaku.mid')
Prototype2.5_CharBasedwithFeaturesLSTM/CharacterBasedwithFeaturesLSTM.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import random # #### import data # + df = pd.read_csv('cluster.csv', header = None) # convert dataframe into numpy array X = df.values # - # #### Standardize the data points # + from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_sc = sc.fit_transform(X) # - # #### Define a function to calculate distances to centroids for all data points - can be further optimized (with the np.vectorize function etc.) def distance(points1, points2): distances = np.zeros(shape=(points1.shape[0], points2.shape[0])) distanceToCentroids = lambda point: \ np.array([np.linalg.norm(point - centroid) for centroid in points2],dtype = float) # Loop over data points: for i in range(points1.shape[0]): distances[i,] = distanceToCentroids(points1[i, ]) return(distances) # #### Define the function to iteratively get find the cluster centroids def k_centroids(X, n_clusters, init='k-means++' , precompute_distances='auto', n_init=10 , max_iter=300, tol=1e-4 # , random_state=None, n_jobs=1 # ,algorithm="auto", return_n_iter=False ): # X : array-like matrix, already standardized n_samples = X.shape[0] n_features = X.shape[1] # initialize the centroids # random sampling, can use other methods like kmeans++ centroids = X[random.sample(range(n_features), n_clusters), ] # calculate the distances to clusters, clustering labels and the resulting inertia distances = distance(X, centroids) labels = np.argmin(distances, axis = 1) inertia = np.sum((X - centroids[labels])**2, dtype=np.float64) # initiate an array to store the silhouette scores for all data points silhouettes = np.zeros(shape=(n_samples, )) for iteration in range(max_iter): n_samples_in_cluster = np.bincount(labels, minlength = n_clusters) # calculate the new centroids by taking the means of data points in the same cluster # this can be customized with other approaches like KMedoids centroids = np.zeros(shape = (n_clusters, n_features)) for i in range(n_samples): for j in range(n_features): centroids[labels[i], j] += X[i, j] centroids /= n_samples_in_cluster[:, np.newaxis] distances = distance(X, centroids) labels = np.argmin(distances, axis = 1) inertia_previous = inertia inertia = np.sum((X - centroids[labels])**2, dtype=np.float64) # calculate the silhouette scores for each data point based on the new clusters for i in range(n_samples): a_i = np.average(np.ma.masked_equal(distance(X[labels == labels[i,], ], X[i:i+1,]),0)) b_i = np.min(distance(X[labels != labels[i,], ], X[i:i+1,])) silhouettes[i,] = (b_i - a_i)/np.max([a_i, b_i]) if (np.linalg.norm(inertia - inertia_previous) < tol): break return(centroids, inertia, labels, silhouettes) centroids, inertia, labels, silhouettes = k_centroids(X_sc, 3) from sklearn.metrics import silhouette_samples, silhouette_score silhouette_avg = silhouette_score(X_sc, labels) sample_silhouette_values = silhouette_samples(X_sc, labels) silhouette_avg np.average(silhouettes) np.vstack((labels, silhouettes))
algorithms/centroidsClustering.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 # --- # # Task 1 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from scipy.io import loadmat import pandas as pd from mpl_toolkits.axes_grid1 import ImageGrid from sklearn.pipeline import Pipeline from sklearn.decomposition import PCA from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score,recall_score,precision_score,f1_score,roc_auc_score, confusion_matrix from sklearn.model_selection import RepeatedStratifiedKFold, GridSearchCV, train_test_split from sklearn.neighbors import KNeighborsClassifier import seaborn as sns from sklearn.preprocessing import StandardScaler from keras.preprocessing.image import ImageDataGenerator import random from sklearn.metrics import plot_confusion_matrix import joblib np.random.seed(31415) # ### Helper Functions # + jupyter={"source_hidden": true} def scree_plot(n_comp): n_comp = 30 pca = PCA(n_components=n_comp) pc = pca.fit_transform(data) scree_df = pd.DataFrame({'exp_var':pca.explained_variance_ratio_, 'PC':[i for i in range(1,n_comp+1)]}) colors = [n_comp * ['blue'] + (20-n_comp) * ['red'] ] scree_df['colors'] = colors[0] sns.barplot(x='PC',y="exp_var", data=scree_df, color="c"); plt.tight_layout() plt.xlabel('Principal Component') plt.ylabel('Explained Varaince') def pcplot2d(): n_comp = 20 pca = PCA(n_components=n_comp) pc = pca.fit_transform(data) pc_df = pd.DataFrame(data= pc, columns = [('PC' + str(i)) for i in range(1,n_comp+1)]) colors = [] for i in labels: if i == 0: colors.append('neutral') else: colors.append('smile') pc_df['class'] =colors sns.lmplot( x="PC1", y="PC2", data=pc_df, fit_reg=False, hue='class', legend=True, scatter_kws={"s": 80}) def pcplot3d(): pca = PCA(n_components=3) pc = pca.fit_transform(data) pc_df = pd.DataFrame(data= pc, columns = ['PC1','PC2','PC3']) fig = plt.figure() ax = Axes3D(fig) ax.scatter(pc_df['PC1'], pc_df['PC2'], pc_df['PC3'], c=labels,depthshade=False) def training_plot(model): results = pd.DataFrame(model.cv_results_) x = results['param_pca__n_components'] y = results['mean_test_score'] best_x = results[results['rank_test_score']==1]['param_pca__n_components'] best_y = results[results['rank_test_score']==1]['mean_test_score'] plt.figure(figsize=(6,4)) sns.lineplot(x,y) plt.scatter(best_x,best_y,c='red',label='Highest Accuracy') plt.xlabel('Number of Principal Components') plt.ylabel('Mean Accuracy Score') # plt.title('Bayes Models: Number of Principal Components') plt.legend(loc=(.6,0.08)) def training_time_plot(model): results = pd.DataFrame(model.cv_results_) x = results['param_pca__n_components'] y = results['mean_fit_time'] best_x = results[results['rank_test_score']==1]['param_pca__n_components'] best_y = results[results['rank_test_score']==1]['mean_fit_time'] plt.figure(figsize=(6,4)) sns.lineplot(x,y) plt.scatter(best_x,best_y,c='red',label='Highest Accuracy') plt.xlabel('Number of Principal Components') plt.ylabel('Mean Training Time') plt.legend() def model_eval(model, X_test, y_test): ypred = model.predict(X_test) results = {'Accuracy' : [accuracy_score(y_test, ypred)], 'F1': [f1_score(y_test, ypred)], 'Precision': [precision_score(y_test, ypred)], 'Recall': [recall_score(y_test, ypred)], 'AUC': [roc_auc_score(y_test, ypred)]} results_df = pd.DataFrame(results) # results_df = results_df.style.hide_index() return results_df def confusion_matrix(model, X_test, y_test, labels_list): ypred = model.predict(X_test) mat = confusion_matrix(y_test, ypred) sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False, xticklabels=labels_list, yticklabels=labels_list) plt.xlabel('true label') plt.ylabel('predicted label'); # + jupyter={"source_hidden": true} #load data chunks and converts to numpy arrays def load_data_chunks(): raw_face = np.array(loadmat('./data/data.mat')['face']) raw_pose = np.array(loadmat('./data/pose.mat')['pose']) raw_illum = np.array(loadmat('./data/illumination.mat')['illum']) aug_neutral = np.load('data/aug_neutral.npy', allow_pickle=True) aug_smile = np.load('data/aug_smile.npy', allow_pickle=True) return raw_face, (raw_pose, raw_illum), (aug_neutral,aug_smile) def make_dataset(raw_face, num_illum, split=.15): np.random.seed(31) neutral= list(raw_face[:,:,::3].reshape((24*21,200)).transpose()) smile = list(raw_face[:,:,1::3].reshape((24*21,200)).transpose()) illum = list(raw_face[:,:,2::3].reshape((24*21,200)).transpose()) np.random.shuffle(neutral) np.random.shuffle(smile) np.random.shuffle(illum) X_train, y_train, X_test, y_test = [],[],[],[] split_half = int((400*split)/2) for i in range(split_half): X_test.append(neutral.pop()) y_test.append(0) X_test.append(smile.pop()) y_test.append(1) for i in range(200-split_half): X_train.append(neutral.pop()) y_train.append(0) X_train.append(smile.pop()) y_train.append(1) for i in range(num_illum): X_train.append(illum.pop()) y_train.append(0) train = list(zip(X_train, y_train)) np.random.shuffle(train) train = np.array(train) X_train, y_train = train[:,0], train[:,1] X_train = np.array([X_train[i].reshape(504) for i in range(((200-split_half)*2) +num_illum)]) test = list(zip(X_test, y_test)) np.random.shuffle(test) test = np.array(test) X_test, y_test = test[:,0], test[:,1] X_test = np.array([X_test[i].reshape(504) for i in range(split_half*2)]) # print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) return X_train, y_train.astype(int), X_test, y_test.astype(int) # - # ## Data Exploration raw_face, _, _ = load_data_chunks() # scree_plot(n_comp=16) # pcplot2d() # + def bayes(): training_logs = {} testing_logs = {} augment, pca_param, acc, fone, prec, rec, au = [], [], [], [], [], [], [] for aug in [0,100,200]: X_train, y_train, X_test, y_test = make_dataset(raw_face, num_illum=aug, split=.15) X_train = X_train/255 X_test = X_test/255 #pipeline components scaler = StandardScaler() pca = PCA() gnb = GaussianNB() param_grid = { 'pca__n_components': [i for i in range(1,40)] } pipe = Pipeline(steps=[('pca', pca), ('bayes', gnb)]) search = GridSearchCV(pipe, param_grid, scoring='accuracy', n_jobs=-1, cv=5) search.fit(X_train, y_train) training = pd.DataFrame(search.cv_results_).sort_values(by='rank_test_score')[['rank_test_score', 'mean_test_score', 'std_test_score', 'param_pca__n_components']].head(5).set_index('rank_test_score') training_logs['training' + str(aug)] = training top_pca = list(training['param_pca__n_components']) accuracy, f1, precision, recall, auc = [], [], [], [], [] for i in range(5): pca = PCA(n_components=top_pca[i]) model = Pipeline(steps=[('pca', pca), ('bayes', gnb)]) model.fit(X_train, y_train) results = model_eval(model, X_test, y_test) accuracy.append(results['Accuracy'][0]) f1.append(results['F1'][0]) precision.append(results['Precision'][0]) recall.append(results['Recall'][0]) auc.append(results['AUC'][0]) testing = pd.DataFrame({'# of PC':top_pca, 'Accuracy':accuracy, 'F1':f1,'Precision':precision, 'Recall':recall, 'AUC':auc}) testing = testing.sort_values(by="Accuracy", ascending =False) testing_logs['testing' + str(aug)] = testing log_entry = testing.head(1).values augment.append(aug) pca_param.append(log_entry[0][0]) acc.append(log_entry[0][1]) fone.append(log_entry[0][2]) prec.append(log_entry[0][3]) rec.append(log_entry[0][4]) au.append(log_entry[0][5]) best_n = int(testing.head(1).values[0][0]) pca = PCA(n_components=best_n) best_model = Pipeline(steps=[('pca', pca), ('bayes', gnb)]) best_model.fit(X_train, y_train) best_model_log = pd.DataFrame({'Augmented': augment,'PC':pca_param, 'Accuracy':acc, 'F1':fone, 'Precision':prec, 'Recall':rec, 'AUC':au}) return best_model, best_model_log, training_logs, testing_logs def knn(): training_logs = {} testing_logs = {} augment, pca_param, knn_param, acc, fone, prec, rec, au = [], [], [], [], [], [], [], [] # each aug value represents the amount of augmented samples included in the training data for aug in [0,100,200]: X_train, y_train, X_test, y_test = make_dataset(raw_face, num_illum=aug, split=.15) X_train = X_train/255 X_test = X_test/255 #pipeline components pca = PCA() knn = KNeighborsClassifier() pipe = Pipeline(steps=[('pca', pca), ('knn', knn)]) param_grid = { 'pca__n_components': [i for i in range(1,31)], 'knn__n_neighbors' : [i for i in range(1,60)], } pipe = Pipeline(steps=[('pca', pca), ('knn', knn)]) search = GridSearchCV(pipe, param_grid, scoring='accuracy', n_jobs=-1, cv=5) search.fit(X_train, y_train) training = pd.DataFrame(search.cv_results_).sort_values(by='rank_test_score')[['rank_test_score', 'mean_test_score', 'param_pca__n_components', 'param_knn__n_neighbors']].head(5).set_index('rank_test_score') training_logs['training' + str(aug)] = training top_pca = list(training['param_pca__n_components']) top_n_knn = list(training['param_knn__n_neighbors']) accuracy, f1, precision, recall, auc = [], [], [], [], [] for i in range(5): pca = PCA(n_components=top_pca[i]) knn = KNeighborsClassifier(n_neighbors=top_n_knn[i]) model = Pipeline(steps=[('pca', pca), ('knn', knn)]) model.fit(X_train, y_train) results = model_eval(model, X_test, y_test) accuracy.append(results['Accuracy'][0]) f1.append(results['F1'][0]) precision.append(results['Precision'][0]) recall.append(results['Recall'][0]) auc.append(results['AUC'][0]) testing = pd.DataFrame({'# of PC':top_pca, '# of Neighbors': top_n_knn, 'Accuracy':accuracy, 'F1':f1,'Precision':precision, 'Recall':recall, 'AUC':auc }) testing = testing.sort_values(by="Accuracy", ascending =False) testing_logs['testing' + str(aug)] = testing log_entry = testing.head(1).values augment.append(aug) pca_param.append(log_entry[0][0]) knn_param.append(log_entry[0][1]) acc.append(log_entry[0][2]) fone.append(log_entry[0][3]) prec.append(log_entry[0][4]) rec.append(log_entry[0][5]) au.append(log_entry[0][6]) best_pca_param = int(testing.head(1).values[0][0]) best_knn_param = int(testing.head(1).values[0][1]) pca = PCA(n_components=best_pca_param) knn = KNeighborsClassifier(n_neighbors=best_knn_param) best_model = Pipeline(steps=[('pca', pca), ('knn', knn)]) best_model.fit(X_train, y_train) best_model_log = pd.DataFrame({'Augmented': augment,'PC':pca_param, '# of Neighbors': knn_param, 'Accuracy':acc, 'F1':fone, 'Precision':prec, 'Recall':rec, 'AUC':au}) return best_model, best_model_log, training_logs, testing_logs # - X_train, y_train, X_test, y_test = make_dataset(raw_face, num_illum=200, split=.15) X_train = X_train/255 X_test = X_test/255 best_bayes_model, bayes_model_log, bayes_training_logs, bayes_testing_logs = bayes() bayes_model_log plot_confusion_matrix(best_bayes_model, X_test, y_test, display_labels=['neutral','smile']) plt.title('Bayes Model') plt.show() #save best knn model joblib.dump(best_bayes_model, './models/face_bayes.pkl') best_knn_model, knn_model_log, training_logs, testing_logs = knn() knn_model_log testing_logs['testing200'] plot_confusion_matrix(best_knn_model, X_test, y_test, display_labels=['neutral','smile']) plt.title('knn') #save best knn model joblib.dump(best_knn_model, './models/face_knn.pkl')
.ipynb_checkpoints/Task1-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="RVgLw1YfBFnz" # <a href="https://githubtocolab.com/giswqs/geemap/blob/master/examples/notebooks/37_pydeck_3d.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a> # # Uncomment the following line to install [geemap](https://geemap.org) if needed. # + id="gcUFCCKaBFn7" # #!pip install geemap # #!pip install pydeck # #!pip install pydeck-earthengine-layers # + [markdown] id="RkyT0QXYBFn_" # # How to use Earth Engine with pydeck for 3D terrain visualization # Pydeck + Earth Engine: Terrain Visualization # # **Requirements** # # - [earthengine-api](https://github.com/google/earthengine-api): a Python client library for calling the Google Earth Engine API. # - [pydeck](https://pydeck.gl/index.html): a WebGL-powered framework for visual exploratory data analysis of large datasets. # - [pydeck-earthengine-layers](https://github.com/UnfoldedInc/earthengine-layers/tree/master/py): a pydekc wrapper for Google Earth Engine. For documentation please visit this [website](https://earthengine-layers.com/). # - [Mapbox API key](https://pydeck.gl/installation.html#getting-a-mapbox-api-key): you will need this add basemap tiles to pydeck. # # **Installation** # # - conda create -n deck python # - conda activate deck # - conda install mamba -c conda-forge # - mamba install earthengine-api pydeck pydeck-earthengine-layers -c conda-forge # - jupyter nbextension install --sys-prefix --symlink --overwrite --py pydeck # - jupyter nbextension enable --sys-prefix --py pydeck # + [markdown] id="hec9af88BFoA" # This example is adopted from [here](https://github.com/UnfoldedInc/earthengine-layers/blob/master/py/examples/terrain.ipynb). Credits to the developers of the [pydeck-earthengine-layers](https://github.com/UnfoldedInc/earthengine-layers) package. # + [markdown] id="V1kzZgTqBFoB" # ## 2D Visualization # + id="bgyVEWksBFoC" import ee import geemap # + colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["c78c253be1334cbf8f79755b211d9a40", "5aebf404f0994643a41301a87ec8f869", "665ec87bb34a4f5197288264334e1ec4", "ac0cbe6f178441f19b2e8fbd5d09c720", "358e431a6eaf45ca80f07ebdb666aae9", "<KEY>", "e6c0f2c67b0549b38ff4fd54a2600a70", "<KEY>", "135c75e14feb41bb88584ec0f05b73b0", "c8dff798950c4d2ba4774164d7672cca", "002cac3d47f34e328229ab1d0bd79600", "fae56ac7610345d79422ee52e5f6827a", "60a145f001d64e219ebe63c221127480", "ccdb518c63784e59a1ce0ba546c6629f", "<KEY>", "50c176ef19f346fa98f83f63e9e56196", "226244df33724db8a6e7599f0ef6fd8c", "<KEY>", "37939cf23cad45a0a85400f875e40227", "<KEY>", "20c1dbee57424e72a7b191c996257109", "<KEY>", "<KEY>", "4e8f6922f2574bef8078e93221335b61", "<KEY>"]} id="WARTTtPgBFoD" outputId="b27a2033-3155-4223-994b-33a278a3d5ec" Map = geemap.Map() Map # + id="TZNzkwVDBFoE" image = ee.Image('USGS/NED').select('elevation') vis_params={ "min": 0, "max": 4000, "palette": ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'] } Map.addLayer(image, vis_params, 'NED') # + [markdown] id="c8h0RX5ABFoF" # ## 3D Visualization # # ### Import libraries # + [markdown] id="UUiHjyTOBFoG" # First, import required packages. Note that here we import the `EarthEngineTerrainLayer` instead of the `EarthEngineLayer`. # + id="OClZhWBbBFoH" import ee import pydeck as pdk from pydeck_earthengine_layers import EarthEngineTerrainLayer # + [markdown] id="apmdsmviBFoI" # ### Authenticate with Earth Engine # # Using Earth Engine requires authentication. If you don't have a Google account approved for use with Earth Engine, you'll need to request access. For more information and to sign up, go to https://signup.earthengine.google.com/. # + id="DprEI9aNBFoJ" try: ee.Initialize() except Exception as e: ee.Authenticate() ee.Initialize() # + [markdown] id="P5W2NrFGBFoJ" # ### Terrain Example # # In contrast to the `EarthEngineLayer`, where you need to supply _one_ Earth Engine object to render, with the `EarthEngineTerrainLayer` you must supply **two** Earth Engine objects. The first is used to render the image in the same way as the `EarthEngineLayer`; the second supplies elevation values used to extrude terrain in 3D. Hence the former can be any `Image` object; the latter must be an `Image` object whose values represents terrain heights. # # It's important for the terrain source to have relatively high spatial resolution. In previous examples, we used [SRTM90][srtm90] as an elevation source, but that only has a resolution of 90 meters. When used as an elevation source, it looks very blocky/pixelated at high zoom levels. In this example we'll use [SRTM30][srtm30] (30-meter resolution) as the `Image` source and the [USGS's National Elevation Dataset][ned] (10-meter resolution, U.S. only) as the terrain source. SRTM30 is generally the best-resolution worldwide data source available. # # [srtm90]: https://developers.google.com/earth-engine/datasets/catalog/CGIAR_SRTM90_V4 # [srtm30]: https://developers.google.com/earth-engine/datasets/catalog/USGS_SRTMGL1_003 # [ned]: https://developers.google.com/earth-engine/datasets/catalog/USGS_NED # + id="cYh-LwxIBFoL" # image = ee.Image('USGS/SRTMGL1_003') image = ee.Image('USGS/NED').select('elevation') terrain = ee.Image('USGS/NED').select('elevation') # + [markdown] id="tZfyEPVwBFoL" # Here `vis_params` consists of parameters that will be passed to the Earth Engine [`visParams` argument][visparams]. Any parameters that you could pass directly to Earth Engine in the code editor, you can also pass here to the `EarthEngineLayer`. # # [visparams]: https://developers.google.com/earth-engine/image_visualization # + id="R1eByPZdBFoM" vis_params={ "min": 0, "max": 4000, "palette": ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'] } # + [markdown] id="bBl6UdlFBFoN" # Now we're ready to create the Pydeck layer. The `EarthEngineLayer` makes this simple. Just pass the Earth Engine object to the class. # + [markdown] id="d37fc2HkBFoN" # Including the `id` argument isn't necessary when you only have one pydeck layer, but it is necessary to distinguish multiple layers, so it's good to get into the habit of including an `id` parameter. # + id="6JSFOXwXBFoO" ee_layer = EarthEngineTerrainLayer( image, terrain, vis_params, id="EETerrainLayer" ) # + [markdown] id="5rZiq4FPBFoO" # Then just pass this layer to a `pydeck.Deck` instance, and call `.show()` to create a map: # + colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["4be3f74aa3cf4400a82a0863db361c28"]} id="0t-1xZBRBFoP" outputId="14f07f1b-52e2-4f6c-fa0d-30afee75dcbc" view_state = pdk.ViewState( latitude=36.15, longitude=-111.96, zoom=10.5, bearing=-66.16, pitch=60) r = pdk.Deck( layers=[ee_layer], initial_view_state=view_state ) r.show() # + id="DE-Iku94H91w"
examples/notebooks/37_pydeck_3d.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="_jQ1tEQCxwRx" # ##### Copyright 2020 The TensorFlow Authors. # + cellView="form" id="V_sgB_5dx1f1" #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # + [markdown] id="p62G8M_viUJp" # # Playing CartPole with the Actor-Critic Method # # + [markdown] id="-mJ2i6jvZ3sK" # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://www.tensorflow.org/tutorials/reinforcement_learning/actor_critic"> # <img src="https://www.tensorflow.org/images/tf_logo_32px.png" /> # View on TensorFlow.org</a> # </td> # <td> # <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/reinforcement_learning/actor_critic.ipynb"> # <img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> # Run in Google Colab</a> # </td> # <td> # <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/reinforcement_learning/actor_critic.ipynb"> # <img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> # View source on GitHub</a> # </td> # <td> # <a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/reinforcement_learning/actor_critic.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> # </td> # </table> # + [markdown] id="kFgN7h_wiUJq" # This tutorial demonstrates how to implement the [Actor-Critic](https://papers.nips.cc/paper/1786-actor-critic-algorithms.pdf) method using TensorFlow to train an agent on the [Open AI Gym](https://gym.openai.com/) CartPole-V0 environment. # The reader is assumed to have some familiarity with [policy gradient methods](https://papers.nips.cc/paper/1713-policy-gradient-methods-for-reinforcement-learning-with-function-approximation.pdf) of reinforcement learning. # # + [markdown] id="_kA10ZKRR0hi" # **Actor-Critic methods** # # Actor-Critic methods are [temporal difference (TD) learning](https://en.wikipedia.org/wiki/Temporal_difference_learning) methods that represent the policy function independent of the value function. # # A policy function (or policy) returns a probability distribution over actions that the agent can take based on the given state. # A value function determines the expected return for an agent starting at a given state and acting according to a particular policy forever after. # # In the Actor-Critic method, the policy is referred to as the *actor* that proposes a set of possible actions given a state, and the estimated value function is referred to as the *critic*, which evaluates actions taken by the *actor* based on the given policy. # # In this tutorial, both the *Actor* and *Critic* will be represented using one neural network with two outputs. # # + [markdown] id="rBfiafKSRs2k" # **CartPole-v0** # # In the [CartPole-v0 environment](https://gym.openai.com/envs/CartPole-v0), a pole is attached to a cart moving along a frictionless track. # The pole starts upright and the goal of the agent is to prevent it from falling over by applying a force of -1 or +1 to the cart. # A reward of +1 is given for every time step the pole remains upright. # An episode ends when (1) the pole is more than 15 degrees from vertical or (2) the cart moves more than 2.4 units from the center. # # <center> # <figure> # <image src="images/cartpole-v0.gif"> # <figcaption> # Trained actor-critic model in Cartpole-v0 environment # </figcaption> # </figure> # </center> # # + [markdown] id="XSNVK0AeRoJd" # The problem is considered "solved" when the average total reward for the episode reaches 195 over 100 consecutive trials. # + [markdown] id="glLwIctHiUJq" # ## Setup # # Import necessary packages and configure global settings. # # + id="13l6BbxKhCKp" # !pip install gym # !pip install pyglet # + id="WBeQhPi2S4m5" language="bash" # # Install additional packages for visualization # sudo apt-get install -y xvfb python-opengl > /dev/null 2>&1 # pip install pyvirtualdisplay > /dev/null 2>&1 # pip install git+https://github.com/tensorflow/docs > /dev/null 2>&1 # + id="tT4N3qYviUJr" import collections import gym import numpy as np import statistics import tensorflow as tf import tqdm from matplotlib import pyplot as plt from tensorflow.keras import layers from typing import Any, List, Sequence, Tuple # Create the environment env = gym.make("CartPole-v0") # Set seed for experiment reproducibility seed = 42 env.seed(seed) tf.random.set_seed(seed) np.random.seed(seed) # Small epsilon value for stabilizing division operations eps = np.finfo(np.float32).eps.item() # + [markdown] id="AOUCe2D0iUJu" # ## Model # # The *Actor* and *Critic* will be modeled using one neural network that generates the action probabilities and critic value respectively. This tutorial uses model subclassing to define the model. # # During the forward pass, the model will take in the state as the input and will output both action probabilities and critic value $V$, which models the state-dependent [value function](https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#value-functions). The goal is to train a model that chooses actions based on a policy $\pi$ that maximizes expected [return](https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#reward-and-return). # # For Cartpole-v0, there are four values representing the state: cart position, cart-velocity, pole angle and pole velocity respectively. The agent can take two actions to push the cart left (0) and right (1) respectively. # # Refer to [OpenAI Gym's CartPole-v0 wiki page](http://www.derongliu.org/adp/adp-cdrom/Barto1983.pdf) for more information. # # + id="aXKbbMC-kmuv" class ActorCritic(tf.keras.Model): """Combined actor-critic network.""" def __init__( self, num_actions: int, num_hidden_units: int): """Initialize.""" super().__init__() self.common = layers.Dense(num_hidden_units, activation="relu") self.actor = layers.Dense(num_actions) self.critic = layers.Dense(1) def call(self, inputs: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]: x = self.common(inputs) return self.actor(x), self.critic(x) # + id="nWyxJgjLn68c" num_actions = env.action_space.n # 2 num_hidden_units = 128 model = ActorCritic(num_actions, num_hidden_units) # + [markdown] id="hk92njFziUJw" # ## Training # # To train the agent, you will follow these steps: # # 1. Run the agent on the environment to collect training data per episode. # 2. Compute expected return at each time step. # 3. Compute the loss for the combined actor-critic model. # 4. Compute gradients and update network parameters. # 5. Repeat 1-4 until either success criterion or max episodes has been reached. # # + [markdown] id="R2nde2XDs8Gh" # ### 1. Collecting training data # # As in supervised learning, in order to train the actor-critic model, you need # to have training data. However, in order to collect such data, the model would # need to be "run" in the environment. # # Training data is collected for each episode. Then at each time step, the model's forward pass will be run on the environment's state in order to generate action probabilities and the critic value based on the current policy parameterized by the model's weights. # # The next action will be sampled from the action probabilities generated by the model, which would then be applied to the environment, causing the next state and reward to be generated. # # This process is implemented in the `run_episode` function, which uses TensorFlow operations so that it can later be compiled into a TensorFlow graph for faster training. Note that `tf.TensorArray`s were used to support Tensor iteration on variable length arrays. # + id="5URrbGlDSAGx" # Wrap OpenAI Gym's `env.step` call as an operation in a TensorFlow function. # This would allow it to be included in a callable TensorFlow graph. def env_step(action: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Returns state, reward and done flag given an action.""" state, reward, done, _ = env.step(action) return (state.astype(np.float32), np.array(reward, np.int32), np.array(done, np.int32)) def tf_env_step(action: tf.Tensor) -> List[tf.Tensor]: return tf.numpy_function(env_step, [action], [tf.float32, tf.int32, tf.int32]) # + id="a4qVRV063Cl9" def run_episode( initial_state: tf.Tensor, model: tf.keras.Model, max_steps: int) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor]: """Runs a single episode to collect training data.""" action_probs = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True) values = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True) rewards = tf.TensorArray(dtype=tf.int32, size=0, dynamic_size=True) initial_state_shape = initial_state.shape state = initial_state for t in tf.range(max_steps): # Convert state into a batched tensor (batch size = 1) state = tf.expand_dims(state, 0) # Run the model and to get action probabilities and critic value action_logits_t, value = model(state) # Sample next action from the action probability distribution action = tf.random.categorical(action_logits_t, 1)[0, 0] action_probs_t = tf.nn.softmax(action_logits_t) # Store critic values values = values.write(t, tf.squeeze(value)) # Store log probability of the action chosen action_probs = action_probs.write(t, action_probs_t[0, action]) # Apply action to the environment to get next state and reward state, reward, done = tf_env_step(action) state.set_shape(initial_state_shape) # Store reward rewards = rewards.write(t, reward) if tf.cast(done, tf.bool): break action_probs = action_probs.stack() values = values.stack() rewards = rewards.stack() return action_probs, values, rewards # + [markdown] id="lBnIHdz22dIx" # ### 2. Computing expected returns # # The sequence of rewards for each timestep $t$, $\{r_{t}\}^{T}_{t=1}$ collected during one episode is converted into a sequence of expected returns $\{G_{t}\}^{T}_{t=1}$ in which the sum of rewards is taken from the current timestep $t$ to $T$ and each reward is multiplied with an exponentially decaying discount factor $\gamma$: # # $$G_{t} = \sum^{T}_{t'=t} \gamma^{t'-t}r_{t'}$$ # # Since $\gamma\in(0,1)$, rewards further out from the current timestep are given less weight. # # Intuitively, expected return simply implies that rewards now are better than rewards later. In a mathematical sense, it is to ensure that the sum of the rewards converges. # # To stabilize training, the resulting sequence of returns is also standardized (i.e. to have zero mean and unit standard deviation). # # + id="jpEwFyl315dl" def get_expected_return( rewards: tf.Tensor, gamma: float, standardize: bool = True) -> tf.Tensor: """Compute expected returns per timestep.""" n = tf.shape(rewards)[0] returns = tf.TensorArray(dtype=tf.float32, size=n) # Start from the end of `rewards` and accumulate reward sums # into the `returns` array rewards = tf.cast(rewards[::-1], dtype=tf.float32) discounted_sum = tf.constant(0.0) discounted_sum_shape = discounted_sum.shape for i in tf.range(n): reward = rewards[i] discounted_sum = reward + gamma * discounted_sum discounted_sum.set_shape(discounted_sum_shape) returns = returns.write(i, discounted_sum) returns = returns.stack()[::-1] if standardize: returns = ((returns - tf.math.reduce_mean(returns)) / (tf.math.reduce_std(returns) + eps)) return returns # + [markdown] id="1hrPLrgGxlvb" # ### 3. The actor-critic loss # # Since a hybrid actor-critic model is used, the chosen loss function is a combination of actor and critic losses for training, as shown below: # # $$L = L_{actor} + L_{critic}$$ # # #### Actor loss # # The actor loss is based on [policy gradients with the critic as a state dependent baseline](https://www.youtube.com/watch?v=EKqxumCuAAY&t=62m23s) and computed with single-sample (per-episode) estimates. # # $$L_{actor} = -\sum^{T}_{t=1} log\pi_{\theta}(a_{t} | s_{t})[G(s_{t}, a_{t}) - V^{\pi}_{\theta}(s_{t})]$$ # # where: # - $T$: the number of timesteps per episode, which can vary per episode # - $s_{t}$: the state at timestep $t$ # - $a_{t}$: chosen action at timestep $t$ given state $s$ # - $\pi_{\theta}$: is the policy (actor) parameterized by $\theta$ # - $V^{\pi}_{\theta}$: is the value function (critic) also parameterized by $\theta$ # - $G = G_{t}$: the expected return for a given state, action pair at timestep $t$ # # A negative term is added to the sum since the idea is to maximize the probabilities of actions yielding higher rewards by minimizing the combined loss. # # <br> # # ##### Advantage # # The $G - V$ term in our $L_{actor}$ formulation is called the [advantage](https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#advantage-functions), which indicates how much better an action is given a particular state over a random action selected according to the policy $\pi$ for that state. # # While it's possible to exclude a baseline, this may result in high variance during training. And the nice thing about choosing the critic $V$ as a baseline is that it trained to be as close as possible to $G$, leading to a lower variance. # # In addition, without the critic, the algorithm would try to increase probabilities for actions taken on a particular state based on expected return, which may not make much of a difference if the relative probabilities between actions remain the same. # # For instance, suppose that two actions for a given state would yield the same expected return. Without the critic, the algorithm would try to raise the probability of these actions based on the objective $J$. With the critic, it may turn out that there's no advantage ($G - V = 0$) and thus no benefit gained in increasing the actions' probabilities and the algorithm would set the gradients to zero. # # <br> # # #### Critic loss # # Training $V$ to be as close possible to $G$ can be set up as a regression problem with the following loss function: # # $$L_{critic} = L_{\delta}(G, V^{\pi}_{\theta})$$ # # where $L_{\delta}$ is the [Huber loss](https://en.wikipedia.org/wiki/Huber_loss), which is less sensitive to outliers in data than squared-error loss. # # + id="9EXwbEez6n9m" huber_loss = tf.keras.losses.Huber(reduction=tf.keras.losses.Reduction.SUM) def compute_loss( action_probs: tf.Tensor, values: tf.Tensor, returns: tf.Tensor) -> tf.Tensor: """Computes the combined actor-critic loss.""" advantage = returns - values action_log_probs = tf.math.log(action_probs) actor_loss = -tf.math.reduce_sum(action_log_probs * advantage) critic_loss = huber_loss(values, returns) return actor_loss + critic_loss # + [markdown] id="HSYkQOmRfV75" # ### 4. Defining the training step to update parameters # # All of the steps above are combined into a training step that is run every episode. All steps leading up to the loss function are executed with the `tf.GradientTape` context to enable automatic differentiation. # # This tutorial uses the Adam optimizer to apply the gradients to the model parameters. # # The sum of the undiscounted rewards, `episode_reward`, is also computed in this step. This value will be used later on to evaluate if the success criterion is met. # # The `tf.function` context is applied to the `train_step` function so that it can be compiled into a callable TensorFlow graph, which can lead to 10x speedup in training. # # + id="QoccrkF3IFCg" optimizer = tf.keras.optimizers.Adam(learning_rate=0.01) @tf.function def train_step( initial_state: tf.Tensor, model: tf.keras.Model, optimizer: tf.keras.optimizers.Optimizer, gamma: float, max_steps_per_episode: int) -> tf.Tensor: """Runs a model training step.""" with tf.GradientTape() as tape: # Run the model for one episode to collect training data action_probs, values, rewards = run_episode( initial_state, model, max_steps_per_episode) # Calculate expected returns returns = get_expected_return(rewards, gamma) # Convert training data to appropriate TF tensor shapes action_probs, values, returns = [ tf.expand_dims(x, 1) for x in [action_probs, values, returns]] # Calculating loss values to update our network loss = compute_loss(action_probs, values, returns) # Compute the gradients from the loss grads = tape.gradient(loss, model.trainable_variables) # Apply the gradients to the model's parameters optimizer.apply_gradients(zip(grads, model.trainable_variables)) episode_reward = tf.math.reduce_sum(rewards) return episode_reward # + [markdown] id="HFvZiDoAflGK" # ### 5. Run the training loop # # Training is executed by running the training step until either the success criterion or maximum number of episodes is reached. # # A running record of episode rewards is kept in a queue. Once 100 trials are reached, the oldest reward is removed at the left (tail) end of the queue and the newest one is added at the head (right). A running sum of the rewards is also maintained for computational efficiency. # # Depending on your runtime, training can finish in less than a minute. # + id="kbmBxnzLiUJx" # %%time min_episodes_criterion = 100 max_episodes = 10000 max_steps_per_episode = 1000 # Cartpole-v0 is considered solved if average reward is >= 195 over 100 # consecutive trials reward_threshold = 195 running_reward = 0 # Discount factor for future rewards gamma = 0.99 # Keep last episodes reward episodes_reward: collections.deque = collections.deque(maxlen=min_episodes_criterion) with tqdm.trange(max_episodes) as t: for i in t: initial_state = tf.constant(env.reset(), dtype=tf.float32) episode_reward = int(train_step( initial_state, model, optimizer, gamma, max_steps_per_episode)) episodes_reward.append(episode_reward) running_reward = statistics.mean(episodes_reward) t.set_description(f'Episode {i}') t.set_postfix( episode_reward=episode_reward, running_reward=running_reward) # Show average episode reward every 10 episodes if i % 10 == 0: pass # print(f'Episode {i}: average reward: {avg_reward}') if running_reward > reward_threshold and i >= min_episodes_criterion: break print(f'\nSolved at episode {i}: average reward: {running_reward:.2f}!') # + [markdown] id="ru8BEwS1EmAv" # ## Visualization # # After training, it would be good to visualize how the model performs in the environment. You can run the cells below to generate a GIF animation of one episode run of the model. Note that additional packages need to be installed for OpenAI Gym to render the environment's images correctly in Colab. # + id="qbIMMkfmRHyC" # Render an episode and save as a GIF file from IPython import display as ipythondisplay from PIL import Image from pyvirtualdisplay import Display display = Display(visible=0, size=(400, 300)) display.start() def render_episode(env: gym.Env, model: tf.keras.Model, max_steps: int): screen = env.render(mode='rgb_array') im = Image.fromarray(screen) images = [im] state = tf.constant(env.reset(), dtype=tf.float32) for i in range(1, max_steps + 1): state = tf.expand_dims(state, 0) action_probs, _ = model(state) action = np.argmax(np.squeeze(action_probs)) state, _, done, _ = env.step(action) state = tf.constant(state, dtype=tf.float32) # Render screen every 10 steps if i % 10 == 0: screen = env.render(mode='rgb_array') images.append(Image.fromarray(screen)) if done: break return images # Save GIF image images = render_episode(env, model, max_steps_per_episode) image_file = 'cartpole-v0.gif' # loop=0: loop forever, duration=1: play each frame for 1ms images[0].save( image_file, save_all=True, append_images=images[1:], loop=0, duration=1) # + id="TLd720SejKmf" import tensorflow_docs.vis.embed as embed embed.embed_file(image_file) # + [markdown] id="lnq9Hzo1Po6X" # ## Next steps # # This tutorial demonstrated how to implement the actor-critic method using Tensorflow. # # As a next step, you could try training a model on a different environment in OpenAI Gym. # # For additional information regarding actor-critic methods and the Cartpole-v0 problem, you may refer to the following resources: # # - [Actor Critic Method](https://hal.inria.fr/hal-00840470/document) # - [Actor Critic Lecture (CAL)](https://www.youtube.com/watch?v=EKqxumCuAAY&list=PLkFD6_40KJIwhWJpGazJ9VSj9CFMkb79A&index=7&t=0s) # - [Cartpole learning control problem \[Barto, et al. 1983\]](http://www.derongliu.org/adp/adp-cdrom/Barto1983.pdf) # # For more reinforcement learning examples in TensorFlow, you can check the following resources: # - [Reinforcement learning code examples (keras.io)](https://keras.io/examples/rl/) # - [TF-Agents reinforcement learning library](https://www.tensorflow.org/agents) #
site/en-snapshot/tutorials/reinforcement_learning/actor_critic.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 # --- # # Entities Recognition # <div class="alert alert-info"> # # This tutorial is available as an IPython notebook at [Malaya/example/entities](https://github.com/huseinzol05/Malaya/tree/master/example/entities). # # </div> # <div class="alert alert-warning"> # # This module only trained on standard language structure, so it is not save to use it for local language structure. # # </div> # %%time import malaya # ### Models accuracy # # We use `sklearn.metrics.classification_report` for accuracy reporting, check at https://malaya.readthedocs.io/en/latest/models-accuracy.html#entities-recognition and https://malaya.readthedocs.io/en/latest/models-accuracy.html#entities-recognition-ontonotes5 # ### Describe supported entities import pandas as pd pd.set_option('display.max_colwidth', -1) malaya.entity.describe() # ### Describe supported Ontonotes 5 entities malaya.entity.describe_ontonotes5() # ### List available Transformer NER models malaya.entity.available_transformer() # ### List available Transformer NER Ontonotes 5 models malaya.entity.available_transformer_ontonotes5() string = 'KUALA LUMPUR: Sempena sambutan Aidilfitri minggu depan, Perdana Menteri Tun Dr <NAME> dan Menteri Pengangkutan <NAME> menitipkan pesanan khas kepada orang ramai yang mahu pulang ke kampung halaman masing-masing. Dalam video pendek terbitan Jabatan Keselamatan Jalan Raya (JKJR) itu, Dr Mahathir menasihati mereka supaya berhenti berehat dan tidur sebentar sekiranya mengantuk ketika memandu.' string1 = 'memperkenalkan Husein, dia sangat comel, berumur 25 tahun, bangsa melayu, agama islam, tinggal di cyberjaya malaysia, bercakap bahasa melayu, semua membaca buku undang-undang kewangan, dengar laju Siti Nurhaliza - Seluruh Cinta sambil makan ayam goreng KFC' # ### Load Transformer model # # ```python # def transformer(model: str = 'xlnet', quantized: bool = False, **kwargs): # """ # Load Transformer Entity Tagging model trained on Malaya Entity, transfer learning Transformer + CRF. # # Parameters # ---------- # model : str, optional (default='bert') # Model architecture supported. Allowed values: # # * ``'bert'`` - Google BERT BASE parameters. # * ``'tiny-bert'`` - Google BERT TINY parameters. # * ``'albert'`` - Google ALBERT BASE parameters. # * ``'tiny-albert'`` - Google ALBERT TINY parameters. # * ``'xlnet'`` - Google XLNET BASE parameters. # * ``'alxlnet'`` - Malaya ALXLNET BASE parameters. # * ``'fastformer'`` - FastFormer BASE parameters. # * ``'tiny-fastformer'`` - FastFormer TINY parameters. # # quantized : bool, optional (default=False) # if True, will load 8-bit quantized model. # Quantized model not necessary faster, totally depends on the machine. # # Returns # ------- # result: model # List of model classes: # # * if `bert` in model, will return `malaya.model.bert.TaggingBERT`. # * if `xlnet` in model, will return `malaya.model.xlnet.TaggingXLNET`. # * if `fastformer` in model, will return `malaya.model.fastformer.TaggingFastFormer`. # """ # ``` model = malaya.entity.transformer(model = 'alxlnet') # #### Load Quantized model # # To load 8-bit quantized model, simply pass `quantized = True`, default is `False`. # # We can expect slightly accuracy drop from quantized model, and not necessary faster than normal 32-bit float model, totally depends on machine. quantized_model = malaya.entity.transformer(model = 'alxlnet', quantized = True) # #### Predict # # ```python # def predict(self, string: str): # """ # Tag a string. # # Parameters # ---------- # string : str # # Returns # ------- # result: Tuple[str, str] # """ # ``` model.predict(string) model.predict(string1) quantized_model.predict(string) quantized_model.predict(string1) # #### Group similar tags # # ```python # def analyze(self, string: str): # """ # Analyze a string. # # Parameters # ---------- # string : str # # Returns # ------- # result: {'words': List[str], 'tags': [{'text': 'text', 'type': 'location', 'score': 1.0, 'beginOffset': 0, 'endOffset': 1}]} # """ # ``` model.analyze(string) model.analyze(string1) # #### Vectorize # # Let say you want to visualize word level in lower dimension, you can use `model.vectorize`, # # ```python # def vectorize(self, string: str): # """ # vectorize a string. # # Parameters # ---------- # string: List[str] # # Returns # ------- # result: np.array # """ # ``` strings = [string, 'Husein baca buku Perlembagaan yang berharga 3k ringgit dekat kfc sungai petani minggu lepas, 2 ptg 2 oktober 2019 , suhu 32 celcius, sambil makan ayam goreng dan milo o ais', 'contact Husein at <EMAIL>', 'tolong tempahkan meja makan makan nasi dagang dan jus apple, milo tarik esok dekat Restoran Sebulek'] r = [quantized_model.vectorize(string) for string in strings] x, y = [], [] for row in r: x.extend([i[0] for i in row]) y.extend([i[1] for i in row]) # + from sklearn.manifold import TSNE import matplotlib.pyplot as plt tsne = TSNE().fit_transform(y) tsne.shape # - plt.figure(figsize = (7, 7)) plt.scatter(tsne[:, 0], tsne[:, 1]) labels = x for label, x, y in zip( labels, tsne[:, 0], tsne[:, 1] ): label = ( '%s, %.3f' % (label[0], label[1]) if isinstance(label, list) else label ) plt.annotate( label, xy = (x, y), xytext = (0, 0), textcoords = 'offset points', ) # Pretty good, the model able to know cluster similar entities. # ### Load Transformer Ontonotes 5 model # # ```python # def transformer_ontonotes5( # model: str = 'xlnet', quantized: bool = False, **kwargs # ): # """ # Load Transformer Entity Tagging model trained on Ontonotes 5 Bahasa, transfer learning Transformer + CRF. # # Parameters # ---------- # model : str, optional (default='bert') # Model architecture supported. Allowed values: # # * ``'bert'`` - Google BERT BASE parameters. # * ``'tiny-bert'`` - Google BERT TINY parameters. # * ``'albert'`` - Google ALBERT BASE parameters. # * ``'tiny-albert'`` - Google ALBERT TINY parameters. # * ``'xlnet'`` - Google XLNET BASE parameters. # * ``'alxlnet'`` - Malaya ALXLNET BASE parameters. # * ``'fastformer'`` - FastFormer BASE parameters. # * ``'tiny-fastformer'`` - FastFormer TINY parameters. # # quantized : bool, optional (default=False) # if True, will load 8-bit quantized model. # Quantized model not necessary faster, totally depends on the machine. # # Returns # ------- # result: model # List of model classes: # # * if `bert` in model, will return `malaya.model.bert.TaggingBERT`. # * if `xlnet` in model, will return `malaya.model.xlnet.TaggingXLNET`. # * if `fastformer` in model, will return `malaya.model.fastformer.TaggingFastFormer`. # """ # ``` albert = malaya.entity.transformer_ontonotes5(model = 'albert') alxlnet = malaya.entity.transformer_ontonotes5(model = 'alxlnet') # #### Load Quantized model # # To load 8-bit quantized model, simply pass `quantized = True`, default is `False`. # # We can expect slightly accuracy drop from quantized model, and not necessary faster than normal 32-bit float model, totally depends on machine. quantized_albert = malaya.entity.transformer_ontonotes5(model = 'albert', quantized = True) quantized_alxlnet = malaya.entity.transformer_ontonotes5(model = 'alxlnet', quantized = True) # #### Predict # # ```python # def predict(self, string: str): # """ # Tag a string. # # Parameters # ---------- # string : str # # Returns # ------- # result: Tuple[str, str] # """ # ``` albert.predict(string) alxlnet.predict(string) albert.predict(string1) alxlnet.predict(string1) quantized_albert.predict(string) quantized_alxlnet.predict(string1) # #### Group similar tags # # ```python # def analyze(self, string: str): # """ # Analyze a string. # # Parameters # ---------- # string : str # # Returns # ------- # result: {'words': List[str], 'tags': [{'text': 'text', 'type': 'location', 'score': 1.0, 'beginOffset': 0, 'endOffset': 1}]} # """ # ``` alxlnet.analyze(string1) # #### Vectorize # # Let say you want to visualize word level in lower dimension, you can use `model.vectorize`, # # ```python # def vectorize(self, string: str): # """ # vectorize a string. # # Parameters # ---------- # string: List[str] # # Returns # ------- # result: np.array # """ # ``` strings = [string, string1] r = [quantized_model.vectorize(string) for string in strings] x, y = [], [] for row in r: x.extend([i[0] for i in row]) y.extend([i[1] for i in row]) tsne = TSNE().fit_transform(y) tsne.shape plt.figure(figsize = (7, 7)) plt.scatter(tsne[:, 0], tsne[:, 1]) labels = x for label, x, y in zip( labels, tsne[:, 0], tsne[:, 1] ): label = ( '%s, %.3f' % (label[0], label[1]) if isinstance(label, list) else label ) plt.annotate( label, xy = (x, y), xytext = (0, 0), textcoords = 'offset points', ) # Pretty good, the model able to know cluster similar entities. # ### Load general Malaya entity model # # This model able to classify, # # 1. date # 2. money # 3. temperature # 4. distance # 5. volume # 6. duration # 7. phone # 8. email # 9. url # 10. time # 11. datetime # 12. local and generic foods, can check available rules in malaya.texts._food # 13. local and generic drinks, can check available rules in malaya.texts._food # # We can insert BERT or any deep learning model by passing `malaya.entity.general_entity(model = model)`, as long the model has `predict` method and return `[(string, label), (string, label)]`. This is an optional. entity = malaya.entity.general_entity(model = model) entity.predict('Husein baca buku Perlembagaan yang berharga 3k ringgit dekat kfc sungai petani minggu lepas, 2 ptg 2 oktober 2019 , suhu 32 celcius, sambil makan ayam goreng dan milo o ais') entity.predict('contact Husein at <EMAIL>') entity.predict('tolong tempahkan meja makan makan nasi dagang dan jus apple, milo tarik esok dekat Restoran Sebulek') # ### Voting stack model malaya.stack.voting_stack([albert, alxlnet, alxlnet], string1)
docs/load-entities.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] papermill={"duration": 0.046731, "end_time": "2020-10-02T02:25:05.928259", "exception": false, "start_time": "2020-10-02T02:25:05.881528", "status": "completed"} tags=[] # Thanks for: # # https://www.kaggle.com/ttahara/osic-baseline-lgbm-with-custom-metric # # https://www.kaggle.com/carlossouza/bayesian-experiments # # + [markdown] papermill={"duration": 0.043987, "end_time": "2020-10-02T02:25:06.016397", "exception": false, "start_time": "2020-10-02T02:25:05.972410", "status": "completed"} tags=[] # v5 Crate features # # v6 Add middle layer feature extraction # # v7 Crate features with middle layer feature extraction # # v8 Crate features with middle layer feature extraction # + [markdown] papermill={"duration": 0.042543, "end_time": "2020-10-02T02:25:06.101790", "exception": false, "start_time": "2020-10-02T02:25:06.059247", "status": "completed"} tags=[] # ## Library # + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" papermill={"duration": 7.897106, "end_time": "2020-10-02T02:25:14.041923", "exception": false, "start_time": "2020-10-02T02:25:06.144817", "status": "completed"} tags=[] import albumentations import copy from collections import defaultdict import os import operator import typing as tp from logging import getLogger, INFO, StreamHandler, FileHandler, Formatter from functools import partial import numpy as np import pandas as pd import pymc3 as pm import random import math from tqdm.notebook import tqdm import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import StratifiedKFold, GroupKFold, KFold from sklearn.metrics import mean_squared_error from sklearn.preprocessing import StandardScaler,LabelEncoder import category_encoders as ce from PIL import Image import cv2 import pydicom import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim import lr_scheduler from torch.utils.data import DataLoader, Dataset from torch.utils.data.sampler import RandomSampler, SequentialSampler import lightgbm as lgb from sklearn.linear_model import Ridge import warnings warnings.filterwarnings("ignore") print("PyTorch Version: ",torch.__version__) print('Running on PyMC3 v{}'.format(pm.__version__)) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) # + [markdown] papermill={"duration": 0.043541, "end_time": "2020-10-02T02:25:14.130126", "exception": false, "start_time": "2020-10-02T02:25:14.086585", "status": "completed"} tags=[] # ## Utils # + _kg_hide-input=true papermill={"duration": 0.056652, "end_time": "2020-10-02T02:25:14.230721", "exception": false, "start_time": "2020-10-02T02:25:14.174069", "status": "completed"} tags=[] def get_logger(filename='log'): logger = getLogger(__name__) logger.setLevel(INFO) handler1 = StreamHandler() handler1.setFormatter(Formatter("%(message)s")) handler2 = FileHandler(filename=f"{filename}.log") handler2.setFormatter(Formatter("%(message)s")) logger.addHandler(handler1) logger.addHandler(handler2) return logger logger = get_logger() def seed_everything(seed=777): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True # + [markdown] papermill={"duration": 0.044563, "end_time": "2020-10-02T02:25:14.320114", "exception": false, "start_time": "2020-10-02T02:25:14.275551", "status": "completed"} tags=[] # ## Config # + papermill={"duration": 0.058262, "end_time": "2020-10-02T02:25:14.424297", "exception": false, "start_time": "2020-10-02T02:25:14.366035", "status": "completed"} tags=[] OUTPUT_DICT = './' data_dir = "/kaggle/input/osic-pulmonary-fibrosis-progression/" train_image_folder = os.path.join(data_dir+'train') test_image_folder = os.path.join(data_dir+'test') train_ct_dic = os.path.join('../input/oscitrainedmodels/osci_train_ct_image_dict.256.pkl') ID = 'Patient_Week' TARGET = 'FVC' SEED = 42 seed_everything(seed=SEED) N_FOLD = 4 n_epochs = 9999 train_bs = 32 valid_bs = 32 test_bs = 16 SIZE = 256 # + [markdown] papermill={"duration": 0.044087, "end_time": "2020-10-02T02:25:14.512724", "exception": false, "start_time": "2020-10-02T02:25:14.468637", "status": "completed"} tags=[] # # Data Loading # + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" papermill={"duration": 0.110338, "end_time": "2020-10-02T02:25:14.667358", "exception": false, "start_time": "2020-10-02T02:25:14.557020", "status": "completed"} tags=[] train = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/train.csv') tr = train.copy() train[ID] = train['Patient'].astype(str) + '_' + train['Weeks'].astype(str) print(train.shape) train.head() # + papermill={"duration": 17.649821, "end_time": "2020-10-02T02:25:32.362320", "exception": false, "start_time": "2020-10-02T02:25:14.712499", "status": "completed"} tags=[] # construct train input output = pd.DataFrame() gb = train.groupby('Patient') tk0 = tqdm(gb, total=len(gb)) for _, usr_df in tk0: usr_output = pd.DataFrame() for week, tmp in usr_df.groupby('Weeks'): rename_cols = {'Weeks': 'base_Week', 'FVC': 'base_FVC', 'Percent': 'base_Percent', 'Age': 'base_Age'} tmp = tmp.drop(columns='Patient_Week').rename(columns=rename_cols) drop_cols = ['Age', 'Sex', 'SmokingStatus', 'Percent'] _usr_output = usr_df.drop(columns=drop_cols).rename(columns={'Weeks': 'predict_Week'}).merge(tmp, on='Patient') _usr_output['Week_passed'] = _usr_output['predict_Week'] - _usr_output['base_Week'] usr_output = pd.concat([usr_output, _usr_output]) output = pd.concat([output, usr_output]) train = output[output['Week_passed']!=0].reset_index(drop=True) print(train.shape) train.head() # + papermill={"duration": 0.059614, "end_time": "2020-10-02T02:25:32.468750", "exception": false, "start_time": "2020-10-02T02:25:32.409136", "status": "completed"} tags=[] # construct test input test = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/test.csv') ts = test.copy() # + [markdown] papermill={"duration": 0.04667, "end_time": "2020-10-02T02:25:32.562065", "exception": false, "start_time": "2020-10-02T02:25:32.515395", "status": "completed"} tags=[] # # Create test dataset with Bayesian approach # https://colab.research.google.com/drive/13WTKUlpYEtN0RNhzax_j8gbf84FuU1CF?authuser=1#scrollTo=jUeafaYrv9Em # + papermill={"duration": 0.061721, "end_time": "2020-10-02T02:25:32.670210", "exception": false, "start_time": "2020-10-02T02:25:32.608489", "status": "completed"} tags=[] # PercentをFVCに合わせて補正 # X * Percent / 100 = FVC # X = FVC * 100 / Percent dic = {} for i in range(len(test)): X = int(test.FVC[i]*100/test.Percent[i]) dic[test.Patient[i]] = X dic # + papermill={"duration": 0.06549, "end_time": "2020-10-02T02:25:32.782831", "exception": false, "start_time": "2020-10-02T02:25:32.717341", "status": "completed"} tags=[] tr = pd.concat([tr, ts], axis=0, ignore_index=True).drop_duplicates() le_id = LabelEncoder() tr['PatientID'] = le_id.fit_transform(tr['Patient']) # + papermill={"duration": 286.90396, "end_time": "2020-10-02T02:30:19.733993", "exception": false, "start_time": "2020-10-02T02:25:32.830033", "status": "completed"} tags=[] n_patients = tr['Patient'].nunique() FVC_obs = tr['FVC'].values Weeks = tr['Weeks'].values PatientID = tr['PatientID'].values with pm.Model() as model_a: # create shared variables that can be changed later on FVC_obs_shared = pm.Data("FVC_obs_shared", FVC_obs) Weeks_shared = pm.Data('Weeks_shared', Weeks) PatientID_shared = pm.Data('PatientID_shared', PatientID) mu_a = pm.Normal('mu_a', mu=1700., sigma=400) sigma_a = pm.HalfNormal('sigma_a', 1000.) mu_b = pm.Normal('mu_b', mu=-4., sigma=1) sigma_b = pm.HalfNormal('sigma_b', 5.) a = pm.Normal('a', mu=mu_a, sigma=sigma_a, shape=n_patients) b = pm.Normal('b', mu=mu_b, sigma=sigma_b, shape=n_patients) # Model error sigma = pm.HalfNormal('sigma', 150.) FVC_est = a[PatientID_shared] + b[PatientID_shared] * Weeks_shared # Data likelihood FVC_like = pm.Normal('FVC_like', mu=FVC_est, sigma=sigma, observed=FVC_obs_shared) # Fitting the model trace_a = pm.sample(2000, tune=2000, target_accept=.9, init="adapt_diag") # + papermill={"duration": 47.404813, "end_time": "2020-10-02T02:31:07.188251", "exception": false, "start_time": "2020-10-02T02:30:19.783438", "status": "completed"} tags=[] pred_template = [] for p in ts['Patient'].unique(): df = pd.DataFrame(columns=['PatientID', 'Weeks']) df['Weeks'] = np.arange(-12, 134) df['Patient'] = p pred_template.append(df) pred_template = pd.concat(pred_template, ignore_index=True) pred_template['PatientID'] = le_id.transform(pred_template['Patient']) with model_a: pm.set_data({ "PatientID_shared": pred_template['PatientID'].values.astype(int), "Weeks_shared": pred_template['Weeks'].values.astype(int), "FVC_obs_shared": np.zeros(len(pred_template)).astype(int), }) post_pred = pm.sample_posterior_predictive(trace_a) # + papermill={"duration": 0.483758, "end_time": "2020-10-02T02:31:07.720947", "exception": false, "start_time": "2020-10-02T02:31:07.237189", "status": "completed"} tags=[] df = pd.DataFrame(columns=['Patient', 'Weeks', 'Patient_Week', 'FVC', 'Confidence']) df['Patient'] = pred_template['Patient'] df['Weeks'] = pred_template['Weeks'] df['Patient_Week'] = df['Patient'] + '_' + df['Weeks'].astype(str) df['FVC'] = post_pred['FVC_like'].T.mean(axis=1) df['Confidence'] = post_pred['FVC_like'].T.std(axis=1) final = df[['Patient_Week', 'FVC', 'Confidence']] final.to_csv('submission.csv', index=False) print(final.shape) final # + papermill={"duration": 0.098205, "end_time": "2020-10-02T02:31:07.868061", "exception": false, "start_time": "2020-10-02T02:31:07.769856", "status": "completed"} tags=[] test = test.rename(columns={'Weeks': 'base_Week', 'FVC': 'base_FVC', 'Percent': 'base_Percent', 'Age': 'base_Age'}) submission = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/sample_submission.csv') submission['Patient'] = submission['Patient_Week'].apply(lambda x: x.split('_')[0]) submission['predict_Week'] = submission['Patient_Week'].apply(lambda x: x.split('_')[1]).astype(int) test = submission.drop(columns=['FVC', 'Confidence']).merge(test, on='Patient') test['Week_passed'] = test['predict_Week'] - test['base_Week'] print(test.shape) test # + papermill={"duration": 0.089687, "end_time": "2020-10-02T02:31:08.007951", "exception": false, "start_time": "2020-10-02T02:31:07.918264", "status": "completed"} tags=[] test = test.drop(columns='base_FVC').merge(final[["Patient_Week", "FVC"]], on='Patient_Week') test # + papermill={"duration": 0.168216, "end_time": "2020-10-02T02:31:08.228833", "exception": false, "start_time": "2020-10-02T02:31:08.060617", "status": "completed"} tags=[] # Percent = FVC * 100 /X for i in range(len(test)): Percent = test.FVC[i]*100 / dic[test.Patient[i]] test.base_Percent[i] = Percent test # + papermill={"duration": 0.073583, "end_time": "2020-10-02T02:31:08.354048", "exception": false, "start_time": "2020-10-02T02:31:08.280465", "status": "completed"} tags=[] #getting FVC for base week and setting it as base_FVC of patient def get_base_FVC(data): df = data.copy() df['min_week'] = df.groupby('Patient')['predict_Week'].transform('min') base = df.loc[df.predict_Week == df.min_week][['Patient','FVC']].copy() base.columns = ['Patient','base_FVC'] base['nb']=1 base['nb'] = base.groupby('Patient')['nb'].transform('cumsum') base = base[base.nb==1] base.drop('nb',axis =1,inplace=True) df = df.merge(base,on="Patient",how='left') df.drop(['min_week'], axis = 1) return df #For Inference #getting Number of CT def get_N_CT(data, mode="test"): df = data.copy() N_CT = [] for pt_id in df.Patient: if mode is "test": png_dir = os.path.join(test_image_folder, pt_id) if mode is "train": png_dir = os.path.join(train_image_folder, pt_id) files = os.listdir(png_dir) N_CT.append(len(files)) df["N_CT"] = N_CT return df # Create feature import itertools def CreateFeat(df): def func_product(row): return (row[col1]) * (row[col2]) def func_division(row): delta = 1e-8 return (row[col1]+delta) / (row[col2]+delta) Columns = df.columns for col1, col2 in tqdm(tuple(itertools.permutations(Columns, 2))): df[f"{col1}_{col2}_prd"] = df[[col1, col2]].apply(func_product, axis=1) df[f"{col1}_{col2}_div"] = round(df[[col1, col2]].apply(func_division, axis=1), 0) print(f"Crated {len(df.columns) - len(Columns)} columns") return df #Reduce columens def ReduceCol(df): remove_cols = [] Columns = df.columns for col1, col2 in tqdm(tuple(itertools.permutations(Columns, 2))): # constant columns if df[col1].std() == 0: remove_cols.append(col1) # duplicated columns if (col1 not in remove_cols) and (col2 not in remove_cols): x, y = df[col1].values, df[col2].values if np.array_equal(x, y): remove_cols.append(col1) df.drop(remove_cols, inplace=True, axis=1) print(f"Removed {len(remove_cols)} constant & duplicated columns") return df # + papermill={"duration": 0.107599, "end_time": "2020-10-02T02:31:08.513126", "exception": false, "start_time": "2020-10-02T02:31:08.405527", "status": "completed"} tags=[] test["min_Weeks"] = np.nan test = get_base_FVC(test) test # + papermill={"duration": 0.081874, "end_time": "2020-10-02T02:31:08.647320", "exception": false, "start_time": "2020-10-02T02:31:08.565446", "status": "completed"} tags=[] test = test.drop(['min_Weeks', 'min_week'], axis = 1) test # + papermill={"duration": 4.804036, "end_time": "2020-10-02T02:31:13.504335", "exception": false, "start_time": "2020-10-02T02:31:08.700299", "status": "completed"} tags=[] train = get_N_CT(train, "train") test = get_N_CT(test) # + papermill={"duration": 0.096032, "end_time": "2020-10-02T02:31:13.654084", "exception": false, "start_time": "2020-10-02T02:31:13.558052", "status": "completed"} tags=[] train['WHERE'] = 'train' test['WHERE'] = 'test' data = train.append(test) data = data.reset_index(drop=True) Splitdata=data['WHERE'] data = data.drop(columns='WHERE') data # + papermill={"duration": 0.549441, "end_time": "2020-10-02T02:31:14.257251", "exception": false, "start_time": "2020-10-02T02:31:13.707810", "status": "completed"} tags=[] pt_min_dic = defaultdict() pt_max_dic = defaultdict() for pt_id in data.Patient.unique(): pt_min = data.FVC[data.Patient==pt_id].min() pt_max = data.FVC[data.Patient==pt_id].max() pt_min_dic[pt_id] = pt_min pt_max_dic[pt_id] = pt_max # + papermill={"duration": 0.063229, "end_time": "2020-10-02T02:31:14.374822", "exception": false, "start_time": "2020-10-02T02:31:14.311593", "status": "completed"} tags=[] data["fvc_min"] = 0.0 data["fvc_max"] = 0.0 # + papermill={"duration": 2.894775, "end_time": "2020-10-02T02:31:17.323456", "exception": false, "start_time": "2020-10-02T02:31:14.428681", "status": "completed"} tags=[] for i in range(len(data.Patient)): data["fvc_min"][i] = data.FVC[i] - pt_min_dic[data.Patient[i]] data["fvc_max"][i] = pt_max_dic[data.Patient[i]] - data.FVC[i] data # + papermill={"duration": 0.064474, "end_time": "2020-10-02T02:31:17.443605", "exception": false, "start_time": "2020-10-02T02:31:17.379131", "status": "completed"} tags=[] data["fvc_min_ratio"] = 0.0 data["fvc_max_ratio"] = 0.0 # + papermill={"duration": 2.643494, "end_time": "2020-10-02T02:31:20.142386", "exception": false, "start_time": "2020-10-02T02:31:17.498892", "status": "completed"} tags=[] for i in range(len(data.Patient)): data["fvc_min_ratio"][i] = data["fvc_min"][i] / data["base_FVC"][i] data["fvc_max_ratio"][i] = data["fvc_max"][i] / data["base_FVC"][i] data # + papermill={"duration": 0.097314, "end_time": "2020-10-02T02:31:20.295871", "exception": false, "start_time": "2020-10-02T02:31:20.198557", "status": "completed"} tags=[] data["diff_fvc"] = data["base_FVC"] - data["FVC"] data["diff_fvc_ratio"] = (data["base_FVC"] - data["FVC"])/data["base_FVC"] data # + papermill={"duration": 0.096258, "end_time": "2020-10-02T02:31:20.497745", "exception": false, "start_time": "2020-10-02T02:31:20.401487", "status": "completed"} tags=[] data['diff_fvc2'] = (data['diff_fvc'] - data['diff_fvc'].min() ) / (data['diff_fvc'].max() - data['diff_fvc'].min()) data # + papermill={"duration": 18.748916, "end_time": "2020-10-02T02:31:39.304637", "exception": false, "start_time": "2020-10-02T02:31:20.555721", "status": "completed"} tags=[] Age = [] for i in range(len(data)): Pt_base_age = data.base_Age[data.Patient == data.Patient[i]].min() # 365/7 = 52.14 # 1/52.14 = 0.01917 Pt_age = 0.0192*data.predict_Week[i] + Pt_base_age Age.append(Pt_age) data["Age"] = Age data # + papermill={"duration": 0.073793, "end_time": "2020-10-02T02:31:39.438136", "exception": false, "start_time": "2020-10-02T02:31:39.364343", "status": "completed"} tags=[] # typical_FVC_cluster fvc_cluster = {} set_fvc = sorted(list(set(round(data.FVC/data.base_Percent*100, -2)))) for idx, fvc in enumerate(set_fvc, 1): fvc_cluster[fvc] = idx fvc_cluster # + papermill={"duration": 0.824127, "end_time": "2020-10-02T02:31:40.321627", "exception": false, "start_time": "2020-10-02T02:31:39.497500", "status": "completed"} tags=[] typical_FVC_cluster = [] for i in range(len(data)): typical_FVC = round(data.FVC[i]/data.base_Percent[i]*100, -2) typical_FVC_cluster.append(fvc_cluster[typical_FVC]) data["typical_FVC_cluster"] = typical_FVC_cluster data # + papermill={"duration": 1.687051, "end_time": "2020-10-02T02:31:42.069610", "exception": false, "start_time": "2020-10-02T02:31:40.382559", "status": "completed"} tags=[] tmp1 = CreateFeat(data[["base_FVC", "diff_fvc"]]) data = pd.concat([data, tmp1], axis=1) #remove dup colunes data = data.loc[:,~data.columns.duplicated()] tmp1 = ReduceCol(data.iloc[:,10:]) data = pd.concat([data.iloc[:,:10], tmp1], axis=1) data # + papermill={"duration": 0.072916, "end_time": "2020-10-02T02:31:42.204848", "exception": false, "start_time": "2020-10-02T02:31:42.131932", "status": "completed"} tags=[] # log transform data["log_N_CT"] = np.log1p(data.N_CT) data["log_diff_fvc_base_FVC_prd"] = np.log1p(data.diff_fvc_base_FVC_prd) # + papermill={"duration": 0.077179, "end_time": "2020-10-02T02:31:42.344739", "exception": false, "start_time": "2020-10-02T02:31:42.267560", "status": "completed"} tags=[] Encoding = {"Currently smokes": 2, "Ex-smoker": 1, "Never smoked": 0, "Male": 1, "Female":0} data['SmokingStatus'] = data.SmokingStatus.map(Encoding) data["Sex"] = data.Sex.map(Encoding) # + papermill={"duration": 0.112448, "end_time": "2020-10-02T02:31:42.520347", "exception": false, "start_time": "2020-10-02T02:31:42.407899", "status": "completed"} tags=[] # clipping clipping = data.columns[10:] for col in clipping: upperbound, lowerbound = np.percentile(data[col], [1, 99]) data[col] = np.clip(data[col], upperbound, lowerbound) # + papermill={"duration": 0.072389, "end_time": "2020-10-02T02:31:42.655519", "exception": false, "start_time": "2020-10-02T02:31:42.583130", "status": "completed"} tags=[] def CreateFeat2(df): func_list = ("max", "min", "mean", "median", "mad", "var", "std")#, "skew","kurt") Columns = df.columns for idx, func in enumerate(func_list): print(f"{idx}/{len(func_list)}: Calucurating... {func}") for col1, col2 in tqdm(tuple(itertools.permutations(Columns, 2))): df[f"{col1}_{col2}_{func}"] = df[[col1, col2]].apply(func, axis=1) print(f"Crated {len(df.columns) - len(Columns)} columns") return df # + papermill={"duration": 0.081406, "end_time": "2020-10-02T02:31:42.818594", "exception": false, "start_time": "2020-10-02T02:31:42.737188", "status": "completed"} tags=[] important_col = ["diff_fvc", "Week_passed", "base_FVC"] # + papermill={"duration": 0.870895, "end_time": "2020-10-02T02:31:43.772225", "exception": false, "start_time": "2020-10-02T02:31:42.901330", "status": "completed"} tags=[] tmp = CreateFeat2(data[important_col]) data = pd.concat([data, tmp], axis=1) data= data.loc[:,~data.columns.duplicated()] tmp = ReduceCol(data.iloc[:,10:]) data = pd.concat([data.iloc[:,:10], tmp], axis=1) data # + [markdown] papermill={"duration": 0.069906, "end_time": "2020-10-02T02:31:43.913457", "exception": false, "start_time": "2020-10-02T02:31:43.843551", "status": "completed"} tags=[] # # CT images extraction # + papermill={"duration": 0.105079, "end_time": "2020-10-02T02:31:44.089118", "exception": false, "start_time": "2020-10-02T02:31:43.984039", "status": "completed"} tags=[] #https://www.kaggle.com/unforgiven/osic-comprehensive-eda import scipy.ndimage from skimage import morphology from skimage import measure from skimage.filters import threshold_otsu, median from scipy.ndimage import binary_fill_holes from skimage.segmentation import clear_border from skimage import exposure from scipy.stats import describe def load_scan(dicom_dir): files = os.listdir(dicom_dir) files.sort(key=lambda x: (int(x[:-4]), x[:-3])) dcms = [] len_files = len(files) if len_files < 15: Point = 2*len(files)//10+2 dicom_file = os.path.join(dicom_dir, files[Point]) dcms.append(dicom_file) elif len_files < 33: # 25% percentile Point = 3*len(files)//10 Range = 3 for file in files[Point: Point+Range]: dicom_file = os.path.join(dicom_dir, file) dcms.append(dicom_file) elif len_files > 500: # 75% percentile Point = 6*len(files)//10 Range = 7 for file in files[Point: Point+Range]: dicom_file = os.path.join(dicom_dir, file) dcms.append(dicom_file) else: Point = 4*len(files)//10 Range = 5 for file in files[Point: Point+Range]: dicom_file = os.path.join(dicom_dir, file) dcms.append(dicom_file) slices = [] for scan in dcms: with pydicom.dcmread(scan) as s: slices.append(s) slices.sort(key = lambda x: int(x.InstanceNumber)) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except: try: slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation) except: slice_thickness = slices[0].SliceThickness for s in slices: s.SliceThickness = slice_thickness return slices def get_pixels_hu(slices): imags = np.stack([s.pixel_array for s in slices]) # Convert to int16 (from sometimes int16), # should be possible as values should always be low enough (<32k) imags = imags.astype(np.int16) # Set outside-of-scan pixels to 1 # The intercept is usually -1024, so air is approximately 0 if slices[0].RescaleIntercept == -1024: imags[imags <= -1000] = 0 # Convert to Hounsfield units (HU) intercept = slices[0].RescaleIntercept slope = slices[0].RescaleSlope center = slices[0].WindowCenter try:thresh = center*0.9 except:thresh = center[0]*0.9 if slope != 1: imags = slope * image.astype(np.float64) imags = image.astype(np.int16) imags += np.int16(intercept) imags = np.array(imags, dtype=np.int16) binaries = [] for imag in imags: binary = imag <= thresh binaries.append(binary) mean_img = np.mean(binaries, axis=0) return mean_img def conv_img(mean_img): h, w = mean_img.shape[:2] if h == w: h1, h2 = int(h * 0.33), int(h * 0.7) w1, w2 = int(w * 0.13), int(w * 0.87) if h > w: a, b = h/w, w/h h1, h2 = int(h * 0.3*a), int(h * 0.7*b) w1, w2 = int(w * 0.13), int(w * 0.87) if h < w: a, b = w/h, h/w h1, h2 = int(h * 0.4), int(h * 0.67) w1, w2 = int(w * 0.3*a), int(w * 0.8*b) mean_img = mean_img[h1: h2, w1: w2] mean_img = cv2.resize(mean_img, (SIZE, SIZE)) stacked_img = np.stack((mean_img,)*3, -1) stacked_img = exposure.equalize_adapthist(stacked_img) return stacked_img # + [markdown] papermill={"duration": 0.070474, "end_time": "2020-10-02T02:31:44.230035", "exception": false, "start_time": "2020-10-02T02:31:44.159561", "status": "completed"} tags=[] # # Middle Layer Feature Extraction # + papermill={"duration": 0.839336, "end_time": "2020-10-02T02:31:45.139840", "exception": false, "start_time": "2020-10-02T02:31:44.300504", "status": "completed"} tags=[] # !ls ../input/keras-pretrained-models/ # + papermill={"duration": 0.079803, "end_time": "2020-10-02T02:31:45.291640", "exception": false, "start_time": "2020-10-02T02:31:45.211837", "status": "completed"} tags=[] from os import makedirs from os.path import expanduser, exists, join cache_dir = expanduser(join('~', '.keras')) if not exists(cache_dir): makedirs(cache_dir) models_dir = join(cache_dir, 'models') if not exists(models_dir): makedirs(models_dir) # + papermill={"duration": 2.576317, "end_time": "2020-10-02T02:31:47.938492", "exception": false, "start_time": "2020-10-02T02:31:45.362175", "status": "completed"} tags=[] # !cp ../input/keras-pretrained-models/*notop* ~/.keras/models/ # !cp ../input/keras-pretrained-models/imagenet_class_index.json ~/.keras/models/ # + papermill={"duration": 0.145833, "end_time": "2020-10-02T02:31:48.154746", "exception": false, "start_time": "2020-10-02T02:31:48.008913", "status": "completed"} tags=[] from keras.applications.inception_v3 import InceptionV3, preprocess_input from keras.layers import GlobalMaxPooling2D, Input from keras.models import Model # + papermill={"duration": 4.74717, "end_time": "2020-10-02T02:31:52.972822", "exception": false, "start_time": "2020-10-02T02:31:48.225652", "status": "completed"} tags=[] base_model = InceptionV3(include_top=False, weights='imagenet', input_tensor=Input((SIZE, SIZE, 3))) # + papermill={"duration": 0.110832, "end_time": "2020-10-02T02:31:53.155478", "exception": false, "start_time": "2020-10-02T02:31:53.044646", "status": "completed"} tags=[] # # Take out the following layers. # mixed7 (None, 17, 17, 768) feature = base_model.get_layer('mixed7') print(type(feature)) # <class 'keras.layers.merge.Concatenate'> print(feature.name, feature.output_shape) # mixed7 (None, 17, 17, 768) # Add Global Average Polling layer output = GlobalMaxPooling2D()(feature.output) # Create model model = Model(inputs=base_model.input, outputs=output) print(model.output_shape) # (None, 768) # + papermill={"duration": 0.495243, "end_time": "2020-10-02T02:31:53.722513", "exception": false, "start_time": "2020-10-02T02:31:53.227270", "status": "completed"} tags=[] #ファイルの読み込み import pickle from collections import defaultdict with open(train_ct_dic, 'rb') as f: data_dic = pickle.load(f) # + papermill={"duration": 0.081415, "end_time": "2020-10-02T02:31:53.876015", "exception": false, "start_time": "2020-10-02T02:31:53.794600", "status": "completed"} tags=[] len(data_dic) # + papermill={"duration": 0.526505, "end_time": "2020-10-02T02:31:54.473960", "exception": false, "start_time": "2020-10-02T02:31:53.947455", "status": "completed"} tags=[] tmp_df = test.reset_index(drop=True) for pt_id in tqdm(set(list(tmp_df.Patient))): dicom_dir = os.path.join(test_image_folder, pt_id) patient = load_scan(dicom_dir) mean_img = get_pixels_hu(patient) stacked_img = conv_img(mean_img) data_dic[pt_id]=stacked_img # + papermill={"duration": 0.080689, "end_time": "2020-10-02T02:31:54.627491", "exception": false, "start_time": "2020-10-02T02:31:54.546802", "status": "completed"} tags=[] len(data_dic) # + papermill={"duration": 0.080377, "end_time": "2020-10-02T02:31:54.780334", "exception": false, "start_time": "2020-10-02T02:31:54.699957", "status": "completed"} tags=[] def processed_img(pt_id): img = data_dic[pt_id] img = np.expand_dims(img, axis=0) return img # + papermill={"duration": 0.083348, "end_time": "2020-10-02T02:31:54.937841", "exception": false, "start_time": "2020-10-02T02:31:54.854493", "status": "completed"} tags=[] pt_lst = list(set(data.Patient)) data_img = processed_img(pt_lst[0]) # + papermill={"duration": 9.607812, "end_time": "2020-10-02T02:32:04.619230", "exception": false, "start_time": "2020-10-02T02:31:55.011418", "status": "completed"} tags=[] for pt_id in tqdm(pt_lst[1:]): img = processed_img(pt_id) data_img = np.vstack([data_img, img]) # + papermill={"duration": 19.636124, "end_time": "2020-10-02T02:32:24.329278", "exception": false, "start_time": "2020-10-02T02:32:04.693154", "status": "completed"} tags=[] from sklearn.decomposition import PCA from umap import UMAP pca = PCA(n_components=100, random_state=42) umap = UMAP(n_components=3, random_state=42) # Extract Middle Layer Features img_features = model.predict(data_img) print(img_features.shape) pca.fit(img_features) # PCA x = pca.fit_transform(img_features) print(f"PCA:{x.shape}") plt.scatter(x[:, 0], x[:, 1]) plt.title("Embedding Space with PCA") plt.show() #UMAP x = umap.fit_transform(x) print(f"UMAP:{x.shape}") plt.scatter(x[:, 0], x[:, 1]) plt.title("Embedding Space with UMAP") plt.show() # + papermill={"duration": 0.153197, "end_time": "2020-10-02T02:32:24.559116", "exception": false, "start_time": "2020-10-02T02:32:24.405919", "status": "completed"} tags=[] feature_dic = defaultdict() for idx, pt_id in tqdm(enumerate(set(list(data.Patient)))): feature_dic[pt_id] = x[idx] feature_dic # + papermill={"duration": 0.200874, "end_time": "2020-10-02T02:32:24.837127", "exception": false, "start_time": "2020-10-02T02:32:24.636253", "status": "completed"} tags=[] features = feature_dic[data.Patient[0]] for pt_id in data.Patient[1:]: features = np.vstack([features, feature_dic[pt_id]]) features # + papermill={"duration": 0.087858, "end_time": "2020-10-02T02:32:25.002839", "exception": false, "start_time": "2020-10-02T02:32:24.914981", "status": "completed"} tags=[] img_feature1 = features[:,0].tolist() img_feature2 = features[:,1].tolist() img_feature3 = features[:,2].tolist() # + papermill={"duration": 0.138671, "end_time": "2020-10-02T02:32:25.219557", "exception": false, "start_time": "2020-10-02T02:32:25.080886", "status": "completed"} tags=[] data["img_feature1"] = img_feature1 data["img_feature2"] = img_feature2 data["img_feature3"] = img_feature3 data # + papermill={"duration": 1.838406, "end_time": "2020-10-02T02:32:27.137598", "exception": false, "start_time": "2020-10-02T02:32:25.299192", "status": "completed"} tags=[] tmp1 = CreateFeat(data[["base_FVC_diff_fvc_div", "img_feature1"]]) data = pd.concat([data, tmp1], axis=1) #remove dup colunes data = data.loc[:,~data.columns.duplicated()] tmp1 = ReduceCol(data.iloc[:,10:]) data = pd.concat([data.iloc[:,:10], tmp1], axis=1) data # + papermill={"duration": 1.888388, "end_time": "2020-10-02T02:32:29.108526", "exception": false, "start_time": "2020-10-02T02:32:27.220138", "status": "completed"} tags=[] tmp1 = CreateFeat(data[["base_FVC_diff_fvc_div", "img_feature2"]]) data = pd.concat([data, tmp1], axis=1) #remove dup colunes data = data.loc[:,~data.columns.duplicated()] tmp1 = ReduceCol(data.iloc[:,10:]) data = pd.concat([data.iloc[:,:10], tmp1], axis=1) data # + papermill={"duration": 1.943292, "end_time": "2020-10-02T02:32:31.139168", "exception": false, "start_time": "2020-10-02T02:32:29.195876", "status": "completed"} tags=[] tmp1 = CreateFeat(data[["base_FVC_diff_fvc_div", "img_feature3"]]) data = pd.concat([data, tmp1], axis=1) #remove dup colunes data = data.loc[:,~data.columns.duplicated()] tmp1 = ReduceCol(data.iloc[:,10:]) data = pd.concat([data.iloc[:,:10], tmp1], axis=1) data # + papermill={"duration": 0.150204, "end_time": "2020-10-02T02:32:31.376491", "exception": false, "start_time": "2020-10-02T02:32:31.226287", "status": "completed"} tags=[] data = data.replace([np.inf, -np.inf], np.nan) data = data.dropna(how='any', axis=1) data # + papermill={"duration": 0.179785, "end_time": "2020-10-02T02:32:31.644860", "exception": false, "start_time": "2020-10-02T02:32:31.465075", "status": "completed"} tags=[] # clipping clipping = data.columns[10:] for col in clipping: upperbound, lowerbound = np.percentile(data[col], [1, 99]) data[col] = np.clip(data[col], upperbound, lowerbound) # + papermill={"duration": 0.143415, "end_time": "2020-10-02T02:32:31.876114", "exception": false, "start_time": "2020-10-02T02:32:31.732699", "status": "completed"} tags=[] # clean up column names with a simple instruction # https://stackoverflow.com/questions/60698860/how-to-deal-with-do-not-support-non-ascii-characters-in-feature-name-error-whe import re data = data.rename(columns = lambda x:re.sub('[^A-Za-z0-9_]+', '', x)) data # + papermill={"duration": 0.144334, "end_time": "2020-10-02T02:32:32.115224", "exception": false, "start_time": "2020-10-02T02:32:31.970890", "status": "completed"} tags=[] data['WHERE'] = Splitdata data train = data[data['WHERE']=="train"] test = data[data['WHERE']=="test"] test # + papermill={"duration": 0.113129, "end_time": "2020-10-02T02:32:32.319346", "exception": false, "start_time": "2020-10-02T02:32:32.206217", "status": "completed"} tags=[] submission = pd.read_csv('../input/osic-pulmonary-fibrosis-progression/sample_submission.csv') print(submission.shape) submission.head() # + [markdown] papermill={"duration": 0.092267, "end_time": "2020-10-02T02:32:32.503301", "exception": false, "start_time": "2020-10-02T02:32:32.411034", "status": "completed"} tags=[] # # Prepare folds # + papermill={"duration": 0.127607, "end_time": "2020-10-02T02:32:32.723351", "exception": false, "start_time": "2020-10-02T02:32:32.595744", "status": "completed"} tags=[] folds = train[[ID, 'Patient', TARGET]].copy() #Fold = KFold(n_splits=N_FOLD, shuffle=True, random_state=SEED) Fold = GroupKFold(n_splits=N_FOLD) groups = folds['Patient'].values for n, (train_index, val_index) in enumerate(Fold.split(folds, folds[TARGET], groups)): folds.loc[val_index, 'fold'] = int(n) folds['fold'] = folds['fold'].astype(int) folds # + [markdown] papermill={"duration": 0.093225, "end_time": "2020-10-02T02:32:32.909332", "exception": false, "start_time": "2020-10-02T02:32:32.816107", "status": "completed"} tags=[] # ## Custom Objective / Metric # # The competition evaluation metric is: # # $ # \displaystyle \sigma_{clipped} = \max \left ( \sigma, 70 \right ) \\ # \displaystyle \Delta = \min \left ( \|FVC_{ture} - FVC_{predicted}\|, 1000 \right ) \\ # \displaystyle f_{metric} = - \frac{\sqrt{2} \Delta}{\sigma_{clipped}} - \ln \left( \sqrt{2} \sigma_{clipped} \right) . # $ # # This is too complex to directly optimize by custom metric. # Here I use negative loglilelihood loss (_NLL_) of gaussian. # # Let $FVC_{ture}$ is $t$ and $FVC_{predicted}$ is $\mu$, the _NLL_ $l$ is formulated by: # # $ # \displaystyle l\left( t, \mu, \sigma \right) = # -\ln \left [ \frac{1}{\sqrt{2 \pi} \sigma} \exp \left \{ - \frac{\left(t - \mu \right)^2}{2 \sigma^2} \right \} \right ] # = \frac{\left(t - \mu \right)^2}{2 \sigma^2} + \ln \left( \sqrt{2 \pi} \sigma \right). # $ # # `grad` and `hess` are calculated as follows: # # $ # \displaystyle \frac{\partial l}{\partial \mu } = -\frac{t - \mu}{\sigma^2} \ , \ \frac{\partial^2 l}{\partial \mu^2 } = \frac{1}{\sigma^2} # $ # # $ # \displaystyle \frac{\partial l}{\partial \sigma} # =-\frac{\left(t - \mu \right)^2}{\sigma^3} + \frac{1}{\sigma} = \frac{1}{\sigma} \left\{ 1 - \left ( \frac{t - \mu}{\sigma} \right)^2 \right \} # \\ # \displaystyle \frac{\partial^2 l}{\partial \sigma^2} # = -\frac{1}{\sigma^2} \left\{ 1 - \left ( \frac{t - \mu}{\sigma} \right)^2 \right \} # # +\frac{1}{\sigma} \frac{2 \left(t - \mu \right)^2 }{\sigma^3} # = -\frac{1}{\sigma^2} \left\{ 1 - 3 \left ( \frac{t - \mu}{\sigma} \right)^2 \right \} # $ # + [markdown] papermill={"duration": 0.091752, "end_time": "2020-10-02T02:32:33.094528", "exception": false, "start_time": "2020-10-02T02:32:33.002776", "status": "completed"} tags=[] # For numerical stability, I replace $\sigma$ with $\displaystyle \tilde{\sigma} := \log\left(1 + \mathrm{e}^{\sigma} \right).$ # # $ # \displaystyle l'\left( t, \mu, \sigma \right) # = \frac{\left(t - \mu \right)^2}{2 \tilde{\sigma}^2} + \ln \left( \sqrt{2 \pi} \tilde{\sigma} \right). # $ # # $ # \displaystyle \frac{\partial l'}{\partial \mu } = -\frac{t - \mu}{\tilde{\sigma}^2} \ , \ \frac{\partial^2 l}{\partial \mu^2 } = \frac{1}{\tilde{\sigma}^2} # $ # <br> # # $ # \displaystyle \frac{\partial l'}{\partial \sigma} # = \frac{1}{\tilde{\sigma}} \left\{ 1 - \left ( \frac{t - \mu}{\tilde{\sigma}} \right)^2 \right \} \frac{\partial \tilde{\sigma}}{\partial \sigma} # \\ # \displaystyle \frac{\partial^2 l'}{\partial \sigma^2} # = -\frac{1}{\tilde{\sigma}^2} \left\{ 1 - 3 \left ( \frac{t - \mu}{\tilde{\sigma}} \right)^2 \right \} # \left( \frac{\partial \tilde{\sigma}}{\partial \sigma} \right) ^2 # # +\frac{1}{\tilde{\sigma}} \left\{ 1 - \left ( \frac{t - \mu}{\tilde{\sigma}} \right)^2 \right \} \frac{\partial^2 \tilde{\sigma}}{\partial \sigma^2} # $ # # , where # # $ # \displaystyle # \frac{\partial \tilde{\sigma}}{\partial \sigma} = \frac{1}{1 + \mathrm{e}^{-\sigma}} \\ # \displaystyle # \frac{\partial^2 \tilde{\sigma}}{\partial^2 \sigma} = \frac{\mathrm{e}^{-\sigma}}{\left( 1 + \mathrm{e}^{-\sigma} \right)^2} # = \frac{\partial \tilde{\sigma}}{\partial \sigma} \left( 1 - \frac{\partial \tilde{\sigma}}{\partial \sigma} \right) # $ # + _kg_hide-input=false papermill={"duration": 0.122343, "end_time": "2020-10-02T02:32:33.309876", "exception": false, "start_time": "2020-10-02T02:32:33.187533", "status": "completed"} tags=[] class OSICLossForLGBM: """ Custom Loss for LightGBM. * Objective: return grad & hess of NLL of gaussian * Evaluation: return competition metric """ def __init__(self, epsilon: float=1) -> None: """Initialize.""" self.name = "osic_loss" self.n_class = 2 # FVC & Confidence self.epsilon = epsilon def __call__(self, preds: np.ndarray, labels: np.ndarray, weight: tp.Optional[np.ndarray]=None) -> float: """Calc loss.""" sigma_clip = np.maximum(preds[:, 1], 70) Delta = np.minimum(np.abs(preds[:, 0] - labels), 1000) loss_by_sample = - np.sqrt(2) * Delta / sigma_clip - np.log(np.sqrt(2) * sigma_clip) loss = np.average(loss_by_sample, weight) return loss def _calc_grad_and_hess( self, preds: np.ndarray, labels: np.ndarray, weight: tp.Optional[np.ndarray]=None ) -> tp.Tuple[np.ndarray]: """Calc Grad and Hess""" mu = preds[:, 0] sigma = preds[:, 1] sigma_t = np.log(1 + np.exp(sigma)) grad_sigma_t = 1 / (1 + np.exp(- sigma)) hess_sigma_t = grad_sigma_t * (1 - grad_sigma_t) grad = np.zeros_like(preds) hess = np.zeros_like(preds) grad[:, 0] = - (labels - mu) / sigma_t ** 2 hess[:, 0] = 1 / sigma_t ** 2 tmp = ((labels - mu) / sigma_t) ** 2 grad[:, 1] = 1 / sigma_t * (1 - tmp) * grad_sigma_t hess[:, 1] = ( - 1 / sigma_t ** 2 * (1 - 3 * tmp) * grad_sigma_t ** 2 + 1 / sigma_t * (1 - tmp) * hess_sigma_t ) if weight is not None: grad = grad * weight[:, None] hess = hess * weight[:, None] return grad, hess def return_loss(self, preds: np.ndarray, data: lgb.Dataset) -> tp.Tuple[str, float, bool]: """Return Loss for lightgbm""" labels = data.get_label() weight = data.get_weight() n_example = len(labels) # # reshape preds: (n_class * n_example,) => (n_class, n_example) => (n_example, n_class) preds = preds.reshape(self.n_class, n_example).T # # calc loss loss = self(preds, labels, weight) return self.name, loss, True def return_grad_and_hess(self, preds: np.ndarray, data: lgb.Dataset) -> tp.Tuple[np.ndarray]: """Return Grad and Hess for lightgbm""" labels = data.get_label() weight = data.get_weight() n_example = len(labels) # # reshape preds: (n_class * n_example,) => (n_class, n_example) => (n_example, n_class) preds = preds.reshape(self.n_class, n_example).T # # calc grad and hess. grad, hess = self._calc_grad_and_hess(preds, labels, weight) # # reshape grad, hess: (n_example, n_class) => (n_class, n_example) => (n_class * n_example,) grad = grad.T.reshape(n_example * self.n_class) hess = hess.T.reshape(n_example * self.n_class) return grad, hess # + [markdown] papermill={"duration": 0.09236, "end_time": "2020-10-02T02:32:33.495448", "exception": false, "start_time": "2020-10-02T02:32:33.403088", "status": "completed"} tags=[] # ## Training Utils # + papermill={"duration": 0.12133, "end_time": "2020-10-02T02:32:33.709158", "exception": false, "start_time": "2020-10-02T02:32:33.587828", "status": "completed"} tags=[] #=========================================================== # model #=========================================================== def run_single_lightgbm( model_param, fit_param, train_df, test_df, folds, features, target, fold_num=0, categorical=[], my_loss=None, ): trn_idx = folds[folds.fold != fold_num].index val_idx = folds[folds.fold == fold_num].index logger.info(f'len(trn_idx) : {len(trn_idx)}') logger.info(f'len(val_idx) : {len(val_idx)}') if categorical == []: trn_data = lgb.Dataset( train_df.iloc[trn_idx][features], label=target.iloc[trn_idx]) val_data = lgb.Dataset( train_df.iloc[val_idx][features], label=target.iloc[val_idx]) else: trn_data = lgb.Dataset( train_df.iloc[trn_idx][features], label=target.iloc[trn_idx], categorical_feature=categorical) val_data = lgb.Dataset( train_df.iloc[val_idx][features], label=target.iloc[val_idx], categorical_feature=categorical) oof = np.zeros((len(train_df), 2)) predictions = np.zeros((len(test_df), 2)) best_model_str = [""] clf = lgb.train( model_param, trn_data, **fit_param, valid_sets=[trn_data, val_data], fobj=my_loss.return_grad_and_hess, feval=my_loss.return_loss, ) oof[val_idx] = clf.predict(train_df.iloc[val_idx][features], num_iteration=clf.best_iteration) fold_importance_df = pd.DataFrame() fold_importance_df["Feature"] = features fold_importance_df["importance"] = clf.feature_importance(importance_type='gain') fold_importance_df["fold"] = fold_num predictions += clf.predict(test_df[features], num_iteration=clf.best_iteration) # RMSE logger.info("fold{} RMSE score: {:<8.5f}".format( fold_num, np.sqrt(mean_squared_error(target[val_idx], oof[val_idx, 0])))) # Competition Metric logger.info("fold{} Metric: {:<8.5f}".format( fold_num, my_loss(oof[val_idx], target[val_idx]))) return oof, predictions, fold_importance_df def run_kfold_lightgbm( model_param, fit_param, train, test, folds, features, target, n_fold=5, categorical=[], my_loss=None, ): logger.info(f"================================= {n_fold}fold lightgbm =================================") oof = np.zeros((len(train), 2)) predictions = np.zeros((len(test), 2)) feature_importance_df = pd.DataFrame() for fold_ in range(n_fold): print("Fold {}".format(fold_)) _oof, _predictions, fold_importance_df =\ run_single_lightgbm( model_param, fit_param, train, test, folds, features, target, fold_num=fold_, categorical=categorical, my_loss=my_loss ) feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0) oof += _oof predictions += _predictions / n_fold # RMSE logger.info("CV RMSE score: {:<8.5f}".format(np.sqrt(mean_squared_error(target, oof[:, 0])))) # Metric logger.info("CV Metric: {:<8.5f}".format(my_loss(oof, target))) logger.info(f"=========================================================================================") return feature_importance_df, predictions, oof def show_feature_importance(feature_importance_df, name): cols = (feature_importance_df[["Feature", "importance"]] .groupby("Feature") .mean() .sort_values(by="importance", ascending=False)[:50].index) best_features = feature_importance_df.loc[feature_importance_df.Feature.isin(cols)] plt.figure(figsize=(8, 16)) #plt.figure(figsize=(6, 4)) sns.barplot(x="importance", y="Feature", data=best_features.sort_values(by="importance", ascending=False)) plt.title('Features importance (averaged/folds)') plt.tight_layout() plt.savefig(OUTPUT_DICT+f'feature_importance_{name}.png') # + [markdown] papermill={"duration": 0.093426, "end_time": "2020-10-02T02:32:33.894691", "exception": false, "start_time": "2020-10-02T02:32:33.801265", "status": "completed"} tags=[] # ## predict FVC & Confidence(signa) # + papermill={"duration": 9.618433, "end_time": "2020-10-02T02:32:43.607369", "exception": false, "start_time": "2020-10-02T02:32:33.988936", "status": "completed"} tags=[] target = train[TARGET] test[TARGET] = np.nan # features cat_features = [] num_features = [c for c in test.columns if (test.dtypes[c] != 'object') & (c not in cat_features)] features = num_features + cat_features drop_features = [ID, TARGET, 'predict_Week', 'base_Week', 'WHERE'] features = [c for c in features if c not in drop_features] if cat_features: ce_oe = ce.OrdinalEncoder(cols=cat_features, handle_unknown='impute') ce_oe.fit(train) train = ce_oe.transform(train) test = ce_oe.transform(test) lgb_model_param = { 'num_class': 2, # 'objective': 'regression', 'metric': 'None', 'boosting_type': 'gbdt', 'learning_rate': 5e-02, 'seed': SEED, "subsample": 0.4, "subsample_freq": 1, 'max_depth': 1, 'verbosity': -1, } lgb_fit_param = { "num_boost_round": 10000, "verbose_eval":100, "early_stopping_rounds": 500, } feature_importance_df, predictions, oof = run_kfold_lightgbm( lgb_model_param, lgb_fit_param, train, test, folds, features, target, n_fold=N_FOLD, categorical=cat_features, my_loss=OSICLossForLGBM()) show_feature_importance(feature_importance_df, TARGET) # + papermill={"duration": 0.115375, "end_time": "2020-10-02T02:32:43.828558", "exception": false, "start_time": "2020-10-02T02:32:43.713183", "status": "completed"} tags=[] oof[:5, :] # + papermill={"duration": 0.117242, "end_time": "2020-10-02T02:32:44.054282", "exception": false, "start_time": "2020-10-02T02:32:43.937040", "status": "completed"} tags=[] predictions[:5] # + papermill={"duration": 0.120083, "end_time": "2020-10-02T02:32:44.282707", "exception": false, "start_time": "2020-10-02T02:32:44.162624", "status": "completed"} tags=[] train["FVC_pred"] = oof[:, 0] train["Confidence"] = oof[:, 1] test["FVC_pred"] = predictions[:, 0] test["Confidence"] = predictions[:, 1] # + [markdown] papermill={"duration": 0.107842, "end_time": "2020-10-02T02:32:44.500394", "exception": false, "start_time": "2020-10-02T02:32:44.392552", "status": "completed"} tags=[] # # Submission # + papermill={"duration": 0.122931, "end_time": "2020-10-02T02:32:44.731461", "exception": false, "start_time": "2020-10-02T02:32:44.608530", "status": "completed"} tags=[] submission.head() # + papermill={"duration": 0.139061, "end_time": "2020-10-02T02:32:44.978803", "exception": false, "start_time": "2020-10-02T02:32:44.839742", "status": "completed"} tags=[] sub = submission.drop(columns=['FVC', 'Confidence']).merge(test[['Patient_Week', 'FVC_pred', 'Confidence']], on='Patient_Week') sub.columns = submission.columns sub.to_csv('submission.csv', index=False) sub # + papermill={"duration": 0.398334, "end_time": "2020-10-02T02:32:45.486327", "exception": false, "start_time": "2020-10-02T02:32:45.087993", "status": "completed"} tags=[] plt.subplot(121) sns.distplot(sub.Confidence) plt.subplot(122) sns.distplot(sub.FVC); # + papermill={"duration": 0.153932, "end_time": "2020-10-02T02:32:45.750466", "exception": false, "start_time": "2020-10-02T02:32:45.596534", "status": "completed"} tags=[] sub.describe() # + papermill={"duration": 0.11669, "end_time": "2020-10-02T02:32:45.984240", "exception": false, "start_time": "2020-10-02T02:32:45.867550", "status": "completed"} tags=[]
notebooks/20201001-osic-baseline-lgbm-with-custom-metric-v8.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # A code example showing how to load NuSTAR evt file and check what it contains # + from astropy.io import fits import numpy as np import astropy.time import astropy.units as u import matplotlib import matplotlib.pyplot as plt # %matplotlib inline import warnings warnings.simplefilter('ignore') dirin='' infile = 'nu90410111001A06_cl_sunpos.evt' # Load in the evt hdulist = fits.open(dirin+infile) # hdulist.info() evtdata=hdulist[1].data hdr = hdulist[1].header # What are the column names of the event list (evtdata) print(hdulist[1].columns.names) hdulist.close() # - # Setup the font used for plotting matplotlib.rcParams['font.sans-serif'] = "Arial" matplotlib.rcParams['font.family'] = "sans-serif" matplotlib.rcParams['font.size'] = 18 # so what does the data look like? print(evtdata) print(evtdata[0]) # plot the x,y position (1500,1500) is (0,0) in HPS fig = plt.figure(figsize=(10, 5)) plt.plot(evtdata['x'],evtdata['y'],'.',ms=0.7) plt.show() # + # plot the x,y position converted into HPS # Find the correct keys to use for field in hdr.keys(): if field.find('TYPE') != -1: if hdr[field] == 'X': xval = field[5:8] # Using pixelsize and number of pixels same in x and y # Should be 3000 and 2.45810736 (x might be -ve from ra to HPS conversion, just need magnitude here) npix=hdr['TLMAX'+xval] pixsize=abs(hdr['TCDLT'+xval]) # get rid of the outlier points (value found from above plot) xy_filter=evtdata["x"] > 800 goodinds=xy_filter.nonzero() xx=evtdata["x"][goodinds] yy=evtdata["y"][goodinds] xa=pixsize*(xx-npix*0.5) ya=pixsize*(yy-npix*0.5) fig = plt.figure(figsize=(7, 7)) plt.plot(xa,ya,'.',ms=0.7) plt.xlabel('x [arcsec]') plt.ylabel('y [arcsec]') plt.show() # + # plot the energy vs time (seconds from start) # Energy = PI*0.04 +1.6 keV fig = plt.figure(figsize=(10, 5)) plt.plot(evtdata['time']-evtdata['time'][0],evtdata['pi']*0.04+1.6,'.',ms=0.7) plt.ylabel('Energy [keV]') plt.xlabel('$t-t_0$ [s]') plt.ylim([1.6,10]) plt.show() # + # Plot a simple spectrum of the whole evtdata hist, bin_edges=np.histogram(evtdata['pi']*0.04+1.6,bins=np.arange(2.0,12,0.1)) # print(hist) fig = plt.figure(figsize=(8, 5)) # as using the left bin edges want steps-pre plt.semilogy(bin_edges[:-1],hist,drawstyle='steps-pre') plt.xlabel('Energy [keV]') plt.ylabel('Counts') plt.show() # + # # #look and see what all the header tags are # for i in hdr.keys(): # print(i) # print some of them print(hdr['date-obs']) print(hdr['tstart'],hdr['tstop']) print(hdr['ontime']) print(hdr['exposure'],hdr['livetime']) print(hdr['mjdrefi']) print(hdr['TELESCOP'],hdr['INSTRUME'],hdr['obs_id']) # Some playing about with the time formats mjdref=astropy.time.Time(hdr['mjdrefi'],format='mjd') tstart=astropy.time.Time(hdr['mjdrefi']*u.d+hdr['tstart']*u.s,format='mjd') tstop=astropy.time.Time(hdr['mjdrefi']*u.d+hdr['tstop']*u.s,format='mjd') print(mjdref.isot) print(tstart.isot,tstop.isot) # -
python/example_evt_fits.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_data_validation as tfdv print('TFDV version: {}'.format(tfdv.version.__version__)) # # Generate Statistic # + # Generate and visualize statistic of a dataset my_train_stats = tfdv.generate_statistics_from_csv(data_location="train.csv") tfdv.visualize_statistics(my_train_stats) # + # Export statistic into file tfdv.write_stats_text(my_train_stats, "my_train_stats.pbtext") # f = open("my_train_stats.pbtext", "r") # print(f.read()) # f.close() # - # # Generate Schema # # + # Generate Schema import warnings warnings.filterwarnings('ignore') my_schema = tfdv.infer_schema(statistics=my_train_stats) tfdv.display_schema(schema=my_schema) # + tfdv.write_schema_text(my_schema, "train_schema.pbtext") # p = open("train_schema.pbtext", "r") # print(p.read()) # p.close() # - # # Check Anomalies # + # Validate anomalies # Import new dataset my_train_missing_stats = tfdv.generate_statistics_from_csv(data_location="train-missing-field.csv") # Validate my_anomalies = tfdv.validate_statistics(statistics=my_train_missing_stats, schema=my_schema) tfdv.display_anomalies(my_anomalies) # + #Ignore validation error # All features are by default in both TRAINING and SERVING environments. my_schema.default_environment.append('TRAINING') my_schema.default_environment.append('SERVING') # Specify that 'risk_lvel' feature is not in SERVING environment. tfdv.get_feature(my_schema, 'risk_level').not_in_environment.append('SERVING') serving_anomalies_with_env = tfdv.validate_statistics(statistics=my_train_missing_stats, schema=my_schema, environment='SERVING') tfdv.display_anomalies(serving_anomalies_with_env) # - # # Detect Data Skew # + # Detect Data Skew my_test_stats = tfdv.generate_statistics_from_csv(data_location="test.csv") race=tfdv.get_feature(my_schema, 'race') race.skew_comparator.infinity_norm.threshold = 0.1 my_skew_anomalies = tfdv.validate_statistics(my_train_stats, my_schema, serving_statistics=my_test_stats) tfdv.display_anomalies(my_skew_anomalies) # - tfdv.visualize_statistics(lhs_statistics=my_train_stats, rhs_statistics=my_test_stats, lhs_name='Train_Dataset', rhs_name='Test_Dataset') # # Detect Data Drift # + # Import new dataset my_train2_stats = tfdv.generate_statistics_from_csv(data_location="train2.csv") # Create new schema to prevent messing up with data skew example my_schema2 = tfdv.infer_schema(statistics=my_train_stats) risk_level=tfdv.get_feature(my_schema2, 'risk_level') risk_level.drift_comparator.infinity_norm.threshold = 0.1 my_drift_anomalies = tfdv.validate_statistics(my_train_stats, my_schema2, previous_statistics=my_train2_stats, serving_statistics=my_test_stats) tfdv.display_anomalies(my_drift_anomalies) # - tfdv.visualize_statistics(lhs_statistics=my_train_stats, rhs_statistics=my_train2_stats, lhs_name='Train_Dataset', rhs_name='Train2_Dataset') tfdv.visualize_statistics(lhs_statistics=my_train2_stats, rhs_statistics=my_test_stats, lhs_name='Train2_Dataset', rhs_name='Test_Dataset')
TFDV simple example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:4ce] * # language: python # name: conda-env-4ce-py # --- # + # %load_ext autoreload # %autoreload 2 # %aimport utils_1_0 import altair as alt import pandas as pd from utils_1_0 import get_visualization_subtitle from web import for_website # - # # Data # ### Input File Format # The input file format is identical to "Options 1: File" in UpSetR-shiny (https://github.com/hms-dbmi/UpSetR-shiny) # # - Columns are `attribute 1, attribute 2, ... attribute N, set 1, set2, ..., set M` where `set` columns contain either `1` or `0`, `1` indicating the '⬤' representation in UpSet # #### Demo Data: COVID Symptom Tracker April 7 (via https://www.nature.com/articles/d41586-020-00154-w) # <img src="https://media.nature.com/lw800/magazine-assets/d41586-020-00154-w/d41586-020-00154-w_17880786.jpg" alt="demo_diagram" style="width:300px;"/> # + df = pd.read_csv("../data/covid_symptoms_table.csv") df # - # # Visualization # #### The UpSetAltair visualizations contain three main views: # # (1) **vertical bar chart** on the top showing the cardinality of each intersecting set; # # (2) **matrix view** on the bottom-left showing the intersecting set; # # (3) **horizontal bar chart** on the bottom-right showing the cardinality of each set. # # #### Options: # 1. Specify sets of interest (e.g., `["Comedy", "Action", "Adventure"]`) # 2. ~~Show empty intersections or not~~ (not yet supported) # 3. Sorting type: `Frequency` or `Degree` # 4. Sorting order: `descending` or `ascending` # Top-level altair configuration def upsetaltair_top_level_configuration( base, legend_orient="top-left", legend_symbol_size=30 ): return base.configure_view( stroke=None ).configure_title( fontSize=18, fontWeight=400, anchor="start" ).configure_axis( labelFontSize=14, labelFontWeight=300, titleFontSize=16, titleFontWeight=400, titlePadding=10 ).configure_legend( titleFontSize=16, titleFontWeight=400, labelFontSize=14, labelFontWeight=300, padding=10, orient=legend_orient, symbolType="circle", symbolSize=legend_symbol_size, ).configure_concat( spacing=0 ) def UpSetAltair( data=None, sets=None, # This reflects the order of sets to be shown in the plots as well abbre=None, sort_by="Frequency", sort_order="ascending", width=1200, height=700, height_ratio=0.6, horizontal_bar_chart_width=300 ): if (data is None) or (sets is None): print("No data and/or a list of sets are provided") return if (height_ratio < 0) or (1 < height_ratio): print("height_ratio set to 0.5") height_ratio = 0.5 """ Data Preprocessing """ data["count"] = 0 data = data[sets + ["count"]] data = data.groupby(sets).count().reset_index() data["intersection_id"] = data.index data["degree"] = data[sets].sum(axis=1) data = data.sort_values(by=["count"], ascending=True if sort_order == "ascending" else False) data = pd.melt(data, id_vars=[ "intersection_id", "count", "degree" # wide to long ]) data = data.rename(columns={"variable": "set", "value": "is_intersect"}) set_to_abbre = pd.DataFrame([ [sets[i], abbre[i]] for i in range(len(sets)) ], columns=["set", "set_abbre"]) set_to_order = pd.DataFrame([ [sets[i], 1 + sets.index(sets[i])] for i in range(len(sets)) ], columns=["set", "set_order"]) degree_calculation = "" for s in sets: degree_calculation += f"(isDefined(datum['{s}']) ? datum['{s}'] : 0)" if sets[-1] != s: degree_calculation += "+" degree_calculation = "" for s in sets: degree_calculation += f"(isDefined(datum['{s}']) ? datum['{s}'] : 0)" if sets[-1] != s: degree_calculation += "+" """ Styles """ vertical_bar_chart_height = height * height_ratio matrix_height = height - vertical_bar_chart_height matrix_width = width - horizontal_bar_chart_width glyph_size = 200 bar_padding = 20 vertical_bar_size = min(30, width / len(data["intersection_id"].unique().tolist()) - bar_padding) horizontal_bar_size = 20 set_label_bg_size = 1000 line_connection_size = 2 color_range = ["#55A8DB", "#3070B5", "#30363F", "#F1AD60", "#DF6234", "#BDC6CA"] main_color = "#3A3A3A" x_sort = alt.Sort( field="count" if sort_by == "Frequency" else "degree", order=sort_order ) # Selections legend_selection = alt.selection_multi(fields=["set"], bind="legend") """ Plots """ # We are transforming data w/ Altair's core functions because # we want to use interactive legends. base = alt.Chart(data).transform_filter( legend_selection ).transform_pivot( # Right before this operation, columns should be: # count, set, is_intersect, (intersection_id, degree, set_order, set_abbre) # where (fields with brackets) should be dropped and recalculated later. "set", op="max", groupby=["intersection_id", "count"], value="is_intersect" ).transform_aggregate( # count, set1, set2, ... count="sum(count)", groupby=sets ).transform_calculate( # count, set1, set2, ... degree=degree_calculation ).transform_filter( # count, set1, set2, ..., degree alt.datum["degree"] != 0 ).transform_window( # count, set1, set2, ..., degree intersection_id="row_number()", frame=[None, None] ).transform_fold( # count, set1, set2, ..., degree, intersection_id sets, as_=["set", "is_intersect"] ).transform_lookup( # count, set, is_intersect, degree, intersection_id lookup="set", from_=alt.LookupData(set_to_abbre, "set", ["set_abbre"]) ).transform_lookup( # count, set, is_intersect, degree, intersection_id, set_abbre lookup="set", from_=alt.LookupData(set_to_order, "set", ["set_order"]) ).transform_filter( # Make sure to remove the filtered sets. legend_selection ).transform_window( # count, set, is_intersect, degree, intersection_id, set_abbre set_order="distinct(set)", frame=[None, 0], sort=[{"field": "set_order"}] ) # Now, we have data in the following format: # count, set, is_intersect, degree, intersection_id, set_abbre # Cardinality by intersecting sets (vertical bar chart) vertical_bar = base.mark_bar(color=main_color, size=vertical_bar_size).encode( x=alt.X( "intersection_id:N", axis=alt.Axis(grid=False, labels=False, ticks=False, domain=True), sort=x_sort, title=None ), y=alt.Y( "max(count):Q", axis=alt.Axis(grid=False, tickCount=3, orient='right'), title="Intersection Size" ) ).properties( width=matrix_width, height=vertical_bar_chart_height ) vertical_bar_text = vertical_bar.mark_text( color=main_color, dy=-10, size=16 ).encode( text=alt.Text("count:Q", format=".0f") ) vertical_bar_chart = (vertical_bar + vertical_bar_text) # UpSet glyph view (matrix view) circle_bg = vertical_bar.mark_circle(size=glyph_size, opacity=1).encode( x=alt.X( "intersection_id:N", axis=alt.Axis(grid=False, labels=False, ticks=False, domain=False), sort=x_sort, title=None ), y=alt.Y( "set_order:N", axis=alt.Axis(grid=False, labels=False, ticks=False, domain=False), title=None ), color=alt.value("#E6E6E6") ).properties( height=matrix_height ) rect_bg = circle_bg.mark_rect().transform_filter( alt.datum["set_order"] % 2 == 1 ).encode( color=alt.value("#F7F7F7") ) circle = circle_bg.transform_filter( alt.datum["is_intersect"] == 1 ).encode( color=alt.value(main_color) ) line_connection = vertical_bar.mark_bar(size=line_connection_size, color=main_color).transform_filter( alt.datum["is_intersect"] == 1 ).encode( y=alt.Y("min(set_order):N"), y2=alt.Y2("max(set_order):N") ) matrix_view = (rect_bg + circle_bg + line_connection + circle) # Cardinality by sets (horizontal bar chart) horizontal_bar_label_bg = base.mark_circle(size=set_label_bg_size).encode( y=alt.Y( "set_order:N", axis=alt.Axis(grid=False, labels=False, ticks=False, domain=False), title=None, ), color=alt.Color( "set:N", scale=alt.Scale(domain=sets, range=color_range), title=None ), opacity=alt.value(1) ) horizontal_bar_label = horizontal_bar_label_bg.mark_text().encode( text=alt.Text("set_abbre:N"), color=alt.value("white") ) horizontal_bar = horizontal_bar_label_bg.mark_bar( size=horizontal_bar_size ).transform_filter( alt.datum["is_intersect"] == 1 ).encode( x=alt.X( "sum(count):Q", axis=alt.Axis(grid=False, tickCount=3), title="Set Size" ) ).properties( width=horizontal_bar_chart_width ) # Concat Plots upsetaltair = alt.vconcat( vertical_bar_chart, alt.hconcat( matrix_view, (horizontal_bar_label_bg + horizontal_bar_label), horizontal_bar, # horizontal bar chart spacing=5 ).resolve_scale( y="shared" ), spacing=20 ).add_selection( legend_selection ) # Apply top-level configuration upsetaltair = upsetaltair_top_level_configuration( upsetaltair, legend_orient="top", legend_symbol_size=set_label_bg_size / 2.0 ).properties( title="Symptoms reported by users of the COVID Symptom Tracker app" ) return upsetaltair # ## Examples w/ Different Options UpSetAltair( data=df.copy(), sets=["Shortness of Breath", "Diarrhea", "Fever", "Cough", "Anosmia", "Fatigue"], abbre=["B", "D", "Fe", "C", "A", "Fa"], sort_by="Frequency", sort_order="ascending" ) UpSetAltair( data=df.copy(), sets=["Shortness of Breath", "Diarrhea", "Fever", "Cough", "Anosmia", "Fatigue"], abbre=["B", "D", "Fe", "C", "A", "Fa"], sort_by="Degree", sort_order="ascending" ) UpSetAltair( data=df.copy(), sets=["Shortness of Breath", "Diarrhea", "Fever", "Cough", "Anosmia", "Fatigue"], abbre=["B", "D", "Fe", "C", "A", "Fa"], sort_by="Frequency", sort_order="ascending", width=1200, height=500, height_ratio=0.6, horizontal_bar_chart_width=300 )
notebooks/1.0.10_upset_altair.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 # --- # + #Tuple # - animal = ('dog','cat','monkey') animal animal[1] # + #nesting in tuples # - tuple1 = ((10,2.3),(3.5,4)) tuple1 tuple1[0] tuple1[0][0] # + #immutable # - tuple1.sort() del tuple1[1]
tuples.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- import numpy as np import pandas as pd from pandas import Series,DataFrame np.random.seed(12345) # + df = DataFrame(np.random.randn(1000,4)) df.head() # - df.tail() df.describe() col1 = df[0] col1.head() col1[np.abs(col1)>3] df[(np.abs(df)>3).any(1)] df[np.abs(df)>3] = np.sign(df) * 3 df.describe()
python/udemy-data-analysis-and-visualization/lecture40_data_outliers.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 # --- from theano.sandbox import cuda # %matplotlib inline import utils; reload(utils) from utils import * from __future__ import division, print_function #path = "data/ml-20m/" path = "data/ml-latest-small/" model_path = path + 'models/' if not os.path.exists(model_path): os.mkdir(model_path) batch_size=64 # ## Set up data # We're working with the movielens data, which contains one rating per row, like this: ratings = pd.read_csv(path+'ratings.csv') ratings.head() len(ratings) # Just for display purposes, let's read in the movie names too. movie_names = pd.read_csv(path+'movies.csv').set_index('movieId')['title'].to_dict() users = ratings.userId.unique() movies = ratings.movieId.unique() userid2idx = {o:i for i,o in enumerate(users)} movieid2idx = {o:i for i,o in enumerate(movies)} # We update the movie and user ids so that they are contiguous integers, which we want when using embeddings. ratings.movieId = ratings.movieId.apply(lambda x: movieid2idx[x]) ratings.userId = ratings.userId.apply(lambda x: userid2idx[x]) user_min, user_max, movie_min, movie_max = (ratings.userId.min(), ratings.userId.max(), ratings.movieId.min(), ratings.movieId.max()) user_min, user_max, movie_min, movie_max n_users = ratings.userId.nunique() n_movies = ratings.movieId.nunique() n_users, n_movies # This is the number of latent factors in each embedding. n_factors = 50 np.random.seed = 42 # Randomly split into training and validation. msk = np.random.rand(len(ratings)) < 0.8 trn = ratings[msk] val = ratings[~msk] # ## Create subset for Excel # We create a crosstab of the most popular movies and most movie-addicted users which we'll copy into Excel for creating a simple example. This isn't necessary for any of the modeling below however. g=ratings.groupby('userId')['rating'].count() topUsers=g.sort_values(ascending=False)[:15] g=ratings.groupby('movieId')['rating'].count() topMovies=g.sort_values(ascending=False)[:15] top_r = ratings.join(topUsers, rsuffix='_r', how='inner', on='userId') top_r = top_r.join(topMovies, rsuffix='_r', how='inner', on='movieId') pd.crosstab(top_r.userId, top_r.movieId, top_r.rating, aggfunc=np.sum) # ## Dot product # The most basic model is a dot product of a movie embedding and a user embedding. Let's see how well that works: user_in = Input(shape=(1,), dtype='int64', name='user_in') u = Embedding(n_users, n_factors, input_length=1, W_regularizer=l2(1e-4))(user_in) movie_in = Input(shape=(1,), dtype='int64', name='movie_in') m = Embedding(n_movies, n_factors, input_length=1, W_regularizer=l2(1e-4))(movie_in) x = merge([u, m], mode='dot') x = Flatten()(x) model = Model([user_in, movie_in], x) model.compile(Adam(0.001), loss='mse') model.summary() model.fit([trn.userId, trn.movieId], trn.rating, batch_size=64, nb_epoch=1, verbose=2, validation_data=([val.userId, val.movieId], val.rating)) model.optimizer.lr=0.01 model.fit([trn.userId, trn.movieId], trn.rating, batch_size=64, nb_epoch=3, verbose=2, validation_data=([val.userId, val.movieId], val.rating)) model.optimizer.lr=0.001 model.fit([trn.userId, trn.movieId], trn.rating, batch_size=64, nb_epoch=6,verbose=2, validation_data=([val.userId, val.movieId], val.rating)) # The [best benchmarks](http://www.librec.net/example.html) are a bit over 0.9, so this model doesn't seem to be working that well... # + [markdown] heading_collapsed=true # ## Bias # + [markdown] hidden=true # The problem is likely to be that we don't have bias terms - that is, a single bias for each user and each movie representing how positive or negative each user is, and how good each movie is. We can add that easily by simply creating an embedding with one output for each movie and each user, and adding it to our output. # + hidden=true def embedding_input(name, n_in, n_out, reg): inp = Input(shape=(1,), dtype='int64', name=name) return inp, Embedding(n_in, n_out, input_length=1, W_regularizer=l2(reg))(inp) # + hidden=true user_in, u = embedding_input('user_in', n_users, n_factors, 1e-4) movie_in, m = embedding_input('movie_in', n_movies, n_factors, 1e-4) # + hidden=true def create_bias(inp, n_in): x = Embedding(n_in, 1, input_length=1)(inp) return Flatten()(x) # + hidden=true ub = create_bias(user_in, n_users) mb = create_bias(movie_in, n_movies) # + hidden=true x = merge([u, m], mode='dot') x = Flatten()(x) x = merge([x, ub], mode='sum') x = merge([x, mb], mode='sum') model = Model([user_in, movie_in], x) model.compile(Adam(0.001), loss='mse') # + hidden=true model.fit([trn.userId, trn.movieId], trn.rating, batch_size=64, nb_epoch=1, verbose=2, validation_data=([val.userId, val.movieId], val.rating)) # + hidden=true model.optimizer.lr=0.01 # + hidden=true model.fit([trn.userId, trn.movieId], trn.rating, batch_size=64, nb_epoch=6, verbose=2, validation_data=([val.userId, val.movieId], val.rating)) # + hidden=true model.optimizer.lr=0.001 # + hidden=true model.fit([trn.userId, trn.movieId], trn.rating, batch_size=64, nb_epoch=10, verbose=2, validation_data=([val.userId, val.movieId], val.rating)) # + hidden=true model.fit([trn.userId, trn.movieId], trn.rating, batch_size=64, nb_epoch=5, verbose=2, validation_data=([val.userId, val.movieId], val.rating)) # + [markdown] hidden=true # This result is quite a bit better than the best benchmarks that we could find with a quick google search - so looks like a great approach! # + hidden=true model.save_weights(model_path+'bias.h5') # + hidden=true model.load_weights(model_path+'bias.h5') # + [markdown] hidden=true # We can use the model to generate predictions by passing a pair of ints - a user id and a movie id. For instance, this predicts that user #3 would really enjoy movie #6. # + hidden=true model.predict([np.array([3]), np.array([6])]) # + [markdown] heading_collapsed=true # ## Analyze results # + [markdown] hidden=true # To make the analysis of the factors more interesting, we'll restrict it to the top 2000 most popular movies. # + hidden=true g=ratings.groupby('movieId')['rating'].count() topMovies=g.sort_values(ascending=False)[:2000] topMovies = np.array(topMovies.index) # + [markdown] hidden=true # First, we'll look at the movie bias term. We create a 'model' - which in keras is simply a way of associating one or more inputs with one more more outputs, using the functional API. Here, our input is the movie id (a single id), and the output is the movie bias (a single float). # + hidden=true get_movie_bias = Model(movie_in, mb) movie_bias = get_movie_bias.predict(topMovies) movie_ratings = [(b[0], movie_names[movies[i]]) for i,b in zip(topMovies,movie_bias)] # + [markdown] hidden=true # Now we can look at the top and bottom rated movies. These ratings are corrected for different levels of reviewer sentiment, as well as different types of movies that different reviewers watch. # + hidden=true sorted(movie_ratings, key=itemgetter(0))[:15] # + hidden=true sorted(movie_ratings, key=itemgetter(0), reverse=True)[:15] # + [markdown] hidden=true # We can now do the same thing for the embeddings. # + hidden=true get_movie_emb = Model(movie_in, m) movie_emb = np.squeeze(get_movie_emb.predict([topMovies])) movie_emb.shape # + [markdown] hidden=true # Because it's hard to interpret 50 embeddings, we use [PCA](https://plot.ly/ipython-notebooks/principal-component-analysis/) to simplify them down to just 3 vectors. # + hidden=true from sklearn.decomposition import PCA pca = PCA(n_components=3) movie_pca = pca.fit(movie_emb.T).components_ # + hidden=true fac0 = movie_pca[0] # + hidden=true movie_comp = [(f, movie_names[movies[i]]) for f,i in zip(fac0, topMovies)] # + [markdown] hidden=true # Here's the 1st component. It seems to be 'critically acclaimed' or 'classic'. # + hidden=true sorted(movie_comp, key=itemgetter(0), reverse=True)[:10] # + hidden=true sorted(movie_comp, key=itemgetter(0))[:10] # + hidden=true fac1 = movie_pca[1] # + hidden=true movie_comp = [(f, movie_names[movies[i]]) for f,i in zip(fac1, topMovies)] # + [markdown] hidden=true # The 2nd is 'hollywood blockbuster'. # + hidden=true sorted(movie_comp, key=itemgetter(0), reverse=True)[:10] # + hidden=true sorted(movie_comp, key=itemgetter(0))[:10] # + hidden=true fac2 = movie_pca[2] # + hidden=true movie_comp = [(f, movie_names[movies[i]]) for f,i in zip(fac2, topMovies)] # + [markdown] hidden=true # The 3rd is 'violent vs happy'. # + hidden=true sorted(movie_comp, key=itemgetter(0), reverse=True)[:10] # + hidden=true sorted(movie_comp, key=itemgetter(0))[:10] # + [markdown] hidden=true # We can draw a picture to see how various movies appear on the map of these components. This picture shows the 1st and 3rd components. # + hidden=true import sys stdout, stderr = sys.stdout, sys.stderr # save notebook stdout and stderr reload(sys) sys.setdefaultencoding('utf-8') sys.stdout, sys.stderr = stdout, stderr # restore notebook stdout and stderr # + hidden=true start=50; end=100 X = fac0[start:end] Y = fac2[start:end] plt.figure(figsize=(15,15)) plt.scatter(X, Y) for i, x, y in zip(topMovies[start:end], X, Y): plt.text(x,y,movie_names[movies[i]], color=np.random.rand(3)*0.7, fontsize=14) plt.show() # - # ## Neural net # Rather than creating a special purpose architecture (like our dot-product with bias earlier), it's often both easier and more accurate to use a standard neural network. Let's try it! Here, we simply concatenate the user and movie embeddings into a single vector, which we feed into the neural net. user_in, u = embedding_input('user_in', n_users, n_factors, 1e-4) movie_in, m = embedding_input('movie_in', n_movies, n_factors, 1e-4) x = merge([u, m], mode='concat') x = Flatten()(x) x = Dropout(0.3)(x) x = Dense(70, activation='relu')(x) x = Dropout(0.75)(x) x = Dense(1)(x) nn = Model([user_in, movie_in], x) nn.compile(Adam(0.001), loss='mse') nn.fit([trn.userId, trn.movieId], trn.rating, batch_size=64, nb_epoch=8, verbose=2, validation_data=([val.userId, val.movieId], val.rating)) # This improves on our already impressive accuracy even further!
deeplearning1/nbs-custom-mine/lesson4_03.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from pyspark.sql import SparkSession from pyspark.sql import Row import collections spark = SparkSession.builder.appName("DF-Ops").getOrCreate() # # Find total count of movie ratings from pyspark.sql.types import StringType, DoubleType, IntegerType, StructType, StructField schema = StructType([StructField('userId', IntegerType(), True), StructField('movieId', IntegerType(), True), StructField('rating', IntegerType(), True), StructField('timestamp', DoubleType(), True)]) data = spark.read.csv('resources/u.data',sep = '\t', header = False, schema = schema) data.printSchema() data.head(3) data.columns data.describe().show() data.groupBy('rating').count().orderBy('rating').show() # # Find average number of friends by age # Load data friendData = spark.read.csv("resources/fakefriends-header.csv", header = True, inferSchema = True) friendData.printSchema() friendData.show(3) from pyspark.sql import functions as f friendData.select('age','friends').groupBy('age').agg(f.round(f.avg('friends'),2).alias('AveFriends')).show() # # Find min and max temperature in a year from pyspark.sql.types import StringType, DoubleType, IntegerType, StructType, StructField schema = StructType([StructField('stationId', StringType(), True), StructField('date', IntegerType(), True), StructField('entryType', StringType(), True), StructField('temperature', DoubleType(), True), StructField('column1', StringType(), True), StructField('column2', StringType(), True), StructField('column3', StringType(), True)]) data = spark.read.csv("resources/1800.csv",header = False,schema=schema) data.printSchema() data.show(3) modifiedData = data.select('stationId','entryType','temperature')\ .withColumn('FTemperature',f.round((data.temperature * 0.1 * (9.0/5.0) + 32.0),2)) modifiedData.show(3) modifiedData.filter(data.entryType=='TMIN').groupBy('stationId').min('FTemperature').show() modifiedData.filter(data.entryType=='TMAX').groupBy('stationId').max('FTemperature')\ .select('stationId',f.col('max(FTemperature)').alias('Max_Temp')).show() # # Count number of word occurrence inputDF = spark.read.text("resources/book.txt") words = inputDF.select(f.explode(f.split(inputDF.value,"\\W+")).alias('word')) words.show(3) words.filter(words.word !='') lowerCaseWords = words.select(f.lower(words.word).alias('word')) lowerCaseWords.show(3) wordCounts = lowerCaseWords.groupBy('word').count() wordCounts.show(3) wordCountsSorted = wordCounts.sort('count', ascending=False) wordCountsSorted.show(3) wordCountsSorted.show(wordCountsSorted.count()) # To show all results # # Find the Total Amount Spent by Customer schema = StructType([StructField('custId', IntegerType(), True), StructField('itemId', IntegerType(), True), StructField('cost', DoubleType(), True)]) data = spark.read.csv("resources/customer-orders.csv",header = False, schema = schema) data.printSchema() data.show(3) data.groupBy('custId').sum('cost').orderBy('custId').show(data.count()) spark.stop()
1. Spark DataFrame(DF) Operations.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import sys sys.path.append("../src") # %load_ext autoreload # + # %autoreload 2 import sys import numpy as np from PIL import Image import torch import torch.nn as nn import torch.nn.functional as F from torchvision import transforms, datasets from torchvision.datasets import FashionMNIST import matplotlib.pyplot as plt from pytorch_impl.nns import FCN from pytorch_impl.nns.utils import warm_up_batch_norm, to_one_hot from pytorch_impl.estimators import MatrixExpEstimator, GradientBoostingEstimator from pytorch_impl import ClassifierTraining from pytorch_impl.matrix_exp import matrix_exp, compute_exp_term # + torch.manual_seed(0) num_classes = 10 if torch.cuda.is_available() and False: device = torch.device('cuda:0') else: device = torch.device('cpu') print('Torch version: {}'.format(torch.__version__)) print('Device: {}'.format(device)) train_loader = torch.utils.data.DataLoader( FashionMNIST(root='.', train=True, download=True, transform=transforms.ToTensor()), batch_size=32, shuffle=True, pin_memory=True) test_loader = torch.utils.data.DataLoader( FashionMNIST(root='.', train=False, transform=transforms.ToTensor()), batch_size=32, shuffle=True, pin_memory=True) device # - a = 30 / 180 * np.pi M = torch.tensor([[0, -1], [1, 0]]) * a matrix_exp(M, device).cpu().numpy() a = 30 / 180 * np.pi M = torch.tensor([[0, -1], [1, 0]]) * a M_clone = M.clone().to(device) (torch.matmul(M_clone, compute_exp_term(M, device)) + torch.eye(2)).numpy() # + D = 28 model = FCN(10, D * D).to(device) # + base_estimator = MatrixExpEstimator(model, num_classes, device, learning_rate=1., aug_grad=True) _, (X, y) = next(enumerate(train_loader)) base_estimator.fit_batch(X, y) gb_estimator = GradientBoostingEstimator(base_estimator, num_classes, nn.CrossEntropyLoss(), device) # + n_iter = 100 for batch_id in range(100): _, (X, y) = next(enumerate(train_loader)) X, y = X.to(device), y.to(device) if batch_id % (n_iter // 10) == 0: gb_estimator.step() print(gb_estimator.predict(X)[:5]) gb_estimator.fit_batch(X, y) print() print() # -
notebooks/2020/matrix-exp-training.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="zX4Kg8DUTKWO" colab_type="code" colab={} #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # + [markdown] colab_type="text" id="UncprnB0ymAE" # Below is code with a link to a happy or sad dataset which contains 80 images, 40 happy and 40 sad. # Create a convolutional neural network that trains to 100% accuracy on these images, which cancels training upon hitting training accuracy of >.999 # # Hint -- it will work best with 3 convolutional layers. # + colab_type="code" id="7Vti6p3PxmpS" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="cd06e9f3-cbd7-4f3b-f69e-c82617583231" import tensorflow as tf import os import zipfile DESIRED_ACCURACY = 0.999 # !wget --no-check-certificate \ # "https://storage.googleapis.com/laurencemoroney-blog.appspot.com/happy-or-sad.zip" \ # -O "/tmp/happy-or-sad.zip" zip_ref = zipfile.ZipFile("/tmp/happy-or-sad.zip", 'r') zip_ref.extractall("/tmp/h-or-s") zip_ref.close() class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('accuracy')>=0.999): print("\nReached 99.8% accuracy so cancelling training!") self.model.stop_training = True callbacks = myCallback() # + colab_type="code" id="6DLGbXXI1j_V" colab={} # This Code Block should Define and Compile the Model model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150,150,3)), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(32, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(64, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid') ]) from tensorflow.keras.optimizers import RMSprop model.compile(loss='binary_crossentropy', optimizer= RMSprop(lr=0.001), metrics=["accuracy"]) # + colab_type="code" id="4Ap9fUJE1vVu" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="aca33735-84c2-42fe-f691-b8e40d0ba78a" # This code block should create an instance of an ImageDataGenerator called train_datagen # And a train_generator by calling train_datagen.flow_from_directory from tensorflow.keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale=1/255) train_generator = train_datagen.flow_from_directory( '/tmp/h-or-s/', target_size=(150,150), batch_size=10, class_mode='binary' ) # Expected output: 'Found 80 images belonging to 2 classes' # + colab_type="code" id="48dLm13U1-Le" colab={"base_uri": "https://localhost:8080/", "height": 221} outputId="3d1fb366-3042-442e-fb5b-7dedda4d1ca5" # This code block should call model.fit and train for # a number of epochs. history = model.fit( train_generator, steps_per_epoch=8, epochs=15, callbacks=[callbacks], verbose=1 ) # Expected output: "Reached 99.9% accuracy so cancelling training!""
1.Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning/Week-4/Exercise_4_Question.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernel_info: # name: u4-s3-dnn # kernelspec: # display_name: u4_s2 # language: python # name: u4_s2 # --- # + [markdown] id="aVFJkgJ3l-fA" colab_type="text" # <img align="left" src="https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png" width=200> # <br></br> # <br></br> # # # Major Neural Network Architectures Challenge # ## *Data Science Unit 4 Sprint 3 Challenge* # # In this sprint challenge, you'll explore some of the cutting edge of Data Science. This week we studied several famous neural network architectures: # recurrent neural networks (RNNs), long short-term memory (LSTMs), convolutional neural networks (CNNs), and Generative Adverserial Networks (GANs). In this sprint challenge, you will revisit these models. Remember, we are testing your knowledge of these architectures not your ability to fit a model with high accuracy. # # __*Caution:*__ these approaches can be pretty heavy computationally. All problems were designed so that you should be able to achieve results within at most 5-10 minutes of runtime on Colab or a comparable environment. If something is running longer, doublecheck your approach! # # ## Challenge Objectives # *You should be able to:* # * <a href="#p1">Part 1</a>: Train a RNN classification model # * <a href="#p2">Part 2</a>: Utilize a pre-trained CNN for objective detection # * <a href="#p3">Part 3</a>: Describe the components of an autoencoder # * <a href="#p4">Part 4</a>: Describe yourself as a Data Science and elucidate your vision of AI # + [markdown] colab_type="text" id="-5UwGRnJOmD4" # <a id="p1"></a> # ## Part 1 - RNNs # # Use an RNN/LSTM to fit a multi-class classification model on reuters news articles to distinguish topics of articles. The data is already encoded properly for use in an RNN model. # # Your Tasks: # - Use Keras to fit a predictive model, classifying news articles into topics. # - Report your overall score and accuracy # # For reference, the [Keras IMDB sentiment classification example](https://github.com/keras-team/keras/blob/master/examples/imdb_lstm.py) will be useful, as well the RNN code we used in class. # # __*Note:*__ Focus on getting a running model, not on maxing accuracy with extreme data size or epoch numbers. Only revisit and push accuracy if you get everything else done! # + colab_type="code" id="DS-9ksWjoJit" colab={} from tensorflow.keras.datasets import reuters (X_train, y_train), (X_test, y_test) = reuters.load_data(num_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=723812, start_char=1, oov_char=2, index_from=3) # + colab_type="code" id="fLKqFh8DovaN" outputId="7ee136de-6f08-4ba4-a5b1-331d05fe054c" colab={"base_uri": "https://localhost:8080/", "height": 102} # Demo of encoding word_index = reuters.get_word_index(path="reuters_word_index.json") print(f"Iran is encoded as {word_index['iran']} in the data") print(f"London is encoded as {word_index['london']} in the data") print("Words are encoded as numbers in our dataset.") # + colab_type="code" id="_QVSlFEAqWJM" colab={"base_uri": "https://localhost:8080/", "height": 241} outputId="e6671bd4-552a-49b9-c2c3-2179c479cba1" from tensorflow.keras.preprocessing import sequence from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Embedding, LSTM batch_size = 46 max_features = len(word_index.values()) maxlen = 200 print(len(X_train), 'train sequences') print(len(X_test), 'test sequences') print('Pad sequences (samples x time)') X_train = sequence.pad_sequences(X_train, maxlen=maxlen) X_test = sequence.pad_sequences(X_test, maxlen=maxlen) print('X_train shape:', X_train.shape) print('X_test shape:', X_test.shape) print('Build model...') model = Sequential() model.add(Embedding(max_features, 128)) model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2)) model.add(Dense(1, activation='sigmoid')) # + id="xuTOoWXHl-fq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 190} outputId="e43fccf5-8865-4f6c-fbae-df9444792e17" # You should only run this cell once your model has been properly configured model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) print('Train...') model.fit(X_train, y_train, batch_size=batch_size, epochs=1, validation_data=(X_test, y_test)) score, acc = model.evaluate(X_test, y_test, batch_size=batch_size) print('Test score:', score) print('Test accuracy:', acc) # + [markdown] id="QWfLRfYPl-fu" colab_type="text" # ## Sequence Data Question # #### *Describe the `pad_sequences` method used on the training dataset. What does it do? Why do you need it?* # # `The pad_sequence method ensures that all sequences in a list of sequences have the same length as the longest sequence. This method is needed when batching sequences in a model so the model gets the same length of sequence every time.` # # ## RNNs versus LSTMs # #### *What are the primary motivations behind using Long-ShortTerm Memory Cell unit over traditional Recurrent Neural Networks?* # # `LSTMs are a special type of RNN. A standard RNN suffers from the vanishing gradient problem where the gradient of the loss function decays exponentially with time. LSTMs solve this with a memory cell that can maintain information in memory for long periods of time. A set of gates is used to control when information enters the memory, when it's output, and when it's forgotten.` # # ## RNN / LSTM Use Cases # #### *Name and Describe 3 Use Cases of LSTMs or RNNs and why they are suited to that use case* # # `RNNs are used to work with sequence prediction problems. RNNs are best suited for the following: text data, speech data, classification prediction problems, regression predicition problems, and generative models. RNNs should not be used for tabular data or image data.` # + id="wZoLVxCsl-fv" colab_type="code" colab={} # + [markdown] colab_type="text" id="yz0LCZd_O4IG" # <a id="p2"></a> # ## Part 2- CNNs # # ### Find the Frog # # Time to play "find the frog!" Use Keras and ResNet50 (pre-trained) to detect which of the following images contain frogs: # # <img align="left" src="https://d3i6fh83elv35t.cloudfront.net/newshour/app/uploads/2017/03/GettyImages-654745934-1024x687.jpg" width=400> # # + colab_type="code" id="whIqEWR236Af" outputId="fb1047b8-3a78-41ba-ca1e-671a68f256e2" colab={"base_uri": "https://localhost:8080/", "height": 258} # !pip install google_images_download # + colab_type="code" id="EKnnnM8k38sN" outputId="3a4ce0a2-2523-4206-efce-466803524e79" colab={"base_uri": "https://localhost:8080/", "height": 272} from google_images_download import google_images_download response = google_images_download.googleimagesdownload() arguments = {"keywords": "animal pond", "limit": 4, "print_urls": True} absolute_image_paths = response.download(arguments) # + [markdown] colab_type="text" id="si5YfNqS50QU" # At time of writing at least a few do, but since the Internet changes - it is possible your 5 won't. You can easily verify yourself, and (once you have working code) increase the number of images you pull to be more sure of getting a frog. Your goal is to validly run ResNet50 on the input images - don't worry about tuning or improving the model. # # *Hint* - ResNet 50 doesn't just return "frog". The three labels it has for frogs are: `bullfrog, tree frog, tailed frog` # # *Stretch goal* - also check for fish. # + colab_type="code" id="FaT07ddW3nHz" colab={} # You've got something to do in this cell. ;) import numpy as np from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions def process_img_path(img_path): return image.load_img(img_path, target_size=(224, 224)) def img_contains_frog(img): """ Scans image for Frogs Should return a integer with the number of frogs detected in an image. Inputs: --------- img: Precrossed image ready for prediction. The `process_img_path` function should already be applied to the image. Returns: --------- frogs (boolean): TRUE or FALSE - There are frogs in the image. """ # Instantiate ResNet50 model resnet = ResNet50(weights='imagenet') # Create predictions pred = resnet.predict(img) # Decode the predictions to return string value result = decode_predictions(pred, top=5)[0] frog_count = list(sum(result, ())) frog_count = [str(i) for i in frog_count] frogs = (' '.join(frog_count)).count('frog') return frogs # + [markdown] id="WAFZQ9tel-gA" colab_type="text" # #### Displaying Predictions # The next two cells are just to display some of your predictions. You will not be graded on their output. # + id="OWp-o3I8l-gB" colab_type="code" colab={} import matplotlib.pyplot as plt def display_predictions(urls): image_data = [] frogs = [] for url in urls: x = process_img_path(url) x = image.img_to_array(x) x = np.expand_dims(x, axis=0) x = preprocess_input(x) image_data.append(x) frogs.append(img_contains_frog(x)) return image_data,frogs # + id="6p6hHEi5l-gE" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 349} outputId="05b6cd13-8f23-44d9-a581-be91f9e237ce" f, axarr = plt.subplots(2,2) imgs, frogs = display_predictions(absolute_image_paths[0]['animal pond']) for x,y in [(0,0),(0,1), (1,0), (1,1)]: axarr[x,y].imshow(np.squeeze(imgs[x], axis=0) / 255) axarr[x,y].set_title(f"Frog: {frogs[x]}") axarr[x,y].axis('off') # + [markdown] colab_type="text" id="XEuhvSu7O5Rf" # <a id="p3"></a> # ## Part 3 - Autoencoders # # Describe a use case for an autoencoder given that an autoencoder tries to predict its own input. # # `Autoencoders are used in image denoising. This is seen when using the mnist dataset where the images of numbers become more clear as the model improves.` # + [markdown] colab_type="text" id="626zYgjkO7Vq" # <a id="p4"></a> # ## Part 4 - More... # + [markdown] colab_type="text" id="__lDWfcUO8oo" # Answer the following questions, with a target audience of a fellow Data Scientist: # # - **What do you consider your strongest area, as a Data Scientist?** # - `My strongest area is supervised learning with tabular data.` # <br> # - **What area of Data Science would you most like to learn more about, and why?** # - `I would like to learn more about NLP because I'm intrigued by the possibilities of making sense out of the vast amounts of text data available to find actionable insights for business purposes.` # <br> # - **Where do you think Data Science will be in 5 years?** # - `I'm not sure. Data Science is such a broad term that encompasses so many fields. I think in 5 years it will be common place for most companies to use data science in some capacity, either in their decision making or as part of their products/services. I think there will be a huge demand for NLP skills since there's so much text data available.` # <br> # - **What are the threats posed by AI to our society?** # - `AI poses two big threats to society. First, the use of AI for military purposes is troubling. One miscalculation or malfunction could have horrible consequences. I also believe that the more we reduce the risk/cost of war, the more we will diminish the importance of diplomacy. The second threat is unemployment due to automation. Automation has already impacted the auto industry, and now truck drivers and customer service representatives are at risk of having their jobs automated away too.` # <br> # - **How do you think we can counteract those threats?** # - `To counteract the military threat, we should have an international treaty detailing how and when countries can use AI. To counteract the threat to employment, we need a big push towards retraining workers for jobs that are not easily automated, such as electircians or plummers. We also need to consider the economic impact of mass unemployment. The economy will stall with too much unemployment because there won't be enough cash recirculating.` # <br> # - **Do you think achieving General Artifical Intelligence is ever possible?** # - `I don't think GAI is possible in the sci-fi sense of the term. I think there's more to being human than just knowledge, we have emotions and intentions, which are not things that can be learned. We will never see "self-aware" AI. However, I do see a future with a greater reliance on AI, but I think most people confuse fiction with reality when discussing GAI. There will also need to be massive advances in transfer learning to get anywhere close to GAI. GAI would require the AI to be able to apply learned knowledge to different but related tasks.` # # A few sentences per answer is fine - only elaborate if time allows. # + [markdown] colab_type="text" id="_Hoqe3mM_Mtc" # ## Congratulations! # # Thank you for your hard work, and congratulations! You've learned a lot, and you should proudly call yourself a Data Scientist. # # + id="1bXQwNL1l-gP" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 320} outputId="2c891ad0-0ebc-4912-b2c1-65f415b76edf" from IPython.display import HTML HTML("""<iframe src="https://giphy.com/embed/26xivLqkv86uJzqWk" width="480" height="270" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="https://giphy.com/gifs/mumm-champagne-saber-26xivLqkv86uJzqWk">via GIPHY</a></p>""")
SC/LS_DS_Uni_4_Sprint_3_Challenge.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Exercise: CBS Innovation import requests from bs4 import BeautifulSoup import time # - Get CBS innovation page using requests and parse result using BeautifulSoup # - Retrieve a list of titles of all innovation articles on this page using a CSS selector and print them # - For each innovation article page retrieve the first 500 characters of the text and print it # First create your code for one article # Then loop through all articles # - Option: retrieve all urls to images in all innovation articles and show them
20200907/CBS_Innovation.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 matplotlib.pyplot as plt from scipy import stats # %precision 3 # %matplotlib inline # + from scipy import integrate import warnings # 積分に関する warining を出力しないようにする warnings.filterwarnings('ignore', category=integrate.IntegrationWarning) # - # 確率変数の取りうる値を定義 x_range = np.array([0, 1]) x_range # 確率密度関数の定義 def f(x): if x_range[0] <= x <= x_range[1]: return 2 * x else: return 0 # 確率変数の定義 X = [x_range, f] # + # 確率密度関数を描画する xs = np.linspace(x_range[0], x_range[1], 100) fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) ax.plot(xs, [f(x) for x in xs], label='f(x)', color='gray') ax.hlines(0, -0.2, 1.2, alpha=0.3) ax.vlines(0, -0.2, 2.2, alpha=0.3) ax.vlines(xs.max(), 0, 2.2, linestyles=':', color='gray') xs = np.linspace(0.4, 0.6, 100) ax.fill_between(xs, [f(x) for x in xs], label='prob') ax.set_xticks(np.arange(-0.2, 1.3, 0.1)) ax.set_xlim(-0.1, 1.1) ax.set_ylim(-0.2, 2.1) ax.legend() plt.show() # - # 積分値 integrate.quad(f, 0.4, 0.6) # + # 確率密度関数の最小値を確認 from scipy.optimize import minimize_scalar res = minimize_scalar(f) res.fun # - # 確率密度関数の積分値が1であることを確認 integrate.quad(f, -np.inf, np.inf)[0] # 累積分布関数 def F(x): return integrate.quad(f, -np.inf, x)[0] # いかさまルーレットが0.4から0.6の間を取る確率 F(0.6) - F(0.4) # + # 累積分布関数を描画する xs = np.linspace(x_range[0], x_range[1], 100) fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) ax.plot(xs, [F(x) for x in xs], label='F(x)', color='gray') ax.hlines(0, -0.1, 1.1, alpha=0.3) ax.vlines(0, -0.1, 1.1, alpha=0.3) ax.vlines(xs.max(), 0, 1, linestyles=':', color='gray') ax.set_xticks(np.arange(-0.1, 1.2, 0.1)) ax.set_xlim(-0.1, 1.1) ax.set_ylim(-0.1, 1.1) ax.legend() plt.show() # + # 確率変数の変換(2X+3) y_range = [3, 5] # 確率密度関数 def g(y): if y_range[0] <= y <= y_range[1]: return (y - 3) / 2 else: return 0 # 累積分布関数 def G(y): return integrate.quad(g, -np.inf, y)[0] # + # 確率密度関数と累積分布関数を描画 ys = np.linspace(y_range[0], y_range[1], 100) fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) ax.plot(ys, [g(y) for y in ys], label='g(y)', color='gray') ax.plot(ys, [G(y) for y in ys], label='G(y)', ls='--', color='gray') ax.hlines(0, 2.8, 5.2, alpha=0.3) ax.vlines(ys.max(), 0, 1, linestyles=':', color='gray') ax.set_xticks(np.arange(2.8, 5.2, 0.2)) ax.set_xlim(2.8, 5.2) ax.set_ylim(-0.1, 1.1) ax.legend() plt.show() # + # 期待値 def integrand(x): return x * f(x) # いかさまルーレットの期待値 integrate.quad(integrand, -np.inf, np.inf)[0] # - def E(X, g=lambda x : x): x_range, f = X def integrand(x): return g(x) * f(x) return integrate.quad(integrand, -np.inf, np.inf)[0] E(X) E(X, g=lambda x: 2 * x + 3) # E(2X+3) = 2E(X) + 3 2 * E(X) + 3 # + # 分散 mean = E(X) def integrand(x): return (x - mean) ** 2 * f(x) # いかさまルーレットの分散 integrate.quad(integrand, -np.inf, np.inf)[0] # - def V(X, g=lambda x: x): x_range, f = X mean = E(X, g) def integrand(x): return (g(x) - mean) ** 2 * f(x) return integrate.quad(integrand, -np.inf, np.inf)[0] V(X) V(X, lambda x: 2 * x + 3) # V(2X+3) = 4V(X) 2 ** 2 * V(X) # + # 2次元の連続型確率変数 # 確率変数XとYのとりうる値 x_range = [0, 2] y_range = [0, 1] # 同時確率密度関数 def f_xy(x, y): if 0 <= y <= 1 and 0 <= x - y <= 1: return 4 * y * (x - y) else: return 0 XY = [x_range, y_range, f_xy] # + # 同時確立密度関数をヒートマップで描画 xs = np.linspace(x_range[0], x_range[1], 200) ys = np.linspace(y_range[0], y_range[1], 200) pd = np.array([[f_xy(x, y) for y in ys] for x in xs]) fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111) c = ax.pcolor(pd) ax.set_xticks(np.linspace(0, 200, 3), minor=False) ax.set_yticks(np.linspace(0, 200, 3), minor=False) ax.set_xticklabels(np.linspace(0, 2, 3)) ax.set_yticklabels(np.linspace(0, 1, 3)) ax.invert_yaxis() ax.xaxis.tick_top() fig.colorbar(c, ax=ax) plt.show() # - # 同時確立密度関数の多重積分値が1であることを確認 integrate.nquad(f_xy, [[-np.inf, np.inf], [-np.inf, np.inf]])[0] # + # 周辺確率密度関数 from functools import partial # Xの周辺確立密度関数 def f_X(x): return integrate.quad(partial(f_xy, x), -np.inf, np.inf)[0] # Yの周辺確立密度関数 def f_Y(y): return integrate.quad(partial(f_xy, y=y), -np.inf, np.inf)[0] # + # X, Yそれぞれの周辺確立密度関数を描画 xs = np.linspace(*x_range, 100) ys = np.linspace(*y_range, 100) fig = plt.figure(figsize=(12, 4)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.plot(xs, [f_X(x) for x in xs], color='gray') ax2.plot(ys, [f_Y(y) for y in ys], color='gray') ax1.set_title('Peripheral density function of X') ax2.set_title('Peripheral density function of Y') plt.show() # + # 期待値 def integrand(x, y): return x * f_xy(x, y) integrate.nquad(integrand, [[-np.inf, np.inf], [-np.inf, np.inf]])[0] # - def E(XY, g): x_range, y_range, f_xy = XY def integrand(x, y): return g(x, y) * f_xy(x, y) return integrate.nquad(integrand, [[-np.inf, np.inf], [-np.inf, np.inf]])[0] # Xの期待値 mean_X = E(XY, lambda x, y: x) mean_X # Yの期待値 mean_Y = E(XY, lambda x, y: y) mean_Y # 期待値の線形性の確認 a, b = 2, 3 E(XY, lambda x, y: a * x + b * y) a * mean_X + b * mean_Y # + # Xの分散 def integrand(x, y): return (x - mean_X) ** 2 * f_xy(x, y) integrate.nquad(integrand, [[-np.inf, np.inf], [-np.inf, np.inf]])[0] # - # XYの分散 def V(XY, g): x_range, y_range, f_xy = XY mean = E(XY, g) def integrand(x, y): return (g(x, y) - mean) ** 2 * f_xy(x, y) return integrate.nquad(integrand, [[-np.inf, np.inf], [-np.inf, np.inf]])[0] # Xの分散 var_X = V(XY, lambda x, y: x) var_X # Yの分散 var_Y = V(XY, lambda x, y: y) var_Y # 共分散 def Cov(XY): x_range, y_range, f_xy = XY mean_X = E(XY, lambda x, y: x) mean_Y = E(XY, lambda x, y: y) def integrand(x, y): return (x - mean_X) * (y - mean_Y) * f_xy(x, y) return integrate.nquad(integrand, [[-np.inf, np.inf], [-np.inf, np.inf]])[0] cov_xy = Cov(XY) cov_xy # V(aX+bY) = a^2V(X)+b^2V(Y)+2abCov(XYを確認する V(XY, lambda x, y: a * x + b * y) a ** 2 * var_X + b ** 2 * var_Y + 2 * a * b * cov_xy # 相関係数 cov_xy / np.sqrt(var_X * var_Y)
chapter07.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 ipyleaflet import ( Map, Marker, TileLayer, ImageOverlay, Polyline, Polygon, Rectangle, Circle, CircleMarker, GeoJSON, DrawControl, ) center = [34.6252978589571, -77.34580993652344] zoom = 10 m = Map(center=center, zoom=zoom) m
examples/MapContainer.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="uJDhTNdYJpU9" # # E05 - Backpropagation nos dados MNIST # # Neste exercício você irá implementar manualmente uma rede neural para o reconhecimento dos dígitos da base de dados MNIST. Esta base de dados consiste em imagens de dígitos manuscritos, contendo $60$ mil amostras para treinamento e $10$ mil amostras para teste. A imagem abaixo ilustra algumas dessas amostras. # # <center> # <img src="https://drive.google.com/uc?id=1ZLiPiJcC6ptyPDKt-lVni-2N53ROZ1ju" /> # </center> # # Para resolver este exercício, acompanhe passo a passo as etapas implementadas no código abaixo e siga as instruções ao final. # + id="7sXLurP3PYww" cellView="form" #@title # %%capture # !pip install git+https://github.com/grading/gradememaybe.git # !gdown --id '1EBcNjuNcnkFiPVSc89nfyFgW9iWgYLf1' # !gdown --id '1RBh0vbz2nKjwv9ua6RNNkFUKnXX1-nP2' # !gdown --id '1nV3_BjjeyO_4sacnceJemOHTBGGGnZZc' # !gdown --id '1u4EvdwDwE1j2hZZU4A2FIVV1DVVOCVwj' # !gdown --id '1hk8OJMXGVHbPooHovB3OBCIsK7m4dsV9' # !gdown --id '1kyUeMWw46rrlDwxqIVlX5bQb82xPdfHy' # !gdown --id '1A3g8vBh3u3MyO99Pm-KVvv_lcrKxDDlW' # !gdown --id '1WhiS-x3M6Am-st0TnSOqyB2_8QsP8wDH' # !gdown --id '1_FzSx9FGy4zaYzuyxILjFjF8tR8u3Kbe' # !gdown --id '1BC2wPJws86yumNfsBB80HApfk4k88TZa' from gofer import ok # + [markdown] id="OrgR4QVdZr0a" # ## Passo 1: Obtenção dos Dados # # Este código baixa os arquivos do [_dataset_ MNIST](https://en.wikipedia.org/wiki/MNIST_database) a partir do [site](http://yann.lecun.com/exdb/mnist/) do [Prof. <NAME>](https://en.wikipedia.org/wiki/Yann_LeCun). # + id="D1ysJPoDYhDm" colab={"base_uri": "https://localhost:8080/"} outputId="b5c911d4-5999-48ea-d43f-bff66113403f" # Imagens de treinamento # !wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz -O train-images-idx3-ubyte.gz # Rótulos (classes) # !wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz -O train-labels-idx1-ubyte.gz # Imagens de validação # !wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz -O t10k-images-idx3-ubyte.gz # Rótulos de validação (classes) # !wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz -O t10k-labels-idx1-ubyte.gz # + [markdown] id="h-9Bk13cH3Qp" # Abaixo extraímos os arquivos comprimidos. # + id="0Y07CnRjaJYU" # Extrai os arquivos treinamento # (esse comando demora um pouco) # !gunzip -f *.gz # + [markdown] id="X4O4zi5lf04t" # ## Passo 2: Leitura dos Dados # # Abaixo definimos as funções auxiliares para leitura do arquivo de imagens # + id="3-GlQ5rjbPwg" import numpy as np from struct import unpack def read_imgs(img_filename): ''' Esta função lê o arquivo de imagens da base de dados MNIST ''' # Abre o arquivo img_file = open(img_filename,'rb') # Lê o cabeçalho do arquivo magic = unpack('>i', img_file.read(4))[0] total = unpack('>i', img_file.read(4))[0] height = unpack('>i', img_file.read(4))[0] width = unpack('>i', img_file.read(4))[0] # Verifica se o arquivo passa no teste # básico (este número deve ser sempre 2051) if magic != 2051: print('Erro, este arquivo não parece ser um arquivo de imagens MNIST') # Aqui criamos a array do NumPy que armazenará # as imagens imgs = np.zeros((total,height,width)) # Nesse laço vamos lendo cada pixel e preenchendo # no array for k in range(total): # Cada amostra k for i in range(height): # Cada linha i for j in range(width): # Cada coluna j imgs[k,i,j] = ord(img_file.read(1)) # Lemos 1 byte # Retornamos o array preenchido return imgs # + [markdown] id="ex6SljeojCtM" # De forma semelhante ao realizado acima, aqui abaixo definimos as funções auxiliares para leitura do arquivo de rótulos. # + id="gpK1CJ0mgAzn" def read_labels(labels_filename): ''' Esta função lê o arquivo de rótulos da base de dados MNIST ''' # Abre o arquivo labels_file = open(labels_filename,'rb') # Lê o cabeçalho do arquivo magic = unpack('>i', labels_file.read(4))[0] total = unpack('>i', labels_file.read(4))[0] # Verifica se o arquivo passa no teste # básico (este número deve ser sempre 2051) if magic != 2049: print('Erro, este arquivo não parece ser um arquivo de imagens MNIST') # Aqui criamos a array do NumPy que armazenará # as imagens labels = np.zeros((total)) # Nesse laço vamos lendo cada label e preenchendo # no array for k in range(total): # Cada amostra k labels[k] = ord(labels_file.read(1)) # Lemos 1 byte # Retornamos o array preenchido return labels # + [markdown] id="PgwpORvVjHBf" # Nas linhas abaixo chamamos as função de leitura para carregar as imagens e os respectivos rótulos # + id="JEEgfzZli9yF" # Lê dados de treinamento imgs = read_imgs('train-images-idx3-ubyte') labels = read_labels('train-labels-idx1-ubyte') # Lê dados de validação imgs_val = read_imgs('t10k-images-idx3-ubyte') labels_val = read_labels('t10k-labels-idx1-ubyte') # + [markdown] id="2VrUcPJsaYcV" # ## Passo 3: Entendendo os dados # # No bloco de código abaixo vamos examinar em detalhe como é o formato desses dados que acabamos de ler como tensores do NumPy. # + colab={"base_uri": "https://localhost:8080/"} id="EhdY9vfOZ7Dq" outputId="a8f0f07d-93fd-41da-c589-b40faa36902e" print('Imagens de treinamento',imgs.shape) print('Etiquetas de treinamento', labels.shape) print('Imagens de validação',imgs_val.shape) print('Etiquetas de validação', labels_val.shape) # + [markdown] id="f88ng4joastd" # ### Passo 3.1: Imagens # # Podemos notar acima que as imagens são tensores de três dimensões, enquanto as etiquetas são vetores de uma única dimensão. # # Vamos examinar a estrutura do tensor `imgs` em maior detalhe na figura abaixo. Esse é um tensor de tamanho 60000x28x28. Podemos imaginar este tensor como uma pilha de imagens, onde a primeira coordenada seleciona uma das 60 mil imagens, e as próximas duas coordenadas indicam respectivamente a linha e a coluna referente ao píxel que queremos examinar. O valor ali contido é um inteiro representando uma escala de cinza no intervalo de 0 a 255, onde 0 representa o valor mais escuro e 255 o valor mais claro, respectivamente. Esse conceito é ilustrado na figura abaixo. # # <center> # <img src="https://drive.google.com/uc?id=1E0w4hac4TmPx41pt8dBkzw3OIkVBDnWY" width="400"/> # </center> # # A estrutura do tensor `imgs_val` é idêntica, exceto que este tensor contém apenas 10 mil imagens. # + [markdown] id="harypu-PJPUM" # ### Passo 3.2: Etiquetas # # Agora vamos dar uma olhada nas etiquetas `labels` e `labels_val` # + colab={"base_uri": "https://localhost:8080/"} id="w2oHhkxzJVX8" outputId="0bc4aac3-2ade-4d35-beb0-76708d3baa63" print('labels =',labels,'é um array de',len(labels),'elementos') print('labels_val =',labels_val,'é um array de',len(labels_val),'elementos') # + [markdown] id="0puSSrc_KEat" # Como podemos observar acima, cada elemento de um array de etiquetas é um número inteiro entre 0 e 9. Para um índice `i` entre $0$ e $59999$, `labels[i]` representa a etiqueta da imagem em `imgs[i,:,:]`. O mesmo acontece entre `labels_val[i]` e `imgs_val[i]`, para índices entre $0$ e $9999$. # # Para verificar isso, podemos utilizar a função `imshow()` do módulo `pyplot`. Essa função recebe como entrada um array de duas dimensões, e mostra seus valores na tela na forma de uma imagem, onde o brilho de cada píxel corresponde ao valor na respectiva posição de linha e coluna do array. # + id="YJP0QNZwLu9V" from matplotlib import pyplot as plt # + colab={"base_uri": "https://localhost:8080/", "height": 814} id="4Nhb5RpMLyV8" outputId="ddde8dd5-5c8f-4ec7-b1ae-46eeb182e958" # No laço abaixo sorteamos três amostras aleatórias # e mostramos a etiqueta e a respectiva imagem. for _ in range(3): # Sorteamos uma amostra i = np.random.randint(0,60000) # Imprimimos a etiqueta e a respectiva imagem print('A imagem abaixo mostra o dígito', labels[i]) plt.imshow(imgs[i,:,:],cmap='gray') plt.show() # + [markdown] id="ujNsuuc_NROj" # ## Passo 4: Embaralhamento das amostras # # Apesar que os dados MNIST baixados aqui já vêm embaralhados, é considerado uma boa prática sempre embaralhar os dados antes de utilizar. No código abaixo faça isso, embaralhando os pares `imgs` e `labels`, tomando o cuidado para que a amostra em cada posição mantenha a correspondência. # # # # # + id="cailF8ekfd8V" # Escreva aqui seu código para embaralhar # os pares de treinamento. Mantenha os mesmos # nomes de variáveis originais. from random import shuffle aux = [] for i in range(len(imgs)): aux.append((imgs[i], labels[i])) shuffle(aux) # Importante manter as dimensões das variáveis usadas imgs = np.zeros(imgs.shape) labels = np.zeros(labels.shape) for i in range(len(imgs)): imgs[i] = aux[i][0] labels[i] = aux[i][1] # + id="auAZ1jwRY1-7" # Este teste avalia o embaralhamento ok.check('e05_1.py') # + [markdown] id="tkyOV_z-fw7g" # ## Passo 5: Normalização # # Note que os dados de brilho de cada pixel são números inteiros convertidos de uma representação de $8$ bits. Isso significa que cada valor está no intervalo $0$ a $255$. No código abaixo, ajuste o intervalo de valores para essas entradas de forma que os valores fiquem no intervalo $0$ a $1$. # + id="EyPMGMZAgYfp" # Escreva aqui seu código para normalizar # as imagens dos dados de treinamento, colocando # os valores no intervalo de 0 a 1 # Se a imagem tiver mais que 8 bits pode ser passado o parametro de bits norm = lambda pos, bits=8 : pos/((2**bits)-1) # Normalização dos valores de imgs for i in range(len(imgs)): for l in range(len(imgs[i])): for w in range(len(imgs[i])): imgs[i][l][w] = norm(imgs[i][l][w]) # Normalização dos valores de imgs_val for i in range(len(imgs_val)): for l in range(len(imgs_val[i])): for w in range(len(imgs_val[i])): imgs_val[i][l][w] = norm(imgs_val[i][l][w]) # + id="vlICzR2xgkMK" # Esse teste avalia a normalização ok.check('e05_2.py') # + [markdown] id="Wcnsbat0k2-L" # ## Passo 6: One-Hot # # Agora você deve converter as etiquetas `labels` e `labels_val` para o formato _one-hot_. Mantenha os mesmos nomes de variável. O resultado deve ser os arrays `labels` com dimensões $60000 \times 10$ e `labels_val` com $10000 \times 10$. # # # `0 => 1 0 0 0 0 0 0 0 0` # # `1 => 0 1 0 0 0 0 0 0 0` # # `2 => 0 0 1 0 0 0 0 0 0` # # `3 => 0 0 0 1 0 0 0 0 0` # # (...) # + id="pTerroaAlu-U" # Escreva aqui o código que converte os # arrays labels e labels_val para o formato # one-hot ZERO = [0,0,0,0,0,0,0,0,0,0] lab = np.zeros( (len(labels), 10) ) lab_val = np.zeros( (len(labels_val), 10) ) def oneHot(pos): aux = ZERO.copy() aux[int(pos)] = 1 return aux for i in range(len(lab)): lab[i] = oneHot( labels[i] ) for j in range(len(lab_val)): lab_val[j] = oneHot(labels_val[j]) labels = lab.copy() labels_val = lab_val.copy() # + colab={"base_uri": "https://localhost:8080/", "height": 46} id="r2_gqLTAl2nA" outputId="44e6db1e-87e2-45a5-85e4-47a9d5f5e9fb" # Este teste avalia a conversão para # o formato one-hot ok.check('e05_3.py') # + [markdown] id="jlrTTreNzJQl" # ## Passo 7: Função softmax # # Implemente a função _softmax_. Essa função deve ser definida com o nome `softmax(x)`, recebendo o parâmetro `x` que será um vetor coluna com `10` elementos. Essa função deve retornar a versão softmax desse vetor, ou seja, cada componente $i$ deve ser calculada como: # # <center> # $\frac{\exp(x_i)}{\sum_{j=0}^{9} \exp(x_j)}$ # </center> # + id="x_MYH0QWzEfX" # Implemente aqui a função softmax from numpy import exp def softmax(x): return exp(x)/np.sum(exp(x)) # + colab={"base_uri": "https://localhost:8080/", "height": 46} id="mXZHuDc50jkV" outputId="ea0b27ab-a826-46b0-9d9f-f412de6b1073" # Este teste avalia a função softmax ok.check('e05_4.py') # + [markdown] id="MZQNESwPb-jC" # ## Passo 8: Função sigmoide # # Implemente a função de ativação _sigmoide_. Essa função deve ser definida com o nome `sigmoid(x)`, recebendo o parâmetro `x` que será um vetor coluna com `n` elementos. Essa função deve retornar um vetor de mesmas dimensões onde o valor de cada elemento é igual a: # # <center> # $\frac{1}{1 + \exp(-x)}$ # </center> # + id="nmPtJQ3Nd6D9" # Implemente aqui a função sigmoide def sigmoid(x): return np.array([1/(1+exp(-i)) for i in x]) # + colab={"base_uri": "https://localhost:8080/", "height": 46} id="pzViNL20eBnK" outputId="e7359620-6fc5-448f-d939-586d7f20f064" # Este teste avalia a função sigmoide ok.check('e05_5.py') # + [markdown] id="me3gTd3zknix" # # Rede Neural # # Agora você começará a escrever o código que representa a classe que implementa a rede neural. Esta será uma rede neural estilo perceptron. A implementação seguirá vários passos. Para cada passo você deve ler as instruções e retornar a ao mesmo código desta classe, acrescentando as alterações necessárias para atender aquela etapa. # + id="E8WhQ55m7Krt" # Implemente aqui, passo a passo, a classe de sua rede neural class Perceptron(): def __init__(self): # Pesos (width) self.W1 = np.random.random((256,784)) * 2 - 1 self.W2 = np.random.random((64, 256)) * 2 - 1 self.W3 = np.random.random((10, 64 )) * 2 - 1 #Bias self.b1 = np.random.random((256,1)) * 2 - 1 self.b2 = np.random.random((64,1)) * 2 - 1 self.b3 = np.random.random((10 ,1)) * 2 - 1 # Passo self.eta = 0.001 def forward(self, inputs): # Garante vetor coluna inputs = np.reshape(inputs, (len(inputs),1)) # Sinapse Hidden 1 camada = Entrada * Pesos Input w1 + bias b1 self.s1 = np.dot(self.W1, inputs) + self.b1 self.z1 = sigmoid(self.s1) # Sinapse Hidden 2 camada = saida z1 * Pesos w2 + bias b2 self.s2 = np.dot(self.W2, self.z1) + self.b2 self.z2 = sigmoid(self.s2) # Sinapse Output = Saida z2 * Pesos w3 + bias b3 self.s3 = np.dot(self.W3, self.z2) + self.b3 self.z3 = softmax(self.s3) return self.z3 # Implementação do backpropagation def backprop(self, X, Y_des ): self.y = self.forward(X) # Delta da camada de saida usando Cross Entropy # δL = y - y_des self.d3 = self.y - Y_des # δl=W(l+1).T *δ(l+1) ⊙ σ′(sl) # σ′(sl) = zl(1−zl) self.d2 = np.dot(self.W3.T, self.d3) * self.z2 *(1-self.z2) self.d1 = np.dot(self.W2.T, self.d2) * self.z1 *(1-self.z1) # Calculo das derivadas parciais de W[n.m] e B[n] self.dW3 = np.dot(self.d3, self.z2.T) self.db3 = self.d3 self.dW2 = np.dot(self.d2, self.z1.T) self.db2 = self.d2 self.dW1 = np.dot(self.d1, X.T) self.db1 = self.d1 # Passo self.eta = 0.1 # Optimização dos pesos e biases self.W1 = self.W1 - self.eta * self.dW1 self.W2 = self.W2 - self.eta * self.dW2 self.W3 = self.W3 - self.eta * self.dW3 self.b1 = self.b1 - self.eta * self.db1 self.b2 = self.b2 - self.eta * self.db2 self.b3 = self.b3 - self.eta * self.db3 # Cross Entropy self.ce = -np.sum(Y_des * np.log(self.y)) return self.ce # + [markdown] id="d07HpCy_qnV3" # #### ATENÇÃO: Os passos abaixo devem ser todos implementados no código acima ### # + [markdown] id="fp1a4Kcx7CPw" # ## Passo 9: Definição da Classe # # Crie uma classe de nome `Perceptron`. Essa classe deve incluir um construtor `__init__(self)` que não recebe parâmetro nenhum. # # No construtor vamos criar as matrizes de pesos e vetores de bias para uma rede neural com as seguintes características: # - $28 \times 28 = 784$ entradas (brilho dos pixels da imagem de uma das amostras, serializados num vetor coluna) # - Camada de $256$ neurônios na primeira camada, com ativação sigmoide # - Camada de $64$ neurônios na segunda camada, com ativação sigmoide # - Camada de $10$ neurônios de saída na última camada, com ativação softmax # # A matriz dos pesos e vetores de bias de cada camada deverão ser chamados, respectivamente de: `w1`, `b1`, `w2`, `b2`, `w3`, `b3`. Crie e inicialize cada matriz de pesos e vetor de bias com valores aleatórios entre $-1$ e $+1$. Certifique-se de que cada uma dessas arrays tenha as dimensões corretas. # + id="DfSjyaXZ9wp8" # Este teste avalia a definição da classe ok.check('e05_6.py') # + [markdown] id="XbyQYMsN77aP" # ## Passo 10: Método `forward(x)` # # Agora crie o método `forward(x)` dentro da classe `Perceptron` (lembre que todos métodos que pertencem a classes, no Python, devem receber `self` como primeiro argumento, ou seja, na realidade o método é `forward(self,x)`). Esse método deve receber o vetor coluna `x` que é a imagem de uma amostra de um dígito da base de dados MNIST, com todos os valores de brilho dos píxels em um vetor coluna de $28 \times 28 = 784$ linhas. # # Dentro desse método você deve seguir os seguintes passos: # # * Calcule os valores de `s1` a partir das entradas `x`, usando os pesos `W1` e bias `b1`. # * Aplique a função de ativação sigmoide em `s1` para encontrar `z1`. # * Calcule os valores de `s2` a partir das ativações `z1` usando os pesos `W2` e bias `b2`. # * Aplique a função de ativação sigmoide em `s2` para encontrar `z2` # * Calcule os valores de `s3` a partir das ativações `z2` usando os pesos `W3` e bias `b3`. # * Aplique a função `softmax()` em `s3` para encontrar `z3`. # * Garanta que todas essas $6$ variáveis, `s1`,`z1`,`s2`,`z2`,`s3`,`z3`, sejam variáveis membro (por exemplo, `self.s1 = ...`, etc) # * Retorne `z3` # # + colab={"base_uri": "https://localhost:8080/", "height": 46} id="C2_PJUMNq1B8" outputId="520177dc-7269-4a4a-df12-131b968629c1" # Este teste avalia o método forward(x) ok.check('e05_7.py') # + [markdown] id="HygZ3aZ7xzx5" # ## Passo 11: Backpropagation # # Finalmente, neste último passo, vamos implementar o algoritmo backpropagation nesta rede neural. Aqui consideramos minimizar o custo _entropia cruzada_ (CE - cross entropy). # # Para isso você vai seguir os seguintes passos: # # * Crie um método de nome `backprop(x,y_des)` que recebe o par `x` e `y_des`, onde `x` é a entrada e `y_des` é a respectiva saída desejada. Lembre sempre que métodos (funções que pertencem a classes) precisam do parâmetro obrigatório `self` (por exemplo `def backprop(self,x,y)`). # # * Dentro deste método, chame a função `forward(x)` com o valor de `x` que é a entrada do par passado no argumento. Salve o resultado da saída obtida na variável de nome `y`. # # * Dentro deste método, calcule o vetor de deltas $\delta^3$ da camada de saída, dando o nome `d3`. Lembre que para uma camada de saída _softmax_, considerando custo CE, temos `d3` = `y - y_des`. # # * Calcule agora os deltas de trás para frente, descobrindo `d2` a partir de `d3`, e em seguida `d1` a partir de `d2`, usando para ambos a fórmula $\delta^l=(W^{l+1})^T\delta^{l+1}\odot\sigma'(s^l)$, lembrando que para a sigmoide, a derivada da função de ativação é $\sigma'(s^l) = z^l (1 - z^l)$ # # * Compute as matrizes e vetores de derivadas parciais (o gradiente) do custo em relação aos pesos e bias de todas camadas, usando essas fórmulas abaixo. Use os nomes `dW1`, `db1`, `dW2`, `db2`, `dW3`, `db3`. # # `dW..` = $\frac{\partial{E_{CE}}}{\partial{W^l}} = \delta^l \times \left(z^{l-1}\right)^T $ # # `db..` = $\frac{\partial{E_{CE}}}{\partial{b^l}} = \delta^l $ # # * Considerando um passo `eta=0.1`, atualize os pesos e biases exatamente um passo na direção oposta. # # * Usando os valores de entrada `x`, `y_des` e a saída calculada `y`, calcule a função de custo entropia cruzada, na variável `ce`. Use esse valor como valor de retorno da função. # # * Grave as variáveis `y`, `d1`, `d2`, `d3`, `dW1`, `dW2`, `dW3`, `db1`, `db2`, `db3`, `ce` como variáveis membro da classe (use, por exemplo, `self.y = ...`) # # Atenção: não crie um laço. Faça essa implementação ajustando no sentido oposto do gradiente em apenas um passo. # + colab={"base_uri": "https://localhost:8080/", "height": 46} id="RZyICTVXH4B1" outputId="8c7adef9-d58d-4854-b058-4fc944d2bb2c" # Este teste avalia sua implementação do # algoritmo backpropagation ok.check('e05_8.py') # + [markdown] id="hueBmOdhV3C_" # # Treinando # # A função abaixo faz o treinamento da rede neural que você acabou de programar, em lotes. # + id="97LdoaGiV2U7" def train_batch(p, X, Y_desired, batch_size=250): ''' Esta função faz o treinamento da rede neural, percorrendo todo dataset, por lotes de 250 amostras PS.: Aqui os lotes não importam muito pois ajustamos os pesos um pouco a para cada amostra individual. ''' # Total de amostras total = X.shape[0] # Erro global vai ser somado aqui Err = 0.0 # Vamos percorrer as amostras em lotes for i in range(0,total,batch_size): # Erro de cada lote err_batch = 0.0 # Aqui neste laço vamos treinar o lote for j in range(i,i+batch_size): # Separamos os dados de entrada x = np.reshape(X[j,:,:],(784,1)) # Separamos os dados de treinamento correspondentes y_desired = np.reshape(Y_desired[j,:],(10,1)) # Calculamos o fator de correção dos pesos e biases ce = p.backprop(x, y_desired) # Computamos o erro do lote err_batch += ce # Normalização do erro do lote err_batch /= batch_size # Soma do erro do lote ao erro global # já com fator de normalização Err += err_batch / (total/batch_size) return Err # + [markdown] id="817-GbFnWrRq" # A função abaixo roda o treinamento completo # + id="u0PWv44SWpzD" colab={"base_uri": "https://localhost:8080/", "height": 420} outputId="08400ed8-e2bf-44d5-8c6c-9e90b69bf92b" import time # Aqui criamos a rede neural p = Perceptron() # Nesta lista gravaremos a evolução do erro # para plotar num gráfico mais tarde Errs = [] # Treinaremos 10 épocas (cada época demora em torno de 2 min) for i in range(10): # Marcamos o tempo de início para computar o tempo # que demoramos para treinar cada época (isso ajuda # a estimar o tempo total) start_time = time.time() # Aqui fazemos o treinamento Err = train_batch(p, imgs, labels) # Mostramos os resultados parciais na tela print('Elapsed time:', time.time() - start_time, 's', \ 'Err:', Err) # Guardamos o erro calculado em cada época para # plotar no gráfico em seguida Errs.append(Err) # + [markdown] id="jWzPz9eRW5pd" # # Avaliação dos Resultados # + id="VyQ0R0bsW8GD" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="3fddc24d-e30b-44d3-b6b0-d5ddebd4b44e" # Plotamos o gráfico da evolução do erro # no tempo. Esta é a chamada "curva de # aprendizagem" plt.plot(Errs) plt.show() # + [markdown] id="WdSLgA5UXBO6" # A função abaixo serve para calcular a taxa de acerto dessa rede neural # + id="E-QlZ2rbXDgQ" def accuracy(p, X, Y): ''' Esta função vai calcular a taxa de acerto da rede neural p nos dados fornecidos ''' # Contador de acertos correct_count = 0 # Total de amostras total = X.shape[0] # Laço vai percorrer todas amostras for k in range(total): # Esta é a resposta que desejamos correct_answer = np.argmax(Y[k,:]) # Esta é a resposta encontrada guess = np.argmax(p.forward(np.reshape(X[k,:,:],(784,1)))) # Se ambas estiverem corretas if correct_answer == guess: # Contabilizamos como resposta correta correct_count += 1 # Aqui retornamos o resultado return correct_count / total # + [markdown] id="QX_j8B41Xl-k" # Aqui avaliamos a performance da rede neural nos próprios dados de treinamento. # + id="0bOGBb9-XrBz" colab={"base_uri": "https://localhost:8080/"} outputId="cd261d16-24db-4331-ef50-7f8499e55f58" print('Taxa de acerto nos dados de treinamento:', \ 100*accuracy(p, imgs, labels), '%') # + [markdown] id="6_tH4GX3Xtvx" # No código abaixo avaliamos a performance da rede neural nos dados de validação, que são dados nunca usados durante o treinamento. # + id="cWdf2fvNXwL0" colab={"base_uri": "https://localhost:8080/"} outputId="96f285e9-f225-47f7-cf95-bbdb00c4ff7e" print('Taxa de acerto nos dados de validação:', \ 100*accuracy(p, imgs_val, labels_val), '%')
DeepLearning/01-Backpropagation/BackpropagationMNIST.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 jieba import json import os from collections import OrderedDict,Counter,defaultdict,Counter import copy import random import math import re import numpy as np import zipfile import torch from transformers import BertTokenizer,BertModel,get_linear_schedule_with_warmup import torch.nn as nn from torch.utils.data import DataLoader,Dataset from transformers import BertConfig,BertTokenizer,BertModel,AdamW from tqdm import tqdm import time seed = 2021 torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. np.random.seed(seed) # Numpy module. random.seed(seed) # Python random module. torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False import warnings warnings.filterwarnings('ignore') def generate_tags(tokenizer,word_seq,slots): tag_seq=['O']*len(word_seq) # attention please here value should be considered to be a list, because some recommends can be shown in one quest. for key,values in slots.items(): for value in values: current_slot_value=tokenizer.tokenize(value) for i in range(len(word_seq)): if word_seq[i:i+len(current_slot_value)]==current_slot_value: tag_seq[i]='B+'+key if len(current_slot_value)>1: tag_seq[i+1:i+len(current_slot_value)]=['I+'+key]*(len(current_slot_value)-1) break return tag_seq def preprocess_data(file_dir,tokenizer,include_sys=False): data_key=['train','val','test'] intent_vocab=[] tag_vocab=[] for key in data_key: file_name=os.path.join(file_dir,key+'.json.zip') zpf=zipfile.ZipFile(file_name,'r') data=json.load(zpf.open(key+'.json')) sessions=[] for num,session in data.items(): for i,message in enumerate(session["messages"]): utterance=message["content"] word_seq=tokenizer.tokenize(utterance) if message["role"]=="sys" and not include_sys: pass else: processed_data=[] slots={} intents=[] golden=[] for intent,domain,slot,value in message["dialog_act"]: if intent in ['Inform','Recommend'] and '酒店设施' not in slot: if value in utterance: idx=utterance.index(value) idx=len(tokenizer.tokenize(utterance[:idx])) new_value=''.join(word_seq[idx:idx+len(tokenizer.tokenize(value))]) new_value=new_value.replace('##','') golden.append([intent,domain,slot,new_value]) slot_name="+".join([intent,domain,slot]) if slot_name not in slots: slots[slot_name]=[value] else: slots[slot_name].append(value) else: golden.append([intent,domain,slot,value]) else: intent_name='+'.join([intent,domain,slot,value]) intents.append(intent_name) intent_vocab.append(intent_name) golden.append([intent,domain,slot,value]) tag_seq=generate_tags(tokenizer,word_seq,slots) tag_vocab+=tag_seq processed_data.append(word_seq) processed_data.append(tag_seq) processed_data.append(intents) processed_data.append(golden) # attention please copy.deepcopy should be used to prevent data change later effect current_context=[item["content"] for item in session["messages"][0:i] ] # if len(current_context)==0:current_context=[''] processed_data.append(current_context) sessions.append(processed_data) with open(os.path.join(file_dir,f'formated_{key}_nlu_data.json'),"w",encoding='utf-8') as g: json.dump(sessions,g,indent=2,ensure_ascii=False) print(os.path.join(file_dir,f'formated_{key}_nlu_data.json')) with open(os.path.join(file_dir,'intent_vocab.json'),"w",encoding='utf-8') as h: output_intent_vocab=[x[0] for x in dict(Counter(intent_vocab)).items()] json.dump(output_intent_vocab,h,indent=2,ensure_ascii=False) print(os.path.join(file_dir,'intent_vocab.json')) with open(os.path.join(file_dir,'tag_vocab.json'),"w",encoding='utf-8') as j: output_tag_vocab=[x[0] for x in dict(Counter(tag_vocab)).items()] json.dump(output_tag_vocab,j,indent=2,ensure_ascii=False) print(os.path.join(file_dir,'tag_vocab.json')) class Dataloader: def __init__(self, intent_vocab_path, tag_vocab_path, pretrained_weights, max_history=3): """ :param intent_vocab: list of all intents :param tag_vocab: list of all tags :param pretrained_weights: which bert_policy, e.g. 'bert_policy-base-uncased' """ with open(intent_vocab_path,'r',encoding='utf-8') as f: self.intent_vocab=json.load(f) with open(tag_vocab_path,'r',encoding='utf-8') as g: self.tag_vocab=json.load(g) self.intent_dim = len(self.intent_vocab) self.tag_dim = len(self.tag_vocab) self.id2intent = dict([(i, x) for i, x in enumerate(self.intent_vocab)]) self.intent2id = dict([(x, i) for i, x in enumerate(self.intent_vocab)]) self.id2tag = dict([(i, x) for i, x in enumerate(self.tag_vocab)]) self.tag2id = dict([(x, i) for i, x in enumerate(self.tag_vocab)]) self.tokenizer = BertTokenizer.from_pretrained(pretrained_weights) self.data = {} self.intent_weight = [1] * len(self.intent2id) self.max_history=max_history self.max_sen_len=0 self.max_context_len=0 def load_data(self, data_path, data_key, cut_sen_len=0): """ sample representation: [list of words, list of tags, list of intents, original dialog act] :param data_key: train/val/tests :param data: :return: """ # data是[tokens, tags, intents, raw_dialog_act, context[-context_size:]]]五个纬度的嵌套列表 # tokens是jieba切分的得到的词,tags是可以看作词对应的slot标签, with open(data_path,'r',encoding='utf-8') as f: self.data[data_key]=json.load(f) max_context_len=0 max_sen_len=0 for d in self.data[data_key]: # d = (tokens, tags, intents, raw_dialog_act, context(list of str)) if cut_sen_len > 0: d[0] = d[0][:cut_sen_len] d[1] = d[1][:cut_sen_len] d[4] = [" ".join(s.split()[:cut_sen_len]) for s in d[4][-self.max_history:]] d[4] = self.tokenizer.encode("[CLS] " + " [SEP] ".join(d[4])) max_context_len = max(max_context_len, len(d[4])) word_seq = d[0] tag_seq = d[1] new2ori = None d.append(new2ori) d.append(word_seq) d.append(self.seq_tag2id(tag_seq)) d.append(self.seq_intent2id(d[2])) # here sep and cls will be added later max_sen_len = max(max_sen_len, len(word_seq)+2) # d = (tokens, tags, intents, da2triples(turn["dialog_act"]), context(token id), new2ori, new_word_seq, tag2id_seq, intent2id_seq) if data_key == "train": for intent_id in d[-1]: self.intent_weight[intent_id] += 1 if data_key == "train": train_size = len(self.data["train"]) for intent, intent_id in self.intent2id.items(): neg_pos = ( train_size - self.intent_weight[intent_id] ) / self.intent_weight[intent_id] self.intent_weight[intent_id] = np.log10(neg_pos) self.intent_weight = torch.tensor(self.intent_weight) self.max_context_len=max_context_len self.max_sen_len=max_sen_len print("max sen bert_policy len from train data", self.max_sen_len) print("max context bert_policy len from train data", self.max_context_len) def seq_tag2id(self, tags): return [self.tag2id[x] for x in tags if x in self.tag2id] def seq_id2tag(self, ids): return [self.id2tag[x] for x in ids] def seq_intent2id(self, intents): return [self.intent2id[x] for x in intents if x in self.intent2id] def seq_id2intent(self, ids): return [self.id2intent[x] for x in ids] def pad_batch(self, batch_data): batch_size = len(batch_data) max_sen_len = max([len(x[-3]) for x in batch_data]) + 2 word_mask_tensor = torch.zeros((batch_size, max_sen_len), dtype=torch.long) word_seq_tensor = torch.zeros((batch_size, max_sen_len), dtype=torch.long) tag_mask_tensor = torch.zeros((batch_size, max_sen_len), dtype=torch.long) tag_seq_tensor = torch.zeros((batch_size, max_sen_len), dtype=torch.long) intent_tensor = torch.zeros((batch_size, self.intent_dim), dtype=torch.float) max_context_len = max([len(x[-5]) for x in batch_data]) context_mask_tensor = torch.zeros( (batch_size, max_context_len), dtype=torch.long) context_seq_tensor = torch.zeros( (batch_size, max_context_len), dtype=torch.long) for i in range(batch_size): words = batch_data[i][-3] # tags = batch_data[i][-2] intents = batch_data[i][-1] words = ["[CLS]"] + words + ["[SEP]"] indexed_tokens = self.tokenizer.convert_tokens_to_ids(words) sen_len = len(words) word_seq_tensor[i, :sen_len] = torch.LongTensor([indexed_tokens]) tag_seq_tensor[i, 1 : sen_len - 1] = torch.LongTensor(tags) word_mask_tensor[i, :sen_len] = torch.LongTensor([1] * sen_len) tag_mask_tensor[i, 1 : sen_len - 1] = torch.LongTensor([1] * (sen_len - 2)) for j in intents: intent_tensor[i, j] = 1.0 context_len = len(batch_data[i][-5]) context_seq_tensor[i, :context_len] = torch.LongTensor([batch_data[i][-5]]) context_mask_tensor[i, :context_len] = torch.LongTensor([1] * context_len) return word_seq_tensor,word_mask_tensor,tag_seq_tensor,tag_mask_tensor,intent_tensor,context_seq_tensor,context_mask_tensor def get_train_batch(self, batch_size): batch_data = random.choices(self.data["train"], k=batch_size) return self.pad_batch(batch_data) def yield_batches(self, batch_size, data_key): batch_num = math.ceil(len(self.data[data_key]) / batch_size) for i in range(batch_num): batch_data = self.data[data_key][i * batch_size : (i + 1) * batch_size] yield self.pad_batch(batch_data), batch_data, len(batch_data) class JointWithBert(nn.Module): def __init__(self, model_config, slot_dim, intent_dim): super(JointWithBert, self).__init__() # count of intent and tag self.slot_num_labels = slot_dim self.intent_num_labels = intent_dim # model self.bert = BertModel.from_pretrained(model_config.pretrained_weights) self.dropout = nn.Dropout(model_config.dropout) self.hidden_units = model_config.hidden_units self.intent_classifier = nn.Linear(self.hidden_units, self.intent_num_labels) self.slot_classifier = nn.Linear(self.hidden_units, self.slot_num_labels) self.intent_hidden = nn.Linear(2 * self.bert.config.hidden_size, self.hidden_units) self.slot_hidden = nn.Linear(2 * self.bert.config.hidden_size, self.hidden_units) nn.init.xavier_uniform_(self.intent_hidden.weight) nn.init.xavier_uniform_(self.slot_hidden.weight) nn.init.xavier_uniform_(self.intent_classifier.weight) nn.init.xavier_uniform_(self.slot_classifier.weight) def forward(self,word_seq_tensor,word_mask_tensor,context_seq_tensor,context_mask_tensor): outputs = self.bert(input_ids=word_seq_tensor, attention_mask=word_mask_tensor) # 获取每个token的output 输出[batch_size, seq_length, embedding_size] 如果做seq2seq 或者ner 用这个 sequence_output = outputs[0] # 这个输出是获取句子的output pooled_output = outputs[1] # 如果有上下文信息 # 将上下文信息进行bert训练并获得整个句子的output context_output = self.bert(input_ids=context_seq_tensor, attention_mask=context_mask_tensor)[1] # 将上下文得到输出和word_seq_tensor得到的输出进行拼接 sequence_output = torch.cat([context_output.unsqueeze(1).repeat(1, sequence_output.size(1), 1),sequence_output,], dim=-1,) # 将上下文得到输出和之前获取句子的output进行拼接 pooled_output = torch.cat([context_output, pooled_output], dim=-1) # 经过dropout、Linear、relu层 sequence_output = nn.functional.relu(self.slot_hidden(self.dropout(sequence_output))) pooled_output = nn.functional.relu(self.intent_hidden(self.dropout(pooled_output))) # 经过dropout sequence_output = self.dropout(sequence_output) # 经过Linear层 slot_logits = self.slot_classifier(sequence_output) outputs = (slot_logits,) pooled_output = self.dropout(pooled_output) intent_logits = self.intent_classifier(pooled_output) outputs = outputs + (intent_logits,) return outputs class Model_Config(): def __init__(self,): self.pretrained_weights='./hfl/chinese-bert-wwm-ext' self.train_data_path='./crosswoz_data/formated_train_nlu_data.json' self.test_data_path='./crosswoz_data/formated_test_nlu_data.json' self.dev_data_path='./crosswoz_data/formated_val_nlu_data.json' self.hidden_units=1536 self.learning_rate=3.0e-5 self.bert_learning_rate=3e-5 self.other_learning_rate=3e-5 self.weight_decay=0.01 self.warmup_steps=0 self.save_weight_path='./crosswoz_data/output/saved_model/my-pytorch-joint-with-bert.pt' self.save_model_path='./crosswoz_data/output/saved_model/my-pytorch-joint-with-bert.pth' self.device='cuda:0' if torch.cuda.is_available() else 'cpu' self.eps=1e-8 self.batch_size=20 self.max_step=40000 self.check_step=1000 self.dropout=0.1 self.cut_sen_len=60 self.intent_vocab_path='./crosswoz_data/intent_vocab.json' self.tag_vocab_path='./crosswoz_data/tag_vocab.json' self.max_history=3 self.if_intent_weight=True self.mask_loss=True def is_slot_da(da): if da[0] in ['Inform','Recommend'] and '酒店设施' not in da[2]: return True return False def get_score(predict_golden): TP,FP,FN=0,0,0 for item in predict_golden: predicts=item['predict'] labels=item['golden'] for item in predicts: if item in labels: TP+=1 else: FP+=1 for item in labels: if item not in predicts: FN+=1 precision=1.0*TP/(TP+FP) if TP+FP else 0.0 recall=1.0*TP/(TP+FN) if TP+FN else 0.0 F1=2.0*precision*recall/(precision+recall) if precision+recall else 0.0 return precision,recall,F1 def tag2das(word_seq,tag_seq): assert len(word_seq)==len(tag_seq) das=[] i=0 while i<len(tag_seq): tag=tag_seq[i] if tag.startswith('B'): intent,domain,slot=tag[2:].split('+') value=word_seq[i] j=i+1 while j<len(tag_seq): if tag_seq[j].startswith('I') and tag_seq[j][2:]==tag[2:]: if word_seq[j].startswith('##'): value+=word_seq[j][2:] else: value+=word_seq[j] i+=1 j+=1 else: break das.append([intent,domain,slot,value]) i+=1 return das def recover_intent(dataloader,intent_logits,tag_logits,tag_mask_tensor,ori_word_seq,new2ori): max_seq_len=tag_logits.size(0) das=[] for j in range(dataloader.intent_dim): if intent_logits[j]>0: intent,domain,slot,value=re.split('\+',dataloader.id2intent[j]) das.append([intent,domain,slot,value]) tags=[] for j in range(1,max_seq_len-1): if tag_mask_tensor[j]==1: value,tag_id=torch.max(tag_logits[j],dim=-1) tags.append(dataloader.id2tag[tag_id.item()]) tag_intent=tag2das(ori_word_seq,tags) das+=tag_intent return das def get_total_loss_func(dataloader,config,intent_logits,intent_tensor,slot_logits,tag_seq_tensor,tag_mask_tensor,intent_loss_fct,slot_loss_fct): if config.mask_loss: active_tag_loss = tag_mask_tensor.view(-1) == 1 # I made some change for the view function active_tag_logits = slot_logits.view(-1, slot_logits.size()[-1])[active_tag_loss] active_tag_labels = tag_seq_tensor.view(-1)[active_tag_loss] else: active_tag_logits = slot_logits active_tag_labels = tag_seq_tensor slot_loss = slot_loss_fct(active_tag_logits, active_tag_labels) intent_loss = intent_loss_fct(intent_logits, intent_tensor) return slot_loss,intent_loss def evaluate(config,model,dataloader,data_key,slot_loss_fct,intent_loss_fct): model.eval() val_slot_loss,val_intent_loss=0,0 predict_golden={'intent':[],'slot':[],'overall':[]} score_result={'intent':[],'slot':[],'overall':[]} for index,(model_inputs,batch_data,num_data) in tqdm(enumerate(dataloader.yield_batches(config.batch_size,data_key))): model_inputs=tuple(item.to(config.device) for item in model_inputs) word_seq_tensor,word_mask_tensor,tag_seq_tensor,tag_mask_tensor,intent_tensor,context_seq_tensor,context_mask_tensor=model_inputs with torch.no_grad(): slot_logits,intent_logits=model.forward(word_seq_tensor,word_mask_tensor,context_seq_tensor,context_mask_tensor) slot_loss,intent_loss=get_total_loss_func(dataloader,config,intent_logits,intent_tensor,slot_logits,tag_seq_tensor,tag_mask_tensor,intent_loss_fct,slot_loss_fct) val_slot_loss+=slot_loss.item()*num_data val_intent_loss+=intent_loss.item()*num_data for i in range(num_data): predicts=recover_intent(dataloader,intent_logits[i],slot_logits[i],tag_mask_tensor[i],batch_data[i][0],batch_data[i][-4]) labels=batch_data[i][3] predict_golden['overall'].append({'predict':predicts,'golden':labels}) predict_golden['intent'].append({'predict':[x for x in predicts if not is_slot_da(x)],'golden':[x for x in labels if not is_slot_da(x)]}) predict_golden['slot'].append({'predict':[x for x in predicts if is_slot_da(x)],'golden':[x for x in labels if is_slot_da(x)]}) for x in ['intent','slot','overall']: precision,recall,F1=get_score(predict_golden[x]) score_result[x]=[precision,recall,F1] print('-'*20+x+'-'*20) print('Precision:{},Recall:{},F1:{}'.format(precision,recall,F1)) avg_slot_loss=val_slot_loss/len(dataloader.data[data_key]) avg_intent_loss=val_intent_loss/len(dataloader.data[data_key]) print('val_slot_loss:{},val_intent_loss:{}'.format(avg_slot_loss,avg_intent_loss)) return avg_slot_loss,avg_intent_loss,score_result def predict_intent_slot(utterance:str,context:list,config,dataloader,model): # utterance: str, context: list model.eval() context_seq = dataloader.tokenizer.encode("[CLS] " + " [SEP] ".join(context[-config.max_history:])) ori_word_seq=dataloader.tokenizer.tokenize(utterance) ori_tag_seq = ["O"]*len(ori_word_seq) intents = [] da = [] word_seq,tag_seq,new2ori=ori_word_seq,ori_tag_seq,None batch_data=[[ori_word_seq,ori_tag_seq,intents,da,context_seq,new2ori,word_seq,dataloader.seq_tag2id(tag_seq),dataloader.seq_intent2id(intents)]] pad_batch=dataloader.pad_batch(batch_data) pad_batch=tuple(t.to(config.device) for t in pad_batch) word_seq_tensor,word_mask_tensor,tag_seq_tensor,tag_mask_tensor,intent_tensor,context_seq_tensor,context_mask_tensor=pad_batch with torch.no_grad(): slot_logits,intent_logits = model.forward(word_seq_tensor,word_mask_tensor,context_seq_tensor,context_mask_tensor) das=recover_intent(dataloader,intent_logits[0],slot_logits[0],tag_mask_tensor[0],batch_data[0][0],batch_data[0][-4]) return das def train(config,model,dataloader,slot_loss_fct,intent_loss_fct): print(config.device) bert_param_optimizer=list(model.bert.named_parameters()) bert_params=list(map(id,model.bert.parameters())) other_param_optimizer=[(n,p) for n,p in model.named_parameters() if id(p) not in bert_params] no_decay=['bias','LayerNorm.bias','LayerNorm.weight'] optimizer_grouped_parameters=[ {'params':[p for n,p in bert_param_optimizer if not any(nd in n for nd in no_decay)],'weight_decay':config.weight_decay,'lr':config.bert_learning_rate}, {'params':[p for n,p in bert_param_optimizer if any(nd in n for nd in no_decay)],'weight_decay':0,'lr':config.bert_learning_rate}, {'params':[p for n,p in other_param_optimizer if not any(nd in n for nd in no_decay)],'weight_decay':config.weight_decay,'lr':config.other_learning_rate}, {'params':[p for n,p in other_param_optimizer if any(nd in n for nd in no_decay)],'weight_decay':0,'lr':config.other_learning_rate}] optimizer=AdamW(optimizer_grouped_parameters,lr=config.learning_rate,eps=config.eps) scheduler=get_linear_schedule_with_warmup(optimizer,num_warmup_steps=config.warmup_steps,num_training_steps=config.max_step) train_slot_loss,train_intent_loss=0,0 best_dev_loss=float('inf') total_train_samples=0 for step in tqdm(range(1,config.max_step+1)): model.train() batched_data=dataloader.get_train_batch(config.batch_size) batched_data=tuple(item.to(config.device) for item in batched_data) word_seq_tensor,word_mask_tensor,tag_seq_tensor,tag_mask_tensor,intent_tensor,context_seq_tensor,context_mask_tensor=batched_data slot_logits,intent_logits=model.forward(word_seq_tensor,word_mask_tensor,context_seq_tensor,context_mask_tensor) slot_loss,intent_loss=get_total_loss_func(dataloader,config,intent_logits,intent_tensor,slot_logits,tag_seq_tensor,tag_mask_tensor,intent_loss_fct,slot_loss_fct) optimizer.zero_grad() total_loss=slot_loss+intent_loss total_loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(),1.0) optimizer.step() train_slot_loss+=slot_loss.item()*word_seq_tensor.size(0) train_intent_loss+=intent_loss.item()*word_seq_tensor.size(0) total_train_samples+=word_seq_tensor.size(0) scheduler.step() if step%config.check_step==0: train_slot_loss=train_slot_loss/total_train_samples train_intent_loss=train_intent_loss/total_train_samples print('current_step{}/total_steps{},train_slot_loss:{},train_intent_loss:{}'.format(step,config.max_step,train_slot_loss,train_intent_loss)) avg_slot_loss,avg_intent_loss,score_result=evaluate(config,model,dataloader,'val',slot_loss_fct,intent_loss_fct) avg_dev_loss=avg_slot_loss+avg_intent_loss if avg_dev_loss<best_dev_loss: best_dev_loss=avg_dev_loss torch.save(model.state_dict(),config.save_weight_path) print('model is saved to:{}'.format(config.save_weight_path)) """ train data: max sen bert_policy len 95 max context bert_policy len 183 dev data: max sen bert_policy len 48 max context bert_policy len 163 """ config=Model_Config() pretrained_weights='./hfl/chinese-bert-wwm-ext' file_dir='./crosswoz_data' tokenizer = BertTokenizer.from_pretrained(pretrained_weights) if not all([os.path.exists(config.train_data_path), os.path.exists(config.test_data_path), os.path.exists(config.dev_data_path), os.path.exists(config.intent_vocab_path), os.path.exists(config.tag_vocab_path)]): preprocess_data(file_dir=file_dir,tokenizer=tokenizer,include_sys=True) print('raw data was just successfully preprocessed') else: print('raw data has already been preprocessed before') dataloader=Dataloader(config.intent_vocab_path, config.tag_vocab_path, config.pretrained_weights, config.max_history) dataloader.load_data(config.train_data_path, "train", config.cut_sen_len) dataloader.load_data(config.dev_data_path, "val", config.cut_sen_len) if os.path.exists(config.save_model_path): model=torch.load(config.save_model_path,map_location=config.device) print('model trained from exist base model') else: model=JointWithBert(model_config=config, slot_dim=dataloader.tag_dim, intent_dim=dataloader.intent_dim) if os.path.exists(config.save_weight_path): model.load_state_dict(torch.load(config.save_weight_path)) print('model trained from exist base weight') else: print('model trained from scratch') if config.if_intent_weight: intent_loss_fct = torch.nn.BCEWithLogitsLoss(pos_weight=dataloader.intent_weight.to(config.device)) else: intent_loss_fct = torch.nn.BCEWithLogitsLoss() slot_loss_fct = torch.nn.CrossEntropyLoss() model.to(config.device) evaluate_sign=False if os.path.exists(config.save_weight_path) or os.path.exists(config.save_model_path): if evaluate_sign: avg_slot_loss,avg_intent_loss,score_result=evaluate(config,model,dataloader,'val',slot_loss_fct,intent_loss_fct) """ --------------------intent-------------------- Precision:0.9606143552311436,Recall:0.9696085955487337,F1:0.9650905202047209 --------------------slot-------------------- Precision:0.964492898579716,Recall:0.9147220641244546,F1:0.9389483933787731 --------------------overall-------------------- Precision:0.9629540243755279,Recall:0.9356862285278771,F1:0.9491243198239719 val_slot_loss:0.06734158956858625,val_intent_loss:0.002130140893944007 """ train_sign=False if train_sign: train(config,model,dataloader,slot_loss_fct,intent_loss_fct) train_sign=False if not train_sign: torch.save(model, config.save_model_path) utterance = "价格比较贵805元,评分是4.7分。" context = ["你好,帮我推荐一个能提供24小时热水和洗衣服务的高档型酒店,谢谢。","建议您去北京广电国际酒店。","行啊,北京广电国际酒店的价格贵吗?评分是多少呢?"] predict_intent_slot(utterance,context,config,dataloader,model) utterance = "".join(["行","啊",",","北京","广电","国际","酒店","的","价格","贵","吗","?","评分","是","多少","呢","?"]) context = ["你好,帮我推荐一个能提供24小时热水和洗衣服务的高档型酒店,谢谢。","建议您去北京广电国际酒店。"] predict_intent_slot(utterance,context,config,dataloader,model)
new_nlu_joint_with_bert/new_nlu_joint_with_bert.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python3 tensorflow==1.5 # language: python # name: tf15 # --- # # Chat 1on1 with any bot from IPython.core.display import display, HTML display(HTML("<style>.container { width:90% !important; }</style>")) import gpt_2_simple as gpt2 import os import requests name = 'george2' sess = gpt2.start_tf_sess() gpt2.load_gpt2(sess, run_name=name) # + k=50 p=.9 t=.7 max_history=2 start_token = '<|<PASSWORD>|>' history = [] while True: raw_text = input(">>> ") while not raw_text: raw_text = input(">>> ") #Append input to history history.append(raw_text) out_ids = gpt2.generate(sess, run_name=name, prefix=' '.join(history) + " " + start_token, truncate="<|endoftext|>", temperature=t, top_k=k, top_p=p, include_prefix=False, return_as_list=True) #Append output to history output = ' '.join(out_ids) output = output.split(start_token)[0] history.append(output) history = history[-(2*max_history+1):] print(output) # -
notebooks/Talk to bot.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: python3 # --- # # <NAME>ox # Use `admission_data.csv` for this exercise. # Load and view first few lines of dataset import pandas as pd import numpy as np % matplotlib inline df = pd.read_csv('admission_data.csv') df.head() # ### Proportion and admission rate for each gender # Proportion of students that are female count_genders = df.gender.value_counts() ratio_f = count_genders.female / (count_genders.female + count_genders.male) "proportion of female students = " + "{:2.3f}".format(ratio_f) # Proportion of students that are male count_genders = df.gender.value_counts() ratio_m = count_genders.male / (count_genders.female + count_genders.male) "proportion of male students = " + "{:2.3f}".format(ratio_m) # Admission rate for females admitted_f = (df[(df.gender == "female") & (df.admitted == True)]).count() admission_rate_f = admitted_f / count_genders.female "admission rate females = " + "{:2.3f}".format(admission_rate_f.major) # Admission rate for males admitted_m = (df[(df.gender == "male") & (df.admitted == True)]).count() admission_rate_m = admitted_m / count_genders.male "admission rate males = " + "{:2.3f}".format(admission_rate_m.major) # ### Proportion and admission rate for physics majors of each gender # What proportion of female students are majoring in physics? count_f_physics = df[(df.gender == "female") & (df.major == "Physics")].count() ratio_f_physics = count_f_physics / count_genders.female "ratio Physics females = " + "{:2.3f}".format(ratio_f_physics.major) # What proportion of male students are majoring in physics? count_m_physics = df[(df.gender == "male") & (df.major == "Physics")].count() ratio_m_physics = count_m_physics / count_genders.male "ratio Physics males = " + "{:2.3f}".format(ratio_m_physics.major) # Admission rate for female physics majors count_f_physics_admitted = df[(df.gender == "female") & (df.major == "Physics") & (df.admitted == True)].count() ratio_f_physics_admitted = count_f_physics_admitted / count_f_physics "ratio Physics female admitted = " + "{:2.3f}".format(ratio_f_physics_admitted.major) # Admission rate for male physics majors count_m_physics_admitted = df[(df.gender == "male") & (df.major == "Physics") & (df.admitted == True)].count() ratio_m_physics_admitted = count_m_physics_admitted / count_m_physics "ratio Physics male admitted = " + "{:2.3f}".format(ratio_m_physics_admitted.major) # ### Proportion and admission rate for chemistry majors of each gender # What proportion of female students are majoring in chemistry? count_f_chemistry = df[(df.gender == "female") & (df.major == "Chemistry")].count() ratio_f_chemistry = count_f_chemistry / count_genders.female "ratio Chemistry females = " + "{:2.3f}".format(ratio_f_chemistry.major) # What proportion of male students are majoring in chemistry? count_m_chemistry = df[(df.gender == "male") & (df.major == "Chemistry")].count() ratio_m_chemistry = count_m_chemistry / count_genders.male "ratio Chemistry males = " + "{:2.3f}".format(ratio_m_chemistry.major) # Admission rate for female chemistry majors count_f_chemistry_admitted = df[(df.gender == "female") & (df.major == "Chemistry") & (df.admitted == True)].count() ratio_f_chemistry_admitted = count_f_chemistry_admitted / count_f_chemistry "ratio Chemistry female admitted = " + "{:2.3f}".format(ratio_f_chemistry_admitted.major) # Admission rate for male chemistry majors count_m_chemistry_admitted = df[(df.gender == "male") & (df.major == "Chemistry") & (df.admitted == True)].count() ratio_m_chemistry_admitted = count_m_chemistry_admitted / count_m_chemistry "ratio Chemistry male admitted = " + "{:2.3f}".format(ratio_m_chemistry_admitted.major) # ### Admission rate for each major # Admission rate for physics majors count_physics = df[(df.major == "Physics")].count() count_physics_admitted = df[(df.major == "Physics") & (df.admitted == True)].count() ratio_physics_admissions = count_physics_admitted / count_physics.major "Admission rate Physics = " + "{:2.3f}".format(ratio_physics_admissions.major) # Admission rate for chemistry majors count_chemistry = df[(df.major == "Chemistry")].count() count_chemistry_admitted = df[(df.major == "Chemistry") & (df.admitted == True)].count() ratio_chemistry_admissions = count_chemistry_admitted / count_chemistry.major "Admission rate Chemistry = " + "{:2.3f}".format(ratio_chemistry_admissions.major)
stats_lessons/simpsons_paradox.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 import math # To understand time delay spectrometry (TDS) we need to understand the waveform which is used by TDS called a chirp. A chirp is a sinusoid that is constantly varying in frequency. The chirp is generated by integrating a varying angle step which is derived from an instantaneous frequency profile. This waveform generation procedure can be illustrated with a waveform simpler than a chirp--a complex sinusoid. We create a waveform which is three cycles of a complex sine wave using the same formulation that we will use for a chirp in a later notebook. The equation for a complex sinusoid is: $e^{(j2\pi ft)}$. We will derive the time domain values by summing angle increments. An overview of this technique is given [here](https://www.youtube.com/watch?v=RQplkt0bw_c). # # Instantaneous frequency is a topic central to this waveform generation. A good primer on instantaneous frequency is given in the [video](https://youtu.be/fqkLgJ0Czoc?t=90) for the time [1:30-4:44]. # + #We will use the sample rate from TDS_Introduction-sine_waves.ipynb #Assume we want to create a waveform that is 3 cycles of a 500 KHz sine wave. fs=16e6 total_cycles=3 f_sine_Hz=2e6 #The time for a single cycle is t_cycle_sec=1/f_sine_Hz #The time for the waveform is Tc_sec=t_cycle_sec*total_cycles samples_per_cycle=fs/f_sine_Hz ts=1/fs #This means we need to have the below number of samples to display the waveform total_samples= math.ceil(fs*Tc_sec) n = np.arange(0,total_samples, step=1, dtype=np.float64) #The time domain signal looks like t_sec=n*ts t_usec = t_sec *1e6 #This makes plotting easier #The instantaneous frequency is constant for all points in the waveform since it is a single sinusoid sine_instantaneous_freq_Hz=t_sec*0+f_sine_Hz sine_instantaneous_angular_freq_radPerSec=2*np.pi*sine_instantaneous_freq_Hz fig, ax = plt.subplots(1, 1) ax.plot(t_usec,sine_instantaneous_freq_Hz); ax.set_title('Instantaneous frequency of the sinusoid') ax.set_ylabel('frequency (Hz)') ax.set_xlabel('time ($\mu$sec)'); # + #Since frequency is a change in phase we can multiply it by the time step to find the amount #of phase change every step, which is fixed. sine_phase_step_rad=sine_instantaneous_angular_freq_radPerSec*ts fig, ax = plt.subplots(1, 1) ax.plot(t_usec,sine_phase_step_rad); ax.set_title('Phase increament of the sinusoid') ax.set_ylabel('phase (rad)') ax.set_xlabel('time ($\mu$sec)'); # + #The actual phase at each point in time is the summation of all the previous phase steps sine_phase_rad=np.cumsum(sine_phase_step_rad) fig, ax = plt.subplots(1,1) ax.plot(t_usec,sine_phase_rad,label='total phase'); ax.plot(t_usec,np.fmod(sine_phase_rad,2*np.pi),label='total phase bound between [0,2$\pi$]'); ax.set_title('Cummulative phase of a sinusoid') ax.set_ylabel('phase (rad)') ax.set_xlabel('time ($\mu$sec)') ax.legend() # + #We now take the complex exponential of the cumulative phase values to get the time domain complex exponential #with the correct number of cycles sine = np.exp(1j*sine_phase_rad) fig, ax = plt.subplots(1, 1) ax.plot(t_usec,np.real(sine),color='#27A4A3',label='real'); ax.plot(t_usec,np.imag(sine),color='#27A4A3',label='imag', linestyle=':'); ax.set_title('Complex exponential in the time domain') ax.set_xlabel('time ($\mu$sec)') ax.set_ylabel('amplitude') ax.legend(); # + #We now combine everything together and see fig, ax = plt.subplots(3, 1, sharex=True,figsize = [8, 7]) lns1=ax[0].plot(t_usec,sine_instantaneous_freq_Hz,linewidth=4, label='instantanous frequency'); ax[0].set_title('Comparing the instantaneous frequency and phase step') ax[0].set_ylabel('instantaneous frequency (Hz)') axt = ax[0].twinx() lns2=axt.plot(t_usec,sine_phase_step_rad,linewidth=2,color='black', linestyle=':', label='phase step'); axt.set_ylabel('phase step (rad)') #ref: https://stackoverflow.com/questions/5484922/secondary-axis-with-twinx-how-to-add-to-legend lns = lns1+lns2 labs = [l.get_label() for l in lns] ax[0].legend(lns, labs, loc=0) ax[1].plot(t_usec,sine_phase_rad,label='total phase'); ax[1].plot(t_usec,np.fmod(sine_phase_rad,2*np.pi),label='total phase bound between [0,2$\pi$]'); ax[1].set_title('Cummulative phase of a sinusoid') ax[1].set_ylabel('total phase (rad)') ax[1].legend() ax[2].plot(t_usec,np.real(sine),color='#27A4A3',label='real'); ax[2].plot(t_usec,np.imag(sine),color='#27A4A3',label='imag', linestyle=':'); ax[2].set_title('Complex exponential in the time domain') ax[2].set_xlabel('time ($\mu$sec)') ax[2].set_ylabel('amplitude') ax[2].legend(); # - #We now what to load this into GNURadio. So we will only write the raw file and then load that into GNURadio. This will cause the array size to be lost sine.astype('complex64').tofile('../data/TDS_Introduction_sine_waves_upper_complex64.bin') print(f'The sample rate is {int(fs)}') print(f'The samples per cycle is {samples_per_cycle}')
course/tds-200/week_01/notebooks/introduction_to_sine_waves_upper.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:drugcomp2] # language: python # name: conda-env-drugcomp2-py # --- # # Automated setup of mixtures # # We've been working on streamlining setup of simulations of arbitrary mixtures in AMBER/GROMACS/OpenMM and others for some of our own research. I thought I'd demo this really quick so you can get a feel for it and see if you're interested in contributing. It also allows quick setup and analysis of nontrivial liquid simulations, which can be a good opportunity to try out MDTraj and other analysis tools. # # *Before running the below*, you will need to have followed the [getting started instructions](https://github.com/MobleyLab/drug-computing/blob/master/uci-pharmsci/getting-started.md) for this course. # + from solvationtoolkit.solvated_mixtures import * #In this particular instance I'll just look at six solutes/solvent mixtures (not an all-by-all combination) which are pre-specified #solute names solutes = ['phenol', 'toluene', 'benzene', 'methane', 'ethanol', 'naphthalene'] #Solvent names solvents = ['cyclohexane', 'cyclohexane', 'cyclohexane', 'octanol', 'octanol', 'octanol'] #Number of solute/solvent molecules Nsolu = 3 Nsolv = 100 #Construct systems for idx in range( len( solutes) ): # Define new mixture mixture = MixtureSystem() # Add solute and solvent mixture.addComponent(name=solutes[idx], number=Nsolu) mixture.addComponent(name=solvents[idx], number=Nsolv) # Note you can optionally specify mole fraction instead, or a mix of numbers/mole fractions, etc. # Build system, including AMBER input files (but not GROMACS) mixture.build(amber=True, gromacs=True) # - # ## Let's try and see if we can do a quick visualization of one of the systems via mdtraj just to make sure it looks right # + #Import MDTraj import mdtraj as md #Load "trajectory" (structures) #You can load from either format (SolvationToolkit generates both) #traj = md.load( 'data/amber/phenol_cyclohexane_3_100.inpcrd', top = 'data/amber/phenol_cyclohexane_3_100.prmtop' ) traj = md.load( 'data/gromacs/phenol_cyclohexane_3_100.gro') #Input viewer import nglview #Set up view of structure view = nglview.show_mdtraj(traj) #Try some of the following to modify representations view.clear_representations() view.add_licorice('all') view.add_licorice('1-3', color = "blue") #For selection info, see http://arose.github.io/ngl/doc/#User_manual/Usage/Selection_language view.add_surface('1', opacity=0.3) view.add_surface('2, 3', color = 'red', opacity=0.3) #Show the view. Note that this needs to be the last command used to manipulate the view, i.e. if you modify the #representation after this, your view will be empty. view #VIEWER USAGE: # - Use your typical zoom command/gesture (i.e. pinch) to zoom in and out # - Click and drag to reorient # - Click on specific atoms/residues to find out details of what they are (and how they could be selected) # - # # Let's use a SMIRNOFF forcefield to parameterize the system, minimize, and run dynamics # # (This requires `openforcefield`, which you will have conda-installed if you've followed the getting started info.) # # First we handle imports # + # Import the SMIRNOFF forcefield engine and some useful tools from openforcefield.topology import Molecule, Topology from openforcefield.typing.engines.smirnoff import ForceField import openeye.oechem as oechem #Here we'll use OpenEye tookits, but RDKIt use is also possible # We use PDBFile to get OpenMM topologies from PDB files from simtk.openmm.app import PDBFile # We'll use OpenMM for simulations/minimization from simtk import openmm, unit from simtk.openmm import app # MDTraj for working with trajectories; time for timing import time import mdtraj # - # ## Now we handle assignment of force field parameters and generation of an OpenMM System # + # Specify names of molecules that are components of the system mol_filenames = ['phenol', 'cyclohexane'] # Load OEMols of components of system - SMIRNOFF requires OEMols of the components # and an OpenMM topology as input oemols = [] flavor = oechem.OEIFlavor_Generic_Default | oechem.OEIFlavor_MOL2_Default | oechem.OEIFlavor_MOL2_Forcefield #input flavor to use for reading mol2 files (so that it can understand GAFF atom names) # Loop over molecule files and load oemols for name in mol_filenames: mol = oechem.OEGraphMol() filename = 'data/monomers/'+name+'.mol2' ifs = oechem.oemolistream(filename) ifs.SetFlavor( oechem.OEFormat_MOL2, flavor) oechem.OEReadMolecule(ifs, mol ) oechem.OETriposAtomNames(mol) #Right now we have GAFF atom names, which OE doesn't like; reassign oemols.append(mol) ifs.close() # Build set of OpenFF mols from OE molecules OFFmols = [] for mol in oemols: OFFmols.append( Molecule.from_openeye(mol)) # Load OpenFF 1.0 force field, plus TIP3P water just in case we use it. ff = ForceField('openff-1.0.0.offxml', 'test_forcefields/tip3p.offxml') # Get OpenMM topology for mixture of phenol and cyclohexane from where SolvationToolkit created # it on disk pdbfile = PDBFile('data/packmol_boxes/phenol_cyclohexane_3_100.pdb') # Create OpenFF Topology off_topology = Topology.from_openmm(openmm_topology = pdbfile.topology, unique_molecules = OFFmols) # Assign SMIRNOFF parameters and create system system = ff.create_openmm_system( off_topology) # - # ## Finally we energy minimize and run dynamics # + # Set how many steps we'll run and other run parameters num_steps=10000 trj_freq = 100 #Trajectory output frequency data_freq = 100 #Energy/data output frequency temperature = 300*unit.kelvin #Temperature time_step = 2.*unit.femtoseconds friction = 1./unit.picosecond #Langevin friction constant # Bookkeeping -- if you run this more than once and perhaps encountered an exception, we need to make sure the reporter is closed try: reporter.close() except: pass # Set up integrator, platform for running simulation integrator = openmm.LangevinIntegrator(temperature, friction, time_step) platform = openmm.Platform.getPlatformByName('Reference') simulation = app.Simulation(pdbfile.topology, system, integrator) # Set positions, velocities simulation.context.setPositions(pdbfile.positions) simulation.context.setVelocitiesToTemperature(temperature) # Before doing dynamics, energy minimize (initial geometry will be strained) simulation.minimizeEnergy() # Set up reporter for output reporter = mdtraj.reporters.HDF5Reporter('mixture.h5', trj_freq) simulation.reporters=[] simulation.reporters.append(reporter) simulation.reporters.append(app.StateDataReporter('data.csv', data_freq, step=True, potentialEnergy=True, temperature=True, density=True)) # Run the dynamics print("Starting simulation") start = time.clock() simulation.step(num_steps) end = time.clock() print("Elapsed time %.2f seconds" % (end-start)) #netcdf_reporter.close() reporter.close() print("Done!") # - # ## Let's make a movie of our simulation # + import nglview traj=mdtraj.load('mixture.h5') view = nglview.show_mdtraj(traj) #Try some of the following to modify representations view.clear_representations() view.add_licorice('all') view.add_licorice('1-3', color = "blue") #For selection info, see http://arose.github.io/ngl/doc/#User_manual/Usage/Selection_language view.add_surface('1', opacity=0.3) view.add_surface('2, 3', color = 'red', opacity=0.3) view #Note that if you view a movie and keep it playing, your notebook will run a hair slow... # - # ## Other possibly interesting things to try: # * Find the average distance from phenol to phenol # * Calculate the density or volume of the system # * etc. # # (Drawing on MDTraj - see docs online) # + # Use this box to try additional things
uci-pharmsci/lectures/SMIRNOFF_simulations/mixture_simulations.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 # --- # # NetsurfP pipeline # Intention is to take a list of mutations and # make a file for netsurfp # # for each of the mutations # - check whether ENST or Uniprot # - for ENST # - get the ENST codes # - for Uniprot - get the ENSTs first # - then get the codes # - check that the wild is where it should be and if so # - add to the list of ENSTs # - construct the section to add to the file for netsurfp # - add to the file # # split the file into files of a reasonable length # Do the same for all the ENSTs in the list # # call netsurfp with each of the files - saving them to somewhere sensible # change each of the responses into a csv file. # # Concatenate the csv files into two - one for the mutations and one for the wild ENSTs # # for each of the mutations take out the right line from the mutations and from the wild ENSTs # # + import pandas as pd import json import re import sys import subprocess # - import os # + ENST_codes = get_ENST_codes() ENST_Uniprot = get_ENST_Uniprot() # - def get_ENST_codes(): with open(os.path.abspath('./data/ENST_codes.json'), 'r') as file: return json.load(file) def get_ENST_Uniprot(): return pd.DataFrame.from_csv(os.path.abspath('./data/ENST_Uniprot.csv')) def clean_directories(): subprocess.Popen(['rm','-rf', os.path.abspath('./temp_questions/')]) subprocess.Popen(['mkdir', 'temp_questions']) subprocess.Popen(['rm','-rf', os.path.abspath('./temp_answers/')]) subprocess.Popen(['mkdir', 'temp_answers']) def Split(string,n): """Split a string into lines of length n with \n in between them""" N =len(string)//n return '\n'.join([string[i*n:(i+1)*n] for i in range(N)]+[string[N*n:]]) class Mut: def __init__(self,mut): self.mut = mut self.messages = {'ok':(True,'no problems encountered' ), 'no ENST':(False,'no ENSTs correspond to this Uniprot code'), 'too short':(False, "none of the corresponding codes were long enough to encorporate this "+ "mutation"), 'wrong wild type': (False, "whilst at least one of the corresponding codes was long enough to"+ "encorporate this mutation the AA did not correspond to the wild type given") } parts = mut.split('_') self.name = parts[0] self.mutation = parts[1] self.wild = self.mutation[0] self.change = self.mutation[-1] self.pos = int(self.mutation[1:-1]) self.valid,self.ENSTs = self.get_ENSTs() self.valid,self.ENST,self.wild_code = self.get_code() self.mutant_code = self.mutate_code() def get_ENSTs(self): i=self.name if i[:4]=='ENST': return [i] elif i in set(ENST_Uniprot['UniProtKB/Swiss-Prot ID']): Uni = 'UniProtKB/Swiss-Prot ID' elif i in set(ENST_Uniprot['UniProtKB/TrEMBL ID']): Uni = 'UniProtKB/TrEMBL ID' else: return (self.messages['no ENST'],'') return (self.messages['ok'],list(ENST_Uniprot[ENST_Uniprot[Uni]==i].index)) def get_code(self): length_ok = False pos_ok = False codes = [ENST_codes.get(m,'') for m in self.ENSTs] C = len(codes) for i in range(C): if len(codes[i])>=self.pos: length_ok = True if codes[i][self.pos-1]==self.wild: pos_ok = True return (self.messages['ok'],self.ENSTs[i],codes[i]) if not length_ok: return (self.messages['too short'],'','') else: return (self.messages['wrong wild type'],'','') def mutate_code(self): return self.wild_code[:self.pos-1]+self.change+self.wild_code[self.pos:] def for_printing(self): return ('>{0}_{1}'.format(self.ENST,self.mut),Split(self.mutant_code,61)) self = Mut('P00519_M244V') def main(): ENST_codes = get_ENST_codes() print('got ENST codes') ENST_Uniprot = get_ENST_Uniprot() print('got ENST Uniprot') clean_directories() print('directories cleaned') file_number = make_NetSurfP_query() print('queries made') do_netsurfp(file_number) print('netsurfp completed') Questions = [q+'.fsa' for q in os.listdir('./temp_questions') if 'json' not in q] for q in os.listdir('./temp_questions'): if 'json' not in q: p=subprocess.Popen(['cp','./temp_questions/'+q,'./temp_questions/'+q+'.fsa']) p.communicate() for i in range(7566): if 'questions{}.fsa'.format(i) not in os.listdir('./temp_questions'): print ('number {} is not there'.format(i)) len(Questions) mokca = pd.DataFrame.from_csv('~/Downloads/MoKCA.csv') mokca.size codes = [mokca.index[i].strip()+'_'+mokca.ix[i]['Substitution'] for i in range(mokca.size)] with open('./data/codes.txt','w') as file: file.write('') with open('./data/codes.txt','a') as file: for f in codes: file.write(f+'\n') codes[:10] def make_NetSurfP_query(): muts = get_query() mutations =[Mut(l) for l in muts] validity = dict(zip([m.name for m in mutations],[m.valid for m in mutations])) for_printing = [m.for_printing() for m in mutations] temp_lists = dont_exceed_max(10000,for_printing) make_questions('./temp_questions/','questions', temp_lists) mutations_listed=[[i[0] for i in j] for j in temp_lists] fine, too_short,wrong_wild = split_validity(validity) query = {'fine':fine, 'too short': too_short, 'wrong wild': wrong_wild, 'mutations for netsurfp': mutations_listed} with open('./temp_answers/query.json','w') as file: json.dump(query,file) return len(temp_lists) def split_validity(validity): too_short=[] wrong_wild=[] fine = [] for v in validity: a,b = validity[v] if a: fine.append(v) elif b=='none of the corresponding codes were long enough to encorporate this mutation': too_short.append(v) else: wrong_wild.append(v) def make_questions(pathname, filename, temp_lists): for t in range(len(temp_lists)): name = pathname+filename+str(t)+'.fsa' with open(name,'w') as file: file.write('') with open(name,'a') as file: for i in temp_lists[t]: a,b = i file.write(a+'\n') file.write(b+'\n') def do_netsurfp(file_number): for j in range(file_number): input_file = 'temp_questions/questions{}.fsa'.format(j) output_file = 'temp_answers/answers{}.rsa'.format(j) p = subprocess.Popen(['netsurfp', '-i',input_file, '-o', output_file]) p.communicate() print('{} completed'.format(j)) mutations_listed=[[i[0] for i in j] for j in temp_lists] mutations_listed[0] muts = get_query() mutations =[Mut(l) for l in muts] validity = dict(zip([m.name for m in mutations],[m.valid for m in mutations])) for_printing = [m.for_printing() for m in mutations] temp_lists = dont_exceed_max(10000,for_printing) f[:2] os.listdir() os.system("netsurfp -h") # + subprocess.Popen(['netsurfp','-i','./temp_questions/questions0','-o','./temp_answers/answers']) # - fine, too_short,wrong_wild = split_validity(validity) subprocess.Popen(['pwd']) validity = make_NetSurfP_query() def get_query(): print('To use this program you need to supply a file with a list of mutation codes\n', 'These codes should be in the form of identifier_M244V where here\n', 'M is the wild type 244 is the position and V is the mutant amino acid\n', 'Your file should contain one mutation code per line and no other information\n') query_file = input('please type the full path of the file that contains your mutation codes here without quotations marks') try: with open(query_file,'r') as file: tmp = file.readlines() print('Your query has been found') return [t.strip('\n') for t in tmp] except FileNotFoundError: print('file not found, quit and try again') return [] def dont_exceed_max(Max,code_list): C = len(code_list) temp_list=[] for_inclusion=[] limit = 0 for i in range(C): a,b = code_list[i] B = len(b) if limit+B<Max: for_inclusion.append(code_list[i]) limit+=B else: temp_list.append(for_inclusion) limit=B for_inclusion=[code_list[i]] temp_list.append(for_inclusion) return temp_list # + muts = get_query() mutations =[Mut(l) for l in muts] Validity = dict(zip([m.name for m in mutations],[m.valid for m in mutations])) for_printing = [m.for_printing() for m in mutations] # - temp_lists = dont_exceed_max(100000,for_printing) temp_lists[0] self.for_printing() # bit of codes to give me something to play with # + codes = pd.DataFrame.from_csv('OGvNeutral.csv') codes['codes'] = codes['Uniprot ID']+'_'+codes['Substitution'] L = list(codes['codes']) L1 = [i for i in L if type(i)==str] with open('./data/codes.txt','w') as file: file.write('') with open('./data/codes.txt','a') as file: for l in L1: file.write(l+'\n') # - def for_printing[:10] self.mutant_code[243] self.ENST self.code
Using_NetSurfP/NetsurfP pipeline.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # + [markdown] origin_pos=0 # # Linear Regression # :label:`sec_linear_regression` # # *Regression* refers to a set of methods for modeling # the relationship between one or more independent variables # and a dependent variable. # In the natural sciences and social sciences, # the purpose of regression is most often to # *characterize* the relationship between the inputs and outputs. # Machine learning, on the other hand, # is most often concerned with *prediction*. # # Regression problems pop up whenever we want to predict a numerical value. # Common examples include predicting prices (of homes, stocks, etc.), # predicting length of stay (for patients in the hospital), # demand forecasting (for retail sales), among countless others. # Not every prediction problem is a classic regression problem. # In subsequent sections, we will introduce classification problems, # where the goal is to predict membership among a set of categories. # # # ## Basic Elements of Linear Regression # # *Linear regression* may be both the simplest # and most popular among the standard tools to regression. # Dating back to the dawn of the 19th century, # linear regression flows from a few simple assumptions. # First, we assume that the relationship between # the independent variables $\mathbf{x}$ and the dependent variable $y$ is linear, # i.e., that $y$ can be expressed as a weighted sum # of the elements in $\mathbf{x}$, # given some noise on the observations. # Second, we assume that any noise is well-behaved # (following a Gaussian distribution). # # To motivate the approach, let us start with a running example. # Suppose that we wish to estimate the prices of houses (in dollars) # based on their area (in square feet) and age (in years). # To actually develop a model for predicting house prices, # we would need to get our hands on a dataset # consisting of sales for which we know # the sale price, area, and age for each home. # In the terminology of machine learning, # the dataset is called a *training dataset* or *training set*, # and each row (here the data corresponding to one sale) # is called an *example* (or *data point*, *data instance*, *sample*). # The thing we are trying to predict (price) # is called a *label* (or *target*). # The independent variables (age and area) # upon which the predictions are based # are called *features* (or *covariates*). # # Typically, we will use $n$ to denote # the number of examples in our dataset. # We index the data examples by $i$, denoting each input # as $\mathbf{x}^{(i)} = [x_1^{(i)}, x_2^{(i)}]^\top$ # and the corresponding label as $y^{(i)}$. # # # ### Linear Model # :label:`subsec_linear_model` # # The linearity assumption just says that the target (price) # can be expressed as a weighted sum of the features (area and age): # # $$\mathrm{price} = w_{\mathrm{area}} \cdot \mathrm{area} + w_{\mathrm{age}} \cdot \mathrm{age} + b.$$ # :eqlabel:`eq_price-area` # # In :eqref:`eq_price-area`, $w_{\mathrm{area}}$ and $w_{\mathrm{age}}$ # are called *weights*, and $b$ is called a *bias* # (also called an *offset* or *intercept*). # The weights determine the influence of each feature # on our prediction and the bias just says # what value the predicted price should take # when all of the features take value 0. # Even if we will never see any homes with zero area, # or that are precisely zero years old, # we still need the bias or else we will # limit the expressivity of our model. # Strictly speaking, :eqref:`eq_price-area` is an *affine transformation* # of input features, # which is characterized by # a *linear transformation* of features via weighted sum, combined with # a *translation* via the added bias. # # Given a dataset, our goal is to choose # the weights $\mathbf{w}$ and the bias $b$ such that on average, # the predictions made according to our model # best fit the true prices observed in the data. # Models whose output prediction # is determined by the affine transformation of input features # are *linear models*, # where the affine transformation is specified by the chosen weights and bias. # # # In disciplines where it is common to focus # on datasets with just a few features, # explicitly expressing models long-form like this is common. # In machine learning, we usually work with high-dimensional datasets, # so it is more convenient to employ linear algebra notation. # When our inputs consist of $d$ features, # we express our prediction $\hat{y}$ (in general the "hat" symbol denotes estimates) as # # $$\hat{y} = w_1 x_1 + ... + w_d x_d + b.$$ # # Collecting all features into a vector $\mathbf{x} \in \mathbb{R}^d$ # and all weights into a vector $\mathbf{w} \in \mathbb{R}^d$, # we can express our model compactly using a dot product: # # $$\hat{y} = \mathbf{w}^\top \mathbf{x} + b.$$ # :eqlabel:`eq_linreg-y` # # In :eqref:`eq_linreg-y`, the vector $\mathbf{x}$ corresponds to features of a single data example. # We will often find it convenient # to refer to features of our entire dataset of $n$ examples # via the *design matrix* $\mathbf{X} \in \mathbb{R}^{n \times d}$. # Here, $\mathbf{X}$ contains one row for every example # and one column for every feature. # # For a collection of features $\mathbf{X}$, # the predictions $\hat{\mathbf{y}} \in \mathbb{R}^n$ # can be expressed via the matrix-vector product: # # $${\hat{\mathbf{y}}} = \mathbf{X} \mathbf{w} + b,$$ # # where broadcasting (see :numref:`subsec_broadcasting`) is applied during the summation. # Given features of a training dataset $\mathbf{X}$ # and corresponding (known) labels $\mathbf{y}$, # the goal of linear regression is to find # the weight vector $\mathbf{w}$ and the bias term $b$ # that given features of a new data example # sampled from the same distribution as $\mathbf{X}$, # the new example's label will (in expectation) be predicted with the lowest error. # # # Even if we believe that the best model for # predicting $y$ given $\mathbf{x}$ is linear, # we would not expect to find a real-world dataset of $n$ examples where # $y^{(i)}$ exactly equals $\mathbf{w}^\top \mathbf{x}^{(i)}+b$ # for all $1 \leq i \leq n$. # For example, whatever instruments we use to observe # the features $\mathbf{X}$ and labels $\mathbf{y}$ # might suffer small amount of measurement error. # Thus, even when we are confident # that the underlying relationship is linear, # we will incorporate a noise term to account for such errors. # # Before we can go about searching for the best *parameters* (or *model parameters*) $\mathbf{w}$ and $b$, # we will need two more things: # (i) a quality measure for some given model; # and (ii) a procedure for updating the model to improve its quality. # # # ### Loss Function # # Before we start thinking about how to *fit* data with our model, # we need to determine a measure of *fitness*. # The *loss function* quantifies the distance # between the *real* and *predicted* value of the target. # The loss will usually be a non-negative number # where smaller values are better # and perfect predictions incur a loss of 0. # The most popular loss function in regression problems # is the squared error. # When our prediction for an example $i$ is $\hat{y}^{(i)}$ # and the corresponding true label is $y^{(i)}$, # the squared error is given by: # # $$l^{(i)}(\mathbf{w}, b) = \frac{1}{2} \left(\hat{y}^{(i)} - y^{(i)}\right)^2.$$ # :eqlabel:`eq_mse` # # The constant $\frac{1}{2}$ makes no real difference # but will prove notationally convenient, # canceling out when we take the derivative of the loss. # Since the training dataset is given to us, and thus out of our control, # the empirical error is only a function of the model parameters. # To make things more concrete, consider the example below # where we plot a regression problem for a one-dimensional case # as shown in :numref:`fig_fit_linreg`. # # ![Fit data with a linear model.](../img/fit-linreg.svg) # :label:`fig_fit_linreg` # # Note that large differences between # estimates $\hat{y}^{(i)}$ and observations $y^{(i)}$ # lead to even larger contributions to the loss, # due to the quadratic dependence. # To measure the quality of a model on the entire dataset of $n$ examples, # we simply average (or equivalently, sum) # the losses on the training set. # # $$L(\mathbf{w}, b) =\frac{1}{n}\sum_{i=1}^n l^{(i)}(\mathbf{w}, b) =\frac{1}{n} \sum_{i=1}^n \frac{1}{2}\left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right)^2.$$ # # When training the model, we want to find parameters ($\mathbf{w}^*, b^*$) # that minimize the total loss across all training examples: # # $$\mathbf{w}^*, b^* = \operatorname*{argmin}_{\mathbf{w}, b}\ L(\mathbf{w}, b).$$ # # # ### Analytic Solution # # Linear regression happens to be an unusually simple optimization problem. # Unlike most other models that we will encounter in this book, # linear regression can be solved analytically by applying a simple formula. # To start, we can subsume the bias $b$ into the parameter $\mathbf{w}$ # by appending a column to the design matrix consisting of all ones. # Then our prediction problem is to minimize $\|\mathbf{y} - \mathbf{X}\mathbf{w}\|^2$. # There is just one critical point on the loss surface # and it corresponds to the minimum of the loss over the entire domain. # Taking the derivative of the loss with respect to $\mathbf{w}$ # and setting it equal to zero yields the analytic (closed-form) solution: # # $$\mathbf{w}^* = (\mathbf X^\top \mathbf X)^{-1}\mathbf X^\top \mathbf{y}.$$ # # While simple problems like linear regression # may admit analytic solutions, # you should not get used to such good fortune. # Although analytic solutions allow for nice mathematical analysis, # the requirement of an analytic solution is so restrictive # that it would exclude all of deep learning. # # # ### Minibatch Stochastic Gradient Descent # # Even in cases where we cannot solve the models analytically, # it turns out that we can still train models effectively in practice. # Moreover, for many tasks, those difficult-to-optimize models # turn out to be so much better that figuring out how to train them # ends up being well worth the trouble. # # The key technique for optimizing nearly any deep learning model, # and which we will call upon throughout this book, # consists of iteratively reducing the error # by updating the parameters in the direction # that incrementally lowers the loss function. # This algorithm is called *gradient descent*. # # The most naive application of gradient descent # consists of taking the derivative of the loss function, # which is an average of the losses computed # on every single example in the dataset. # In practice, this can be extremely slow: # we must pass over the entire dataset before making a single update. # Thus, we will often settle for sampling a random minibatch of examples # every time we need to compute the update, # a variant called *minibatch stochastic gradient descent*. # # In each iteration, we first randomly sample a minibatch $\mathcal{B}$ # consisting of a fixed number of training examples. # We then compute the derivative (gradient) of the average loss # on the minibatch with regard to the model parameters. # Finally, we multiply the gradient by a predetermined positive value $\eta$ # and subtract the resulting term from the current parameter values. # # We can express the update mathematically as follows # ($\partial$ denotes the partial derivative): # # $$(\mathbf{w},b) \leftarrow (\mathbf{w},b) - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} \partial_{(\mathbf{w},b)} l^{(i)}(\mathbf{w},b).$$ # # # To summarize, steps of the algorithm are the following: # (i) we initialize the values of the model parameters, typically at random; # (ii) we iteratively sample random minibatches from the data, # updating the parameters in the direction of the negative gradient. # For quadratic losses and affine transformations, # we can write this out explicitly as follows: # # $$\begin{aligned} \mathbf{w} &\leftarrow \mathbf{w} - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} \partial_{\mathbf{w}} l^{(i)}(\mathbf{w}, b) = \mathbf{w} - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} \mathbf{x}^{(i)} \left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right),\\ b &\leftarrow b - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} \partial_b l^{(i)}(\mathbf{w}, b) = b - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} \left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right). \end{aligned}$$ # :eqlabel:`eq_linreg_batch_update` # # # Note that $\mathbf{w}$ and $\mathbf{x}$ are vectors in :eqref:`eq_linreg_batch_update`. # Here, the more elegant vector notation makes the math # much more readable than expressing things in terms of coefficients, # say $w_1, w_2, \ldots, w_d$. # The set cardinality # $|\mathcal{B}|$ represents # the number of examples in each minibatch (the *batch size*) # and $\eta$ denotes the *learning rate*. # We emphasize that the values of the batch size and learning rate # are manually pre-specified and not typically learned through model training. # These parameters that are tunable but not updated # in the training loop are called *hyperparameters*. # *Hyperparameter tuning* is the process by which hyperparameters are chosen, # and typically requires that we adjust them # based on the results of the training loop # as assessed on a separate *validation dataset* (or *validation set*). # # After training for some predetermined number of iterations # (or until some other stopping criteria are met), # we record the estimated model parameters, # denoted $\hat{\mathbf{w}}, \hat{b}$. # Note that even if our function is truly linear and noiseless, # these parameters will not be the exact minimizers of the loss # because, although the algorithm converges slowly towards the minimizers # it cannot achieve it exactly in a finite number of steps. # # Linear regression happens to be a learning problem where there is only one minimum # over the entire domain. # However, for more complicated models, like deep networks, # the loss surfaces contain many minima. # Fortunately, for reasons that are not yet fully understood, # deep learning practitioners seldom struggle to find parameters # that minimize the loss *on training sets*. # The more formidable task is to find parameters # that will achieve low loss on data # that we have not seen before, # a challenge called *generalization*. # We return to these topics throughout the book. # # # ### Making Predictions with the Learned Model # # # Given the learned linear regression model # $\hat{\mathbf{w}}^\top \mathbf{x} + \hat{b}$, # we can now estimate the price of a new house # (not contained in the training data) # given its area $x_1$ and age $x_2$. # Estimating targets given features is # commonly called *prediction* or *inference*. # # We will try to stick with *prediction* because # calling this step *inference*, # despite emerging as standard jargon in deep learning, # is somewhat of a misnomer. # In statistics, *inference* more often denotes # estimating parameters based on a dataset. # This misuse of terminology is a common source of confusion # when deep learning practitioners talk to statisticians. # # # ## Vectorization for Speed # # When training our models, we typically want to process # whole minibatches of examples simultaneously. # Doing this efficiently requires that (**we**) (~~should~~) (**vectorize the calculations # and leverage fast linear algebra libraries # rather than writing costly for-loops in Python.**) # # + origin_pos=3 tab=["tensorflow"] # %matplotlib inline import math import time import numpy as np import tensorflow as tf from d2l import tensorflow as d2l # + [markdown] origin_pos=4 # To illustrate why this matters so much, # we can (**consider two methods for adding vectors.**) # To start we instantiate two 10000-dimensional vectors # containing all ones. # In one method we will loop over the vectors with a Python for-loop. # In the other method we will rely on a single call to `+`. # # + origin_pos=5 tab=["tensorflow"] n = 10000 a = tf.ones(n) b = tf.ones(n) # + [markdown] origin_pos=6 # Since we will benchmark the running time frequently in this book, # [**let us define a timer**]. # # + origin_pos=7 tab=["tensorflow"] class Timer: #@save """Record multiple running times.""" def __init__(self): self.times = [] self.start() def start(self): """Start the timer.""" self.tik = time.time() def stop(self): """Stop the timer and record the time in a list.""" self.times.append(time.time() - self.tik) return self.times[-1] def avg(self): """Return the average time.""" return sum(self.times) / len(self.times) def sum(self): """Return the sum of time.""" return sum(self.times) def cumsum(self): """Return the accumulated time.""" return np.array(self.times).cumsum().tolist() # + [markdown] origin_pos=8 # Now we can benchmark the workloads. # First, [**we add them, one coordinate at a time, # using a for-loop.**] # # + origin_pos=10 tab=["tensorflow"] c = tf.Variable(tf.zeros(n)) timer = Timer() for i in range(n): c[i].assign(a[i] + b[i]) f'{timer.stop():.5f} sec' # + [markdown] origin_pos=11 # (**Alternatively, we rely on the reloaded `+` operator to compute the elementwise sum.**) # # + origin_pos=12 tab=["tensorflow"] timer.start() d = a + b f'{timer.stop():.5f} sec' # + [markdown] origin_pos=13 # You probably noticed that the second method # is dramatically faster than the first. # Vectorizing code often yields order-of-magnitude speedups. # Moreover, we push more of the mathematics to the library # and need not write as many calculations ourselves, # reducing the potential for errors. # # ## The Normal Distribution and Squared Loss # :label:`subsec_normal_distribution_and_squared_loss` # # While you can already get your hands dirty using only the information above, # in the following we can more formally motivate the squared loss objective # via assumptions about the distribution of noise. # # Linear regression was invented by Gauss in 1795, # who also discovered the normal distribution (also called the *Gaussian*). # It turns out that the connection between # the normal distribution and linear regression # runs deeper than common parentage. # To refresh your memory, the probability density # of a normal distribution with mean $\mu$ and variance $\sigma^2$ (standard deviation $\sigma$) # is given as # # $$p(x) = \frac{1}{\sqrt{2 \pi \sigma^2}} \exp\left(-\frac{1}{2 \sigma^2} (x - \mu)^2\right).$$ # # Below [**we define a Python function to compute the normal distribution**]. # # + origin_pos=14 tab=["tensorflow"] def normal(x, mu, sigma): p = 1 / math.sqrt(2 * math.pi * sigma**2) return p * np.exp(-0.5 / sigma**2 * (x - mu)**2) # + [markdown] origin_pos=15 # We can now (**visualize the normal distributions**). # # + origin_pos=16 tab=["tensorflow"] # Use numpy again for visualization x = np.arange(-7, 7, 0.01) # Mean and standard deviation pairs params = [(0, 1), (0, 2), (3, 1)] d2l.plot(x, [normal(x, mu, sigma) for mu, sigma in params], xlabel='x', ylabel='p(x)', figsize=(4.5, 2.5), legend=[f'mean {mu}, std {sigma}' for mu, sigma in params]) # + [markdown] origin_pos=17 # As we can see, changing the mean corresponds to a shift along the $x$-axis, # and increasing the variance spreads the distribution out, lowering its peak. # # One way to motivate linear regression with the mean squared error loss function (or simply squared loss) # is to formally assume that observations arise from noisy observations, # where the noise is normally distributed as follows: # # $$y = \mathbf{w}^\top \mathbf{x} + b + \epsilon \text{ where } \epsilon \sim \mathcal{N}(0, \sigma^2).$$ # # Thus, we can now write out the *likelihood* # of seeing a particular $y$ for a given $\mathbf{x}$ via # # $$P(y \mid \mathbf{x}) = \frac{1}{\sqrt{2 \pi \sigma^2}} \exp\left(-\frac{1}{2 \sigma^2} (y - \mathbf{w}^\top \mathbf{x} - b)^2\right).$$ # # Now, according to the principle of maximum likelihood, # the best values of parameters $\mathbf{w}$ and $b$ are those # that maximize the *likelihood* of the entire dataset: # # $$P(\mathbf y \mid \mathbf X) = \prod_{i=1}^{n} p(y^{(i)}|\mathbf{x}^{(i)}).$$ # # Estimators chosen according to the principle of maximum likelihood # are called *maximum likelihood estimators*. # While, maximizing the product of many exponential functions, # might look difficult, # we can simplify things significantly, without changing the objective, # by maximizing the log of the likelihood instead. # For historical reasons, optimizations are more often expressed # as minimization rather than maximization. # So, without changing anything we can minimize the *negative log-likelihood* # $-\log P(\mathbf y \mid \mathbf X)$. # Working out the mathematics gives us: # # $$-\log P(\mathbf y \mid \mathbf X) = \sum_{i=1}^n \frac{1}{2} \log(2 \pi \sigma^2) + \frac{1}{2 \sigma^2} \left(y^{(i)} - \mathbf{w}^\top \mathbf{x}^{(i)} - b\right)^2.$$ # # Now we just need one more assumption that $\sigma$ is some fixed constant. # Thus we can ignore the first term because # it does not depend on $\mathbf{w}$ or $b$. # Now the second term is identical to the squared error loss introduced earlier, # except for the multiplicative constant $\frac{1}{\sigma^2}$. # Fortunately, the solution does not depend on $\sigma$. # It follows that minimizing the mean squared error # is equivalent to maximum likelihood estimation # of a linear model under the assumption of additive Gaussian noise. # # ## From Linear Regression to Deep Networks # # So far we only talked about linear models. # While neural networks cover a much richer family of models, # we can begin thinking of the linear model # as a neural network by expressing it in the language of neural networks. # To begin, let us start by rewriting things in a "layer" notation. # # ### Neural Network Diagram # # Deep learning practitioners like to draw diagrams # to visualize what is happening in their models. # In :numref:`fig_single_neuron`, # we depict our linear regression model as a neural network. # Note that these diagrams highlight the connectivity pattern # such as how each input is connected to the output, # but not the values taken by the weights or biases. # # ![Linear regression is a single-layer neural network.](../img/singleneuron.svg) # :label:`fig_single_neuron` # # For the neural network shown in :numref:`fig_single_neuron`, # the inputs are $x_1, \ldots, x_d$, # so the *number of inputs* (or *feature dimensionality*) in the input layer is $d$. # The output of the network in :numref:`fig_single_neuron` is $o_1$, # so the *number of outputs* in the output layer is 1. # Note that the input values are all *given* # and there is just a single *computed* neuron. # Focusing on where computation takes place, # conventionally we do not consider the input layer when counting layers. # That is to say, # the *number of layers* for the neural network in :numref:`fig_single_neuron` is 1. # We can think of linear regression models as neural networks # consisting of just a single artificial neuron, # or as single-layer neural networks. # # Since for linear regression, every input is connected # to every output (in this case there is only one output), # we can regard this transformation (the output layer in :numref:`fig_single_neuron`) # as a *fully-connected layer* or *dense layer*. # We will talk a lot more about networks composed of such layers # in the next chapter. # # # ### Biology # # Since linear regression (invented in 1795) # predates computational neuroscience, # it might seem anachronistic to describe # linear regression as a neural network. # To see why linear models were a natural place to begin # when the cyberneticists/neurophysiologists # <NAME> and <NAME> began to develop # models of artificial neurons, # consider the cartoonish picture # of a biological neuron in :numref:`fig_Neuron`, consisting of # *dendrites* (input terminals), # the *nucleus* (CPU), the *axon* (output wire), # and the *axon terminals* (output terminals), # enabling connections to other neurons via *synapses*. # # ![The real neuron.](../img/neuron.svg) # :label:`fig_Neuron` # # Information $x_i$ arriving from other neurons # (or environmental sensors such as the retina) # is received in the dendrites. # In particular, that information is weighted by *synaptic weights* $w_i$ # determining the effect of the inputs # (e.g., activation or inhibition via the product $x_i w_i$). # The weighted inputs arriving from multiple sources # are aggregated in the nucleus as a weighted sum $y = \sum_i x_i w_i + b$, # and this information is then sent for further processing in the axon $y$, # typically after some nonlinear processing via $\sigma(y)$. # From there it either reaches its destination (e.g., a muscle) # or is fed into another neuron via its dendrites. # # Certainly, the high-level idea that many such units # could be cobbled together with the right connectivity # and right learning algorithm, # to produce far more interesting and complex behavior # than any one neuron alone could express # owes to our study of real biological neural systems. # # At the same time, most research in deep learning today # draws little direct inspiration in neuroscience. # We invoke <NAME> and <NAME> who, # in their classic AI text book # *Artificial Intelligence: A Modern Approach* :cite:`Russell.Norvig.2016`, # pointed out that although airplanes might have been *inspired* by birds, # ornithology has not been the primary driver # of aeronautics innovation for some centuries. # Likewise, inspiration in deep learning these days # comes in equal or greater measure from mathematics, # statistics, and computer science. # # ## Summary # # * Key ingredients in a machine learning model are training data, a loss function, an optimization algorithm, and quite obviously, the model itself. # * Vectorizing makes everything better (mostly math) and faster (mostly code). # * Minimizing an objective function and performing maximum likelihood estimation can mean the same thing. # * Linear regression models are neural networks, too. # # # ## Exercises # # 1. Assume that we have some data $x_1, \ldots, x_n \in \mathbb{R}$. Our goal is to find a constant $b$ such that $\sum_i (x_i - b)^2$ is minimized. # 1. Find a analytic solution for the optimal value of $b$. # 1. How does this problem and its solution relate to the normal distribution? # 1. Derive the analytic solution to the optimization problem for linear regression with squared error. To keep things simple, you can omit the bias $b$ from the problem (we can do this in principled fashion by adding one column to $\mathbf X$ consisting of all ones). # 1. Write out the optimization problem in matrix and vector notation (treat all the data as a single matrix, and all the target values as a single vector). # 1. Compute the gradient of the loss with respect to $w$. # 1. Find the analytic solution by setting the gradient equal to zero and solving the matrix equation. # 1. When might this be better than using stochastic gradient descent? When might this method break? # 1. Assume that the noise model governing the additive noise $\epsilon$ is the exponential distribution. That is, $p(\epsilon) = \frac{1}{2} \exp(-|\epsilon|)$. # 1. Write out the negative log-likelihood of the data under the model $-\log P(\mathbf y \mid \mathbf X)$. # 1. Can you find a closed form solution? # 1. Suggest a stochastic gradient descent algorithm to solve this problem. What could possibly go wrong (hint: what happens near the stationary point as we keep on updating the parameters)? Can you fix this? # # + [markdown] origin_pos=20 tab=["tensorflow"] # [Discussions](https://discuss.d2l.ai/t/259) #
d2l/tensorflow/chapter_linear-networks/linear-regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Experiment of our program in a real quantum computer # We run the training of a minimum-error discriminator on the IBM quantum device "ibmq_guadalupe". # + import sys sys.path.append('../..') import itertools import numpy as np import matplotlib.pyplot as plt from numpy import pi from qiskit import IBMQ from qiskit.algorithms.optimizers import SPSA from qnn.quantum_neural_networks import StateDiscriminativeQuantumNeuralNetworks as nnd from qnn.quantum_state import QuantumState plt.style.use('ggplot') # - IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-csic', group='internal', project='iff-csic') name_backend = 'ibmq_casablanca' backend = provider.get_backend(name_backend) def callback(params, results, prob_error, prob_inc, prob): datos.append(prob_error) # + # Create random states ψ = QuantumState.random(1) ϕ = QuantumState.random(1) # Parameters th_u, fi_u, lam_u = [0], [0], [0] th1, th2 = [0], [pi] th_v1, th_v2 = [0], [0] fi_v1, fi_v2 = [0], [0] lam_v1, lam_v2 = [0], [0] params = list(itertools.chain(th_u, fi_u, lam_u, th1, th2, th_v1, th_v2, fi_v1, fi_v2, lam_v1, lam_v2)) # Initialize Discriminator discriminator = nnd([ψ, ϕ]) datos = [] results = discriminator.discriminate(SPSA(100), params, callback=callback) optimal = nnd.helstrom_bound(ψ, ϕ) # - print(f'Optimal results: {optimal}\nActual results: {results}') fig = plt.figure(figsize=(14, 6)) plt.plot(datos, '-') plt.hlines( optimal, 0, len(datos), 'b') plt.xlabel('Number of evaluations') plt.ylabel('Probability') plt.legend(['Experimental', 'Helstrom bound']) plt.show() np.save('Experimental_data_v2', np.array([ ψ, ϕ, results, optimal, datos ], dtype=object)) fig.savefig('experiment.png')
qnn/results/experiment_minimum_error.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 # --- # + pycharm={"is_executing": true} #import packages import gym import numpy as np import matplotlib.pylab as plt import random as r import math as m # + pycharm={"is_executing": true} # import neural network charactristics from keras from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam # + pycharm={"is_executing": true} #initialise memory class class MemoryRL: # initialisation function def __init__(self, mem_max): self.mem_max = mem_max self.samps = [] # appending function def append_sample(self, sample): self.samps.append(sample) if len(self.samps) > self.mem_max: self.samps.pop(0) # sample generation function def generate(self, samp_nos): if samp_nos > len(self.samps): return r.sample(self.samps, len(self.samps)) else: return r.sample(self.samps, samp_nos) # + pycharm={"is_executing": true} class AgentRL: # agent parameters initialisation def __init__(self, env): self.env = env self.memory = MemoryRL(5000) self.model = self.create_model() self.target = self.create_model() # initialise parameters self.epsilon_max = 1 self.epsilon_min = 0.01 self.gamma_p = 0.99 self.batch_size = 50 self.lamda = 0.0001 self.tau = 0.099 #define deep neural network model def create_model(self): agent = Sequential() s_shape = self.env.observation_space.shape agent.add(Dense(50, input_dim=s_shape[0], activation="relu")) agent.add(Dense(50, activation="relu")) agent.add(Dense(self.env.action_space.n)) agent.compile(loss="mean_squared_error", optimizer=Adam(lr=0.02)) return agent #create function for action selection def select_action(self, state, step): epsilon = self.epsilon_min + (self.epsilon_max - self.epsilon_min)* m.exp(-self.lamda *step) if np.random.random() < epsilon: return r.randint(0, self.env.action_space.n - 1) else: return np.argmax(self.model.predict(state)[0]) #create function for updating the agent information def capture_memory(self, state, action, reward, new_state, done): self.memory.append_sample((state, action, reward, new_state, done)) #create function for q-updates def replay(self): batch_size = self.batch_size samples = self.memory.generate(batch_size) for sample in samples: state, action, reward, new_state, done = sample Q_val = self.target.predict(state) next_Q = self.target.predict(new_state) if done: Q_val[0][action] = reward else: next_Q = np.amax(next_Q) Q_val[0][action] = reward + next_Q * self.gamma_p self.model.fit(state, Q_val, epochs=1, verbose=0) #create function for updating the weights of the network def train(self): weights = self.model.get_weights() target_weights = self.target.get_weights() for i in range(len(target_weights)): target_weights[i] = weights[i] * self.tau + target_weights[i] * (1 - self.tau) self.target.set_weights(target_weights) # + pycharm={"is_executing": true} #main function if __name__ == "__main__": #generate the mountain car model env = gym.make("MountainCar-v0") trials = 10 trial_len = 200 dqn_agent = AgentRL(env=env) count_trials = 0 stored_reward = [] max_state = -100 stored_f_state = [] #for loop for episodes initilise state and reward for trial in range(trials): if trials % 10 == 0: print("Episode {} of {}".format(trial+1, trials)) current_state = env.reset() current_state= np.reshape(current_state,[1, 2]) total_reward = 0 step_count = 0 # for loop for steps, update action and pass unformation to env. for step in range(trial_len): env.render() action = dqn_agent.select_action(current_state, step + 1) new_state, reward, done, info = env.step(action) #reset reward values as positive rewards for states closer to the optimum if new_state[0] >= -0.5: reward += 1 elif new_state[0] >= -0.1: reward += 5 elif new_state[0] >= 0.1: reward += 10 elif new_state[0] >= 0.25: reward += 20 elif new_state[0] >= 0.5: reward += 100 if new_state[0] > max_state: max_state = new_state[0] new_state = np.reshape(new_state,[1, 2]) #update memory with newly generated values, replay and train dqn_agent.capture_memory(current_state, action, reward, new_state, done) dqn_agent.replay() dqn_agent.train() #update move to the new state unless the end of the episode current_state = new_state total_reward += reward step_count += 1 if done: break #update total reward and final state printout steps and reward stored_reward.append(total_reward) stored_f_state.append(max_state) print("Steps {}, total reward {}".format(step_count, total_reward)) #plot the final states acheived and rewards for the episodes plt.plot(stored_f_state) plt.show() plt.close("all") plt.plot(stored_reward) plt.show() # + pycharm={"is_executing": true}
Chapter13/Activity 13/MountainCarActivity.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 scipy as sc from scipy.integrate import odeint import matplotlib.pyplot as plt from datetime import datetime, date import calendar from time import ctime # + #initia Conditions Rs= 20 #in unit of solar radius R0 = Rs*695700 # unit is Km v0=1000 # unit is km/s w=400 # which is ambient solar wind speed in unit of km/s Gamma=0.2 gamma=Gamma*10**(-7) # unit is km-1 Time_UTC=datetime(2020,8,7,10,15,0) #input utc time in format (year,month,date,hr,minute,second) #Advance Drag based model parameter Omega=30 # half angular width of CME in degree Phi_target=20 # Earth-target heliocentric angular separation in degree Phi_CME=0 # source region central meridian distance in degree; shows shift of cme # + def dbm(x,t): r,v=x dxdt=[v,-gamma*(v-w)*np.abs(v-w)] return dxdt ts = calendar.timegm(Time_UTC.timetuple()) #this command provide second correspond to given input time t=np.arange(ts,ts+388000,1) # - #we calculate speed and distance at alpha angle def RV_alpha(omega,alpha): omega=np.deg2rad(omega) alpha=np.deg2rad(alpha) Y0=[R0,v0] Y=odeint(dbm,Y0,t) R=Y[:,0]/695700 # from now onwards we take solar radius as unit of distance V=Y[:,1] Ra=R *(np.cos(alpha) +((np.tan(omega))**2 - (np.sin(alpha))**2)**0.5)/(1+ np.tan(omega)) Va= V *(np.cos(alpha) +((np.tan(omega))**2 - (np.sin(alpha))**2)**0.5)/(1+ np.tan(omega)) return Ra,Va; # # Forecasting CME def find_nearest(d,v, value): array = np.asarray(d) idx = (np.abs(array - value)).argmin() v=v[idx] T=(t[idx]-t[0])/3600 T_Utc=datetime.utcfromtimestamp(t[idx]) print("Transit time of CME is " + str(T) +" hr") print("Transit Speed of CME is " + str(v) + " km/s") print("Arrival time of CME in UTC is " +str(T_Utc)) return idx # + if Phi_CME-Omega < Phi_target < Phi_CME+Omega: print("Ohh no, CME hits the target.") alpha=np.abs(Phi_CME - Phi_target) R1=RV_alpha(Omega,alpha)[0]/215 V1=RV_alpha(Omega,alpha)[1] A=find_nearest(R1,V1,1.0000) else: print("Yeahh, CME misses the target") R1=RV_alpha(Omega,0)[0]/215 V1=RV_alpha(Omega,0)[1] A=find_nearest(R1,V1,1.0000) # - # # CME Geometry # + plt.figure(figsize=(10,8)) rads = np.arange(-2*np.pi,2* np.pi, 0.01) for rad in rads: if Phi_CME-Omega < np.rad2deg(rad) < Phi_CME+Omega: angle=np.abs(Phi_CME-np.rad2deg(rad)) r=RV_alpha(Omega,angle)[0] q=r[A]/215 ax = plt.subplot(111, projection='polar') ax.plot(rad, q,'r.') else: pass ax.set_rticks([0.25,0.5,0.75,1,1.25,1.5]) ax.set_ylim(0,1.5) ax.plot(0,0,"*",markersize=15,color='orange') ax.text(0,0,"Sun",fontsize=12,va='top') ax.plot(0,1,'o',markersize=10,color='green') ax.text(0,1,"Earth",fontsize=12,va='top') ax.plot(np.deg2rad(Phi_target),1,'x',markersize=10) ax.text(np.deg2rad(Phi_target),1,"Target",fontsize=12,va='top') ax.axvline(np.deg2rad(Phi_target)) ax.text(np.deg2rad(Phi_CME),1,"CME",fontsize=12) ax.set_title("CME Geometry",fontsize=15) plt.show()
Model_code/Advance DBM.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 # # Test for an education/gender interaction in wages # ================================================== # # Wages depend mostly on education. Here we investigate how this dependence # is related to gender: not only does gender create an offset in wages, it # also seems that wages increase more with education for males than # females. # # Does our data support this last hypothesis? We will test this using # statsmodels' formulas # (http://statsmodels.sourceforge.net/stable/example_formulas.html). # # # # Load and massage the data # # # + import pandas import urllib import os if not os.path.exists('wages.txt'): # Download the file if it is not present urllib.urlretrieve('http://lib.stat.cmu.edu/datasets/CPS_85_Wages', 'wages.txt') # EDUCATION: Number of years of education # SEX: 1=Female, 0=Male # WAGE: Wage (dollars per hour) data = pandas.read_csv('wages.txt', skiprows=27, skipfooter=6, sep=None, header=None, names=['education', 'gender', 'wage'], usecols=[0, 2, 5], ) # Convert genders to strings (this is particulary useful so that the # statsmodels formulas detects that gender is a categorical variable) import numpy as np data['gender'] = np.choose(data.gender, ['male', 'female']) # Log-transform the wages, because they typically are increased with # multiplicative factors data['wage'] = np.log10(data['wage']) # - # simple plotting # # # + import seaborn # Plot 2 linear fits for male and female. seaborn.lmplot(y='wage', x='education', hue='gender', data=data) # - # statistical analysis # # # + import statsmodels.formula.api as sm # Note that this model is not the plot displayed above: it is one # joined model for male and female, not separate models for male and # female. The reason is that a single model enables statistical testing result = sm.ols(formula='wage ~ education + gender', data=data).fit() print(result.summary()) # - # The plots above highlight that there is not only a different offset in # wage but also a different slope # # We need to model this using an interaction # # result = sm.ols(formula='wage ~ education + gender + education * gender', data=data).fit() print(result.summary()) # Looking at the p-value of the interaction of gender and education, the # data does not support the hypothesis that education benefits males # more than female (p-value > 0.05). # # import matplotlib.pyplot as plt plt.show()
_downloads/plot_wage_education_gender.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="h2q27gKz1H20" # ##### Copyright 2021 The TensorFlow Authors. # + cellView="form" id="TUfAcER1oUS6" #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # + [markdown] id="Gb7qyhNL1yWt" # # Object Detection with TensorFlow Lite Model Maker # + [markdown] id="Fw5Y7snSuG51" # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://www.tensorflow.org/lite/tutorials/model_maker_object_detection"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> # </td> # <td> # <a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/tutorials/model_maker_object_detection.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> # </td> # <td> # <a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/tutorials/model_maker_object_detection.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> # </td> # <td> # <a href="https://storage.googleapis.com/tensorflow_docs/tensorflow/tensorflow/lite/g3doc/tutorials/model_maker_object_detection.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> # </td> # </table> # + [markdown] id="sr3q-gvm3cI8" # In this colab notebook, you'll learn how to use the [TensorFlow Lite Model Maker](https://www.tensorflow.org/lite/guide/model_maker) library to train a custom object detection model capable of detecting salads within images on a mobile device. # # The Model Maker library uses *transfer learning* to simplify the process of training a TensorFlow Lite model using a custom dataset. Retraining a TensorFlow Lite model with your own custom dataset reduces the amount of training data required and will shorten the training time. # # You'll use the publicly available *Salads* dataset, which was created from the [Open Images Dataset V4](https://storage.googleapis.com/openimages/web/index.html). # # Each image in the dataset contains objects labeled as one of the following classes: # * Baked Good # * Cheese # * Salad # * Seafood # * Tomato # # The dataset contains the bounding-boxes specifying where each object locates, together with the object's label. # # Here is an example image from the dataset: # # <br/> # # <img src="https://cloud.google.com/vision/automl/object-detection/docs/images/quickstart-preparing_a_dataset.png" width="400" hspace="0"> # # + [markdown] id="bcLF2PKkSbV3" # ## Prerequisites # # + [markdown] id="2vvAObmTqglq" # ### Install the required packages # Start by installing the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker) and the pycocotools library you'll use for evaluation. # + id="qhl8lqVamEty" # !pip install -q tensorflow==2.5.0 # !pip install -q --use-deprecated=legacy-resolver tflite-model-maker # !pip install -q pycocotools # + [markdown] id="l6lRhVK9Q_0U" # Import the required packages. # + id="XtxiUeZEiXpt" import numpy as np import os from tflite_model_maker.config import ExportFormat from tflite_model_maker import model_spec from tflite_model_maker import object_detector import tensorflow as tf assert tf.__version__.startswith('2') tf.get_logger().setLevel('ERROR') from absl import logging logging.set_verbosity(logging.ERROR) # + [markdown] id="BRd13bfetO7B" # ### Prepare the dataset # # Here you'll use the same dataset as the AutoML [quickstart](https://cloud.google.com/vision/automl/object-detection/docs/edge-quickstart#preparing_a_dataset). # # The *Salads* dataset is available at: # `gs://cloud-ml-data/img/openimage/csv/salads_ml_use.csv`. # # It contains 175 images for training, 25 images for validation, and 25 images for testing. The dataset has five classes: `Salad`, `Seafood`, `Tomato`, `Baked goods`, `Cheese`. # # <br/> # # The dataset is provided in CSV format: # ``` # TRAINING,gs://cloud-ml-data/img/openimage/3/2520/3916261642_0a504acd60_o.jpg,Salad,0.0,0.0954,,,0.977,0.957,, # VALIDATION,gs://cloud-ml-data/img/openimage/3/2520/3916261642_0a504acd60_o.jpg,Seafood,0.0154,0.1538,,,1.0,0.802,, # TEST,gs://cloud-ml-data/img/openimage/3/2520/3916261642_0a504acd60_o.jpg,Tomato,0.0,0.655,,,0.231,0.839,, # ``` # # * Each row corresponds to an object localized inside a larger image, with each object specifically designated as test, train, or validation data. You'll learn more about what that means in a later stage in this notebook. # * The three lines included here indicate **three distinct objects located inside the same image** available at `gs://cloud-ml-data/img/openimage/3/2520/3916261642_0a504acd60_o.jpg`. # * Each row has a different label: `Salad`, `Seafood`, `Tomato`, etc. # * Bounding boxes are specified for each image using the top left and bottom right vertices. # # Here is a visualzation of these three lines: # # <br> # # <img src="https://cloud.google.com/vision/automl/object-detection/docs/images/quickstart-preparing_a_dataset.png" width="400" hspace="100"> # # If you want to know more about how to prepare your own CSV file and the minimum requirements for creating a valid dataset, see the [Preparing your training data](https://cloud.google.com/vision/automl/object-detection/docs/prepare) guide for more details. # # If you are new to Google Cloud, you may wonder what the `gs://` URL means. They are URLs of files stored on [Google Cloud Storage](https://cloud.google.com/storage) (GCS). If you make your files on GCS public or [authenticate your client](https://cloud.google.com/storage/docs/authentication#libauth), Model Maker can read those files similarly to your local files. # # However, you don't need to keep your images on Google Cloud to use Model Maker. You can use a local path in your CSV file and Model Maker will just work. # + [markdown] id="xushUyZXqP59" # ## Quickstart # + [markdown] id="vn61LJ9QbOPi" # There are six steps to training an object detection model: # # **Step 1. Choose an object detection model archiecture.** # # This tutorial uses the EfficientDet-Lite0 model. EfficientDet-Lite[0-4] are a family of mobile/IoT-friendly object detection models derived from the [EfficientDet](https://arxiv.org/abs/1911.09070) architecture. # # Here is the performance of each EfficientDet-Lite models compared to each others. # # | Model architecture | Size(MB)* | Latency(ms)** | Average Precision*** | # |--------------------|-----------|---------------|----------------------| # | EfficientDet-Lite0 | 4.4 | 37 | 25.69% | # | EfficientDet-Lite1 | 5.8 | 49 | 30.55% | # | EfficientDet-Lite2 | 7.2 | 69 | 33.97% | # | EfficientDet-Lite3 | 11.4 | 116 | 37.70% | # | EfficientDet-Lite4 | 19.9 | 260 | 41.96% | # # <i> * Size of the integer quantized models. <br/> # ** Latency measured on Pixel 4 using 4 threads on CPU. <br/> # *** Average Precision is the mAP (mean Average Precision) on the COCO 2017 validation dataset. # </i> # # + id="CtdZ-JDwMimd" spec = model_spec.get('efficientdet_lite0') # + [markdown] id="s5U-A3tw6Y27" # **Step 2. Load the dataset.** # # Model Maker will take input data in the CSV format. Use the `object_detector.DataLoader.from_csv` method to load the dataset and split them into the training, validation and test images. # # * Training images: These images are used to train the object detection model to recognize salad ingredients. # * Validation images: These are images that the model didn't see during the training process. You'll use them to decide when you should stop the training, to avoid [overfitting](https://en.wikipedia.org/wiki/Overfitting). # * Test images: These images are used to evaluate the final model performance. # # You can load the CSV file directly from Google Cloud Storage, but you don't need to keep your images on Google Cloud to use Model Maker. You can specify a local CSV file on your computer, and Model Maker will work just fine. # + id="HD5BvzWe6YKa" train_data, validation_data, test_data = object_detector.DataLoader.from_csv('gs://cloud-ml-data/img/openimage/csv/salads_ml_use.csv') # + [markdown] id="2uZkLR6N6gDR" # **Step 3. Train the TensorFlow model with the training data.** # # * The EfficientDet-Lite0 model uses `epochs = 50` by default, which means it will go through the training dataset 50 times. You can look at the validation accuracy during training and stop early to avoid overfitting. # * Set `batch_size = 8` here so you will see that it takes 21 steps to go through the 175 images in the training dataset. # * Set `train_whole_model=True` to fine-tune the whole model instead of just training the head layer to improve accuracy. The trade-off is that it may take longer to train the model. # + id="kwlYdTcg63xy" model = object_detector.create(train_data, model_spec=spec, batch_size=8, train_whole_model=True, validation_data=validation_data) # + [markdown] id="-BzCHLWJ6h7q" # **Step 4. Evaluate the model with the test data.** # # After training the object detection model using the images in the training dataset, use the remaining 25 images in the test dataset to evaluate how the model performs against new data it has never seen before. # # As the default batch size is 64, it will take 1 step to go through the 25 images in the test dataset. # # The evaluation metrics are same as [COCO](https://cocodataset.org/#detection-eval). # + id="8xmnl6Yy7ARn" model.evaluate(test_data) # + [markdown] id="CgCDMe0e6jlT" # **Step 5. Export as a TensorFlow Lite model.** # # Export the trained object detection model to the TensorFlow Lite format by specifying which folder you want to export the quantized model to. The default post-training quantization technique is full integer quantization. # + id="Hm_UULdW7A9T" model.export(export_dir='.') # + [markdown] id="ZQpahAIBqBPp" # **Step 6. Evaluate the TensorFlow Lite model.** # # Several factors can affect the model accuracy when exporting to TFLite: # * [Quantization](https://www.tensorflow.org/lite/performance/model_optimization) helps shrinking the model size by 4 times at the expense of some accuracy drop. # * The original TensorFlow model uses per-class [non-max supression (NMS)](https://www.coursera.org/lecture/convolutional-neural-networks/non-max-suppression-dvrjH) for post-processing, while the TFLite model uses global NMS that's much faster but less accurate. # Keras outputs maximum 100 detections while tflite outputs maximum 25 detections. # # Therefore you'll have to evaluate the exported TFLite model and compare its accuracy with the original TensorFlow model. # + id="RS3Ell_lqH4e" model.evaluate_tflite('model.tflite', test_data) # + [markdown] id="rVxaf3x_7OfB" # You can download the TensorFlow Lite model file using the left sidebar of Colab. Right-click on the `model.tflite` file and choose `Download` to download it to your local computer. # # This model can be integrated into an Android or an iOS app using the [ObjectDetector API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/object_detector) of the [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview). # # See the [TFLite Object Detection sample app](https://github.com/tensorflow/examples/blob/master/lite/examples/object_detection/android/lib_task_api/src/main/java/org/tensorflow/lite/examples/detection/tflite/TFLiteObjectDetectionAPIModel.java#L91) for more details on how the model is used in an working app. # # *Note: Android Studio Model Binding does not support object detection yet so please use the TensorFlow Lite Task Library.* # + [markdown] id="me6_RwPZqNhX" # ## (Optional) Test the TFLite model on your image # # You can test the trained TFLite model using images from the internet. # * Replace the `INPUT_IMAGE_URL` below with your desired input image. # * Adjust the `DETECTION_THRESHOLD` to change the sensitivity of the model. A lower threshold means the model will pickup more objects but there will also be more false detection. Meanwhile, a higher threshold means the model will only pickup objects that it has confidently detected. # # Although it requires some of boilerplate code to run the model in Python at this moment, integrating the model into a mobile app only requires a few lines of code. # + cellView="form" id="XqS0rFCrqM1o" #@title Load the trained TFLite model and define some visualization functions import cv2 from PIL import Image model_path = 'model.tflite' # Load the labels into a list classes = ['???'] * model.model_spec.config.num_classes label_map = model.model_spec.config.label_map for label_id, label_name in label_map.as_dict().items(): classes[label_id-1] = label_name # Define a list of colors for visualization COLORS = np.random.randint(0, 255, size=(len(classes), 3), dtype=np.uint8) def preprocess_image(image_path, input_size): """Preprocess the input image to feed to the TFLite model""" img = tf.io.read_file(image_path) img = tf.io.decode_image(img, channels=3) img = tf.image.convert_image_dtype(img, tf.uint8) original_image = img resized_img = tf.image.resize(img, input_size) resized_img = resized_img[tf.newaxis, :] return resized_img, original_image def set_input_tensor(interpreter, image): """Set the input tensor.""" tensor_index = interpreter.get_input_details()[0]['index'] input_tensor = interpreter.tensor(tensor_index)()[0] input_tensor[:, :] = image def get_output_tensor(interpreter, index): """Retur the output tensor at the given index.""" output_details = interpreter.get_output_details()[index] tensor = np.squeeze(interpreter.get_tensor(output_details['index'])) return tensor def detect_objects(interpreter, image, threshold): """Returns a list of detection results, each a dictionary of object info.""" # Feed the input image to the model set_input_tensor(interpreter, image) interpreter.invoke() # Get all outputs from the model boxes = get_output_tensor(interpreter, 0) classes = get_output_tensor(interpreter, 1) scores = get_output_tensor(interpreter, 2) count = int(get_output_tensor(interpreter, 3)) results = [] for i in range(count): if scores[i] >= threshold: result = { 'bounding_box': boxes[i], 'class_id': classes[i], 'score': scores[i] } results.append(result) return results def run_odt_and_draw_results(image_path, interpreter, threshold=0.5): """Run object detection on the input image and draw the detection results""" # Load the input shape required by the model _, input_height, input_width, _ = interpreter.get_input_details()[0]['shape'] # Load the input image and preprocess it preprocessed_image, original_image = preprocess_image( image_path, (input_height, input_width) ) # Run object detection on the input image results = detect_objects(interpreter, preprocessed_image, threshold=threshold) # Plot the detection results on the input image original_image_np = original_image.numpy().astype(np.uint8) for obj in results: # Convert the object bounding box from relative coordinates to absolute # coordinates based on the original image resolution ymin, xmin, ymax, xmax = obj['bounding_box'] xmin = int(xmin * original_image_np.shape[1]) xmax = int(xmax * original_image_np.shape[1]) ymin = int(ymin * original_image_np.shape[0]) ymax = int(ymax * original_image_np.shape[0]) # Find the class index of the current object class_id = int(obj['class_id']) # Draw the bounding box and label on the image color = [int(c) for c in COLORS[class_id]] cv2.rectangle(original_image_np, (xmin, ymin), (xmax, ymax), color, 2) # Make adjustments to make the label visible for all objects y = ymin - 15 if ymin - 15 > 15 else ymin + 15 label = "{}: {:.0f}%".format(classes[class_id], obj['score'] * 100) cv2.putText(original_image_np, label, (xmin, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) # Return the final image original_uint8 = original_image_np.astype(np.uint8) return original_uint8 # + cellView="form" id="GkXtipXKqXp4" #@title Run object detection and show the detection results INPUT_IMAGE_URL = "https://storage.googleapis.com/cloud-ml-data/img/openimage/3/2520/3916261642_0a504acd60_o.jpg" #@param {type:"string"} DETECTION_THRESHOLD = 0.3 #@param {type:"number"} TEMP_FILE = '/tmp/image.png' # !wget -q -O $TEMP_FILE $INPUT_IMAGE_URL im = Image.open(TEMP_FILE) im.thumbnail((512, 512), Image.ANTIALIAS) im.save(TEMP_FILE, 'PNG') # Load the TFLite model interpreter = tf.lite.Interpreter(model_path=model_path) interpreter.allocate_tensors() # Run inference and draw detection result on the local copy of the original file detection_result_image = run_odt_and_draw_results( TEMP_FILE, interpreter, threshold=DETECTION_THRESHOLD ) # Show the detection result Image.fromarray(detection_result_image) # + [markdown] id="oxgWQyYOqZha" # ## (Optional) Compile For the Edge TPU # # Now that you have a quantized EfficientDet Lite model, it is possible to compile and deploy to a [Coral EdgeTPU](https://coral.ai/). # # **Step 1. Install the EdgeTPU Compiler** # + id="Oy3QIn_YqaRP" # ! curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - # ! echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list # ! sudo apt-get update # ! sudo apt-get install edgetpu-compiler # + [markdown] id="qRWewhqFqeL_" # **Step 2. Select number of Edge TPUs, Compile** # # The EdgeTPU has 8MB of SRAM for caching model paramaters ([more info](https://coral.ai/docs/edgetpu/compiler/#parameter-data-caching)). This means that for models that are larger than 8MB, inference time will be increased in order to transfer over model paramaters. One way to avoid this is [Model Pipelining](https://coral.ai/docs/edgetpu/pipeline/) - splitting the model into segments that can have a dedicated EdgeTPU. This can significantly improve latency. # # The below table can be used as a reference for the number of Edge TPUs to use - the larger models will not compile for a single TPU as the intermediate tensors can't fit in on-chip memory. # # | Model architecture | Minimum TPUs | Recommended TPUs # |--------------------|-------|-------| # | EfficientDet-Lite0 | 1 | 1 | # | EfficientDet-Lite1 | 1 | 1 | # | EfficientDet-Lite2 | 1 | 2 | # | EfficientDet-Lite3 | 2 | 2 | # | EfficientDet-Lite4 | 2 | 3 | # + cellView="form" id="LZdonJGCqieU" NUMBER_OF_TPUS = 1#@param {type:"number"} # !edgetpu_compiler model.tflite --num_segments=$NUMBER_OF_TPUS # + [markdown] id="-g6_KQXnqlTC" # **Step 3. Download, Run Model** # # With the model(s) compiled, they can now be run on EdgeTPU(s) for object detection. First, download the compiled TensorFlow Lite model file using the left sidebar of Colab. Right-click on the `model_edgetpu.tflite` file and choose `Download` to download it to your local computer. # + [markdown] id="VkQFz_qzqrrA" # Now you can run the model in your preferred manner. Examples of detection include: # * [pycoral detection](https://github.com/google-coral/pycoral/blob/master/examples/detect_image.py) # * [Basic TFLite detection](https://github.com/google-coral/tflite/tree/master/python/examples/detection) # * [Example Video Detection](https://github.com/google-coral/examples-camera) # * [libcoral C++ API](https://github.com/google-coral/libcoral) # # + [markdown] id="EoWiA_zX8rxE" # ## Advanced Usage # # This section covers advanced usage topics like adjusting the model and the training hyperparameters. # + [markdown] id="p79NHCx0xFqb" # ### Load the dataset # # #### Load your own data # # You can upload your own dataset to work through this tutorial. Upload your dataset by using the left sidebar in Colab. # # <img src="https://storage.googleapis.com/download.tensorflow.org/models/tflite/screenshots/model_maker_object_detection.png" alt="Upload File" width="1000" hspace="0"> # # If you prefer not to upload your dataset to the cloud, you can also locally run the library by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). # # #### Load your data with a different data format # # The Model Maker library also supports the `object_detector.DataLoader.from_pascal_voc` method to load data with [PASCAL VOC](https://towardsdatascience.com/coco-data-format-for-object-detection-a4c5eaf518c5#:~:text=Pascal%20VOC%20is%20an%20XML,for%20training%2C%20testing%20and%20validation) format. [makesense.ai](https://www.makesense.ai/) and [LabelImg](https://github.com/tzutalin/labelImg) are the tools that can annotate the image and save annotations as XML files in PASCAL VOC data format: # ```python # object_detector.DataLoader.from_pascal_voc(image_dir, annotations_dir, label_map={1: "person", 2: "notperson"}) # ``` # # + [markdown] id="E8VxPiOLy4Gv" # ### Customize the EfficientDet model hyperparameters # # The model and training pipline parameters you can adjust are: # # * `model_dir`: The location to save the model checkpoint files. If not set, a temporary directory will be used. # * `steps_per_execution`: Number of steps per training execution. # * `moving_average_decay`: Float. The decay to use for maintaining moving averages of the trained parameters. # * `var_freeze_expr`: The regular expression to map the prefix name of variables to be frozen which means remaining the same during training. More specific, use `re.match(var_freeze_expr, variable_name)` in the codebase to map the variables to be frozen. # * `tflite_max_detections`: integer, 25 by default. The max number of output detections in the TFLite model. # * `strategy`: A string specifying which distribution strategy to use. Accepted values are 'tpu', 'gpus', None. tpu' means to use TPUStrategy. 'gpus' mean to use MirroredStrategy for multi-gpus. If None, use TF default with OneDeviceStrategy. # * `tpu`: The Cloud TPU to use for training. This should be either the name used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 url. # * `use_xla`: Use XLA even if strategy is not tpu. If strategy is tpu, always use XLA, and this flag has no effect. # * `profile`: Enable profile mode. # * `debug`: Enable debug mode. # # Other parameters that can be adjusted is shown in [hparams_config.py](https://github.com/google/automl/blob/df451765d467c5ed78bbdfd632810bc1014b123e/efficientdet/hparams_config.py#L170). # # # For instance, you can set the `var_freeze_expr='efficientnet'` which freezes the variables with name prefix `efficientnet` (default is `'(efficientnet|fpn_cells|resample_p6)'`). This allows the model to freeze untrainable variables and keep their value the same through training. # # ```python # spec = model_spec.get('efficientdet-lite0') # spec.config.var_freeze_expr = 'efficientnet' # ``` # + [markdown] id="4J2qre1fwXsi" # ### Change the Model Architecture # # You can change the model architecture by changing the `model_spec`. For instance, change the `model_spec` to the EfficientDet-Lite4 model. # # ```python # spec = model_spec.get('efficientdet-lite4') # ``` # + [markdown] id="LvQuy7RSDir3" # ### Tune the training hyperparameters # # The `create` function is the driver function that the Model Maker library uses to create models. The `model_spec` parameter defines the model specification. The `object_detector.EfficientDetSpec` class is currently supported. The `create` function comprises of the following steps: # # 1. Creates the model for the object detection according to `model_spec`. # 2. Trains the model. The default epochs and the default batch size are set by the `epochs` and `batch_size` variables in the `model_spec` object. # You can also tune the training hyperparameters like `epochs` and `batch_size` that affect the model accuracy. For instance, # # * `epochs`: Integer, 50 by default. More epochs could achieve better accuracy, but may lead to overfitting. # * `batch_size`: Integer, 64 by default. The number of samples to use in one training step. # * `train_whole_model`: Boolean, False by default. If true, train the whole model. Otherwise, only train the layers that do not match `var_freeze_expr`. # # For example, you can train with less epochs and only the head layer. You can increase the number of epochs for better results. # # ```python # model = object_detector.create(train_data, model_spec=spec, epochs=10, validation_data=validation_data) # ``` # + [markdown] id="3vPyZInPxJBT" # ### Export to different formats # + [markdown] id="0xqNIcBM-4YR" # The export formats can be one or a list of the following: # # * `ExportFormat.TFLITE` # * `ExportFormat.LABEL` # * `ExportFormat.SAVED_MODEL` # # + [markdown] id="enhsZhW3ApcX" # By default, it exports only the TensorFlow Lite model file containing the model [metadata](https://www.tensorflow.org/lite/convert/metadata) so that you can later use in an on-device ML application. The label file is embedded in metadata. # # In many on-device ML application, the model size is an important factor. Therefore, it is recommended that you quantize the model to make it smaller and potentially run faster. As for EfficientDet-Lite models, full integer quantization is used to quantize the model by default. Please refer to [Post-training quantization](https://www.tensorflow.org/lite/performance/post_training_quantization) for more detail. # # ```python # model.export(export_dir='.') # ``` # + [markdown] id="RLGZs6InAnP5" # You can also choose to export other files related to the model for better examination. For instance, exporting both the saved model and the label file as follows: # ```python # model.export(export_dir='.', export_format=[ExportFormat.SAVED_MODEL, ExportFormat.LABEL]) # ``` # + [markdown] id="W5q_McchQ2C4" # ### Customize Post-training quantization on the TensorFlow Lite model # # [Post-training quantization](https://www.tensorflow.org/lite/performance/post_training_quantization) is a conversion technique that can reduce model size and inference latency, while also improving CPU and hardware accelerator inference speed, with a little degradation in model accuracy. Thus, it's widely used to optimize the model. # # Model Maker library applies a default post-training quantization techique when exporting the model. If you want to customize post-training quantization, Model Maker supports multiple post-training quantization options using [QuantizationConfig](https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker/config/QuantizationConfig) as well. Let's take float16 quantization as an instance. First, define the quantization config. # # ```python # config = QuantizationConfig.for_float16() # ``` # # # Then we export the TensorFlow Lite model with such configuration. # # ```python # model.export(export_dir='.', tflite_filename='model_fp16.tflite', quantization_config=config) # ``` # + [markdown] id="HS4u77W5gnzQ" # # Read more # # You can read our [object detection](https://www.tensorflow.org/lite/examples/object_detection/overview) example to learn technical details. For more information, please refer to: # # * TensorFlow Lite Model Maker [guide](https://www.tensorflow.org/lite/guide/model_maker) and [API reference](https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker). # * Task Library: [ObjectDetector](https://www.tensorflow.org/lite/inference_with_metadata/task_library/object_detector) for deployment. # * The end-to-end reference apps: [Android](https://github.com/tensorflow/examples/tree/master/lite/examples/object_detection/android), [iOS](https://github.com/tensorflow/examples/tree/master/lite/examples/object_detection/ios), and [Raspberry PI](https://github.com/tensorflow/examples/tree/master/lite/examples/object_detection/raspberry_pi). #
site/en-snapshot/lite/tutorials/model_maker_object_detection.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # %matplotlib notebook from threeML import * # + data_dir = os.path.join('gbm','bn080916009') trigger_number = 'bn080916009' # Download the data data_dir_gbm = os.path.join('gbm',trigger_number) gbm_data = download_GBM_trigger_data(trigger_number,detectors=['n3','b0'],destination_directory=data_dir_gbm,compress_tte=True) src_selection = "0.-5." nai3 = FermiGBMTTELike('NAI3', os.path.join(data_dir, "glg_tte_n3_bn080916009_v01.fit.gz"), "-10-0,100-200", src_selection, rsp_file=os.path.join(data_dir, "glg_cspec_n3_bn080916009_v00.rsp2")) bgo0 = FermiGBMTTELike('BGO0', os.path.join(data_dir, "glg_tte_b0_bn080916009_v01.fit.gz"), "-10-0,100-200", src_selection, rsp_file=os.path.join(data_dir, "glg_cspec_b0_bn080916009_v00.rsp2")) nai3.set_active_measurements("8.0-30.0", "40.0-950.0") bgo0.set_active_measurements("250-43000") # + nai3.create_time_bins(start=0,stop=10,dt=2,method='constant') bgo0.read_bins(nai3) nai3_intervals = nai3.get_ogip_from_binner() bgo0_intervals = bgo0.get_ogip_from_binner() all_data = nai3_intervals + bgo0_intervals # + triggerName = 'bn080916009' ra = 121.8 dec = -61.3 data_list = DataList( *all_data ) band = Band() GRB = PointSource( triggerName, ra, dec, spectral_shape=band ) model = Model( GRB ) time = IndependentVariable("time",13.0, unit='s') model law = Powerlaw(K=500,index=-1) #law = Line(a=-0.02,b=-2.0) model.add_independent_variable(time) model.link(model.bn080916009.spectrum.main.Band.xp,time,law) mean_time = [np.mean([x,y]) for x,y in zip(nai3.bins[0],nai3.bins[1])] ff = step_generator(mean_time,band.alpha) model.link(model.bn080916009.spectrum.main.Band.alpha,time,ff) ff = step_generator(mean_time,band.K) model.link(model.bn080916009.spectrum.main.Band.K,time,ff) ff = step_generator(mean_time,band.beta) model.link(model.bn080916009.spectrum.main.Band.beta,time,ff) for n,b,t in zip(nai3_intervals,bgo0_intervals,mean_time): n.external_property(time,t) b.external_property(time,t) # - model jl = JointLikelihood( model, data_list, verbose=False ) #jl.set_minimizer("PYOPT","COBYLA") res = jl.fit() cleanup_downloaded_GBM_data(gbm_data)
examples/obsolete/time_dependent_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 # name: python3 # --- # + [markdown] id="alFvNvNWKY8R" # ## Load data # + id="KRNu9dkCKONa" import tensorflow as tf mnist = tf.keras.datasets.mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() # + id="i7MF-Lz0LvO_" # feature scaling (data normalisation) # Prediction accuracy gets higher with scaled images. # Original colour vector range 0 ~ 255 ---> scaled range 0.0 ~ 1.0 X_train, X_test = X_train/255.0, X_test/255.0 # + [markdown] id="HfRAe2arVGlS" # # Multiple ways to create a model # + [markdown] id="Sk0HiiKYcYVX" # ## 1) Using Keras # + id="B3Qj5njSMY7K" mlp_model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) mlp_model.fit(X_train, y_train, epochs=5) mlp_model.evaluate(X_test, y_test, verbose=1) # + [markdown] id="QBFJ5f3_TmGk" # ## 2) Using functional API # + colab={"base_uri": "https://localhost:8080/"} id="8aPbwqFISzfy" outputId="b4a22276-e208-4dc2-d87a-64c53cd26407" # DNN - multi-layer perceptrons inputs = tf.keras.Input(shape=(28,28)) x = tf.keras.layers.Flatten()(inputs) x = tf.keras.layers.Dense(128, activation='relu')(x) outputs = tf.keras.layers.Dense(10, activation='softmax')(x) mlp_model = tf.keras.Model(inputs=inputs, outputs=outputs) mlp_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) mlp_model.fit(X_train, y_train, epochs=5) mlp_model.evaluate(X_test, y_test, verbose=1) # + [markdown] id="E-kSUpWfVBgi" # ## 3) Using class (best format) # - Highest re-usability # # + colab={"base_uri": "https://localhost:8080/"} id="TQ5EG-xeVDnh" outputId="73752eeb-395e-4a02-a633-1a54066ed245" # 재사용성이 가장 높음 - 모델 자체를 배포할 때도 이 방식 사용 class MLP_Model(tf.keras.Model): def __init__(self): super(MLP_Model, self).__init__() self.flatten = tf.keras.layers.Flatten() self.dense = tf.keras.layers.Dense(128, activation='relu') self.softmax = tf.keras.layers.Dense(10, activation='softmax') def call(self, inputs): x = self.flatten(inputs) x = self.dense(x) return self.softmax(x) mlp_model = MLP_Model() mlp_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) mlp_model.fit(X_train, y_train, epochs=5) mlp_model.evaluate(X_test, y_test, verbose=2) # + [markdown] id="mg8tG63pedp8" # ## 4) CNN # # + colab={"base_uri": "https://localhost:8080/"} id="rzp6JuN9XRVV" outputId="86f0f8c4-b99c-453f-99c0-09f27d4e5bdc" import tensorflow as tf mnist = tf.keras.datasets.mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train, X_test = X_train/255.0, X_test/255.0 # 입력 데이터 수정 X_train_4d = X_train.reshape(-1, 28, 28, 1) X_test_4d = X_test.reshape(-1, 28, 28, 1) cnn_model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D((2,2)), # MaxPooling merges neurons. tf.keras.layers.Conv2D(64, (3,3), activation='relu'), # So increase the neuron quantity the next layer. tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Conv2D(64, (3,3), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) cnn_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) cnn_model.fit(X_train_4d, y_train, epochs=5) cnn_model.evaluate(X_test_4d, y_test, verbose=1) # + [markdown] id="rK_JWZzXe8-a" # ## 5) ResNet # + colab={"base_uri": "https://localhost:8080/"} id="zn40-dRTeTKm" outputId="10529f71-9148-4045-e04d-d6021cd7083c" import tensorflow as tf # Load and scale data. mnist = tf.keras.datasets.mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train, X_test = X_train/255.0, X_test/255.0 # Change the input data shape. X_train_4d = X_train.reshape(-1, 28, 28, 1) X_test_4d = X_test.reshape(-1, 28, 28, 1) # Further modify the shape for ResNet resized_X_train = tf.image.resize(X_train_4d, [32, 32]) resized_X_test = tf.image.resize(X_test_4d, [32, 32]) # Create model resnet_model = tf.keras.applications.ResNet50V2( input_shape=(32,32,1), classes=10, weights=None ) resnet_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) resnet_model.fit(resized_X_train, y_train, epochs=5) resnet_model.evaluate(resized_X_test, y_test, verbose=1) # ResNet is deeper than other models created here. So it takes longer. # + [markdown] id="bzkhqhpIfKMo" # # Running the model # + [markdown] id="B9N8dFIaRp3f" # ## i. Model structure # + colab={"base_uri": "https://localhost:8080/"} id="QJaI09iEQws1" outputId="0aa85025-7eb6-4d11-d40a-d520b5085de5" mlp_model.summary() # + [markdown] id="dJPU9xiyPonB" # ## ii. Compiling the model # # Options for loss fucntion: # - Regression: `MSE` (value) # - or... `MAE`, `RMSE` are also available. # - Classification: `CrossEntropy` (probability) # - binary classification: `binary_crossentropy` # - multi-classification: `sparse_categorical crossentropy`, `categorical_crossentropy` # - One-hot encoded: `categorical_crossentropy` # - None one-hot encoded: `sparse_categorical_crossentropy` # # + colab={"base_uri": "https://localhost:8080/"} id="Rigezi4mPn4C" outputId="890b750e-a27f-4c8d-fdde-2b3c94b597d4" y_train = tf.keras.utils.to_categorical(y_train) y_test = tf.keras.utils.to_categorical(y_test) mlp_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # + [markdown] id="csjzcdsRSOit" # ## iii. Train the model # + colab={"base_uri": "https://localhost:8080/"} id="Bup9qfocSQTv" outputId="7889441f-a592-452d-dc54-91e124478336" mlp_model.fit(X_train, y_train, epochs=5) # + [markdown] id="x2s0_nHgSuU-" # ## iv. Evaluate the model # + colab={"base_uri": "https://localhost:8080/"} id="ZeRLeBvxSSiF" outputId="07262601-5415-4fca-b79a-f71485db2595" mlp_model.evaluate(X_test, y_test, verbose=1) # + [markdown] id="roaqCfZYd6O4" # ## 6) Create a transfer-learning model # - Import from *Mobile TensorFlow Hub*. # - https://tfhub.dev/ # - Convert to Tensorflow Light model (ext .tflite) # # <br/> # # Process: # # 1) Create a converter: # # - `tensorflow.lite.TFLiteConverter.from_keras_model(model_name)` # # # 2) Write it to a file. # # - `with open('/content/here/MyDrive/MLP_model/keras_model.tflite', 'wb') as f:` # - `f.write(tflite_model)` # -extension: `.tflite` # # model = tf.keras.Sequential([ # tensorflow_hun.KerasLayer(url, input_shape=(입력 구조), trainable=False), # tf.keras.layers.Dense(출력의 개수) # ]) # # # # + [markdown] id="XURGP3wcjESw" # ### Convert the above models into a TensorFlow Lite model # + colab={"base_uri": "https://localhost:8080/"} id="rIfn2pwljdwf" outputId="1a264369-3fc9-4108-af41-67305b6f9c92" from google.colab import drive drive.mount('here') # + colab={"base_uri": "https://localhost:8080/"} id="J7x4GB6QeEJY" outputId="9519fc44-fe42-475d-ab78-cc5a431ff9f4" converter = tf.lite.TFLiteConverter.from_keras_model(mlp_model) tflite_model = converter.convert() with open('/content/here/MyDrive/MLP_model/keras_model.tflite', 'wb') as f: f.write(tflite_model) # + [markdown] id="5V18tknFU2jq" # # Error Notes # # ValueError: Shape mismatch: The shape of labels (received (320,)) # should equal the shape of logits # except for the last dimension (received (32, 10)). # # - When you are running the same model built with different methods multiple times, be sure to reset runtime to clear memory. # #
Multiple ways to create the same model.ipynb