markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
[ ] Los corchetes tienen la función de formar conjuntos de caracteres. Hasta ahora hemos usado punto (`.`) para cuando queremos acpetar más de un posible caracter. En expresiones como: `r"M..ic."` ; la naturaleza del texto provocó que solo se obtuvieran cosas relacionadas con México, pero fácilmente la expresión hubie...
expresion_corchetes = re.compile(r"[Mm].[xj]ic[^ \n]+") busqueda = expresion_corchetes.finditer(texto) for resultado in busqueda: print(resultado.group(0)) expresion_rango = re.compile(r"[0-9]+") busqueda = expresion_rango.finditer(texto) for resultado in busqueda: print(resultado.group(0))
1830 1830 32 31 3155 958 276 9330 126 2019 67 287 14 000 300 1810 1821 0 774 74 17 10 12 12 000 6 1813 22 1814 28 1821 1824 1857 1917 30 000 9000 12 000 8000 1000 10 500 2500 1500 200 200 900 900 900 1300 1521 1517 1518 1520 13 1521 1525 1527 1535 300 1546 1540 1551 1734 1737 1761 8 300 1808 16 1810 1811 1813 1815 1815...
MIT
Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb
jorgeo80/UP_MDC
\ Por último, la barra invertida. Ya la había mencionado, sirve para eliminar el significado especial, pero tiene otro uso.Así como quita significado a los caracteres especiales, le da significado especial a caracteres normales para formar conjuntos preestablecidos (conjuntos como los que se podrían formar con los cor...
# Palabras de 12 letras expresion_12letras = re.compile(r"\b\w{12}\b") busqueda = expresion_12letras.finditer(texto) for resultado in busqueda: print(resultado.group(0))
oficialmente precolombina Organización considerados decimocuarta megadiversos denominación Constitución correspondía dependientes constituiría denominación antecedieron conformación Constitución Constitución Constitución generalizado prevaleciera Tenochtitlan peninsulares denominación significaría alternativos conocimi...
MIT
Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb
jorgeo80/UP_MDC
Los conjuntos se puden usar dentro de `[^ ]` para negarlos, pero muchas veces no hace falta ya que las letras mayúsculas (`\D, \S, \W`) ya significan lo opuesto de cada conjunto respectivamente.
# Palabras expresion = re.compile(r"\b\S+\b") busqueda = expresion.finditer(texto) for resultado in busqueda: print(resultado.group(0))
Se truncaron las últimas líneas 5000 del resultado de transmisión. escritor Carlos Monsiváis y el fotógrafo Gabriel Figueroa Cabe mencionar al director español nacionalizado mexicano Luis Buñuel y sus aportaciones al cine surrealista Un Chien Andalou y L'age D'Or ambas coproducidas con Salvador Dalí y que...
MIT
Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb
jorgeo80/UP_MDC
Grupos Para cerrar el tema, veremos los grupos, ya vimos como formarlos: con paréntesis `( )`. Pero cada paréntesis que se usa forma un grupo al cuál se le puede hacer referencia despúes.
# Se pueden usar los grupos dentro de la misma expresion expresion = re.compile(r"\b(\w+)\b(.*?)\b\1\b") busqueda = expresion.finditer(texto) for resultado in busqueda: print(resultado.group(1),len(resultado.group(2)))
1830 43 México 144 federal 74 tiene 217 de 124 el 43 México 335 en 56 el 50 en 114 el 128 y 35 en 204 la 100 la 242 de 106 la 189 y 48 por 80 en 191 es 122 12 50 término 809 como 37 que 206 de 77 de 12 como 593 gentilicio 314 de 11 del 39 de 52 es 59 del 584 vocablo 225 Clavijero 179 que 24 el 25 del 28 de 13 los 80 de...
MIT
Materias/ProcesamientoLenguaje/Clases/S01_003_RE.ipynb
jorgeo80/UP_MDC
Collaborative FilteringEstimated time needed: **25** minutes ObjectivesAfter completing this lab you will be able to:* Create recommendation system based on collaborative filtering Recommendation systems are a collection of algorithms used to recommend items to users based on information taken from the user. The...
!wget -O moviedataset.zip https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%205/data/moviedataset.zip print('unziping ...') !unzip -o -j moviedataset.zip
--2021-09-11 13:35:55-- https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%205/data/moviedataset.zip Resolving cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)... 169.63.1...
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Now you're ready to start working with the data! Preprocessing First, let's get all of the imports out of the way:
#Dataframe manipulation library import pandas as pd #Math functions, we'll only need the sqrt function so let's import only that from math import sqrt import numpy as np import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Now let's read each file into their Dataframes:
#Storing the movie information into a pandas dataframe movies_df = pd.read_csv('movies.csv') #Storing the user information into a pandas dataframe ratings_df = pd.read_csv('ratings.csv')
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Let's also take a peek at how each of them are organized:
#Head is a function that gets the first N rows of a dataframe. N's default is 5. movies_df.head()
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
So each movie has a unique ID, a title with its release year along with it (Which may contain unicode characters) and several different genres in the same field. Let's remove the year from the title column and place it into its own one by using the handy [extract](http://pandas.pydata.org/pandas-docs/stable/generated/p...
#Using regular expressions to find a year stored between parentheses #We specify the parantheses so we don't conflict with movies that have years in their titles movies_df['year'] = movies_df.title.str.extract('(\(\d\d\d\d\))',expand=False) #Removing the parentheses movies_df['year'] = movies_df.year.str.extract('(\d\d...
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Let's look at the result!
movies_df.head()
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
With that, let's also drop the genres column since we won't need it for this particular recommendation system.
#Dropping the genres column movies_df = movies_df.drop('genres', 1)
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Here's the final movies dataframe:
movies_df.head()
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Next, let's look at the ratings dataframe.
ratings_df.head()
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Every row in the ratings dataframe has a user id associated with at least one movie, a rating and a timestamp showing when they reviewed it. We won't be needing the timestamp column, so let's drop it to save on memory.
#Drop removes a specified row or column from a dataframe ratings_df = ratings_df.drop('timestamp', 1)
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Here's how the final ratings Dataframe looks like:
ratings_df.head()
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Collaborative Filtering Now it's time to start our work on recommendation systems.The first technique we're going to take a look at is called **Collaborative Filtering**, which is also known as **User-User Filtering**. As hinted by its alternate name, this technique uses other users to recommend items to the input use...
userInput = [ {'title':'Breakfast Club, The', 'rating':5}, {'title':'Toy Story', 'rating':3.5}, {'title':'Jumanji', 'rating':2}, {'title':"Pulp Fiction", 'rating':5}, {'title':'Akira', 'rating':4.5} ] inputMovies = pd.DataFrame(userInput) inputMovies
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Add movieId to input userWith the input complete, let's extract the input movies's ID's from the movies dataframe and add them into it.We can achieve this by first filtering out the rows that contain the input movies' title and then merging this subset with the input dataframe. We also drop unnecessary columns for the...
#Filtering out the movies by title inputId = movies_df[movies_df['title'].isin(inputMovies['title'].tolist())] #Then merging it so we can get the movieId. It's implicitly merging it by title. inputMovies = pd.merge(inputId, inputMovies) #Dropping information we won't use from the input dataframe inputMovies = inputMovi...
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
The users who has seen the same moviesNow with the movie ID's in our input, we can now get the subset of users that have watched and reviewed the movies in our input.
#Filtering out users that have watched movies that the input has watched and storing it userSubset = ratings_df[ratings_df['movieId'].isin(inputMovies['movieId'].tolist())] userSubset.head()
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
We now group up the rows by user ID.
#Groupby creates several sub dataframes where they all have the same value in the column specified as the parameter userSubsetGroup = userSubset.groupby(['userId'])
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Let's look at one of the users, e.g. the one with userID=1130.
userSubsetGroup.get_group(1130)
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Let's also sort these groups so the users that share the most movies in common with the input have higher priority. This provides a richer recommendation since we won't go through every single user.
#Sorting it so users with movie most in common with the input will have priority userSubsetGroup = sorted(userSubsetGroup, key=lambda x: len(x[1]), reverse=True)
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Now let's look at the first user.
userSubsetGroup[0:3]
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Similarity of users to input userNext, we are going to compare all users (not really all !!!) to our specified user and find the one that is most similar.\we're going to find out how similar each user is to the input through the **Pearson Correlation Coefficient**. It is used to measure the strength of a linear associ...
userSubsetGroup = userSubsetGroup[0:100]
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Now, we calculate the Pearson Correlation between input user and subset group, and store it in a dictionary, where the key is the user Id and the value is the coefficient.
#Store the Pearson Correlation in a dictionary, where the key is the user Id and the value is the coefficient pearsonCorrelationDict = {} #For every user group in our subset for name, group in userSubsetGroup: #Let's start by sorting the input and current user group so the values aren't mixed up later on group...
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
The top x similar users to input userNow let's get the top 50 users that are most similar to the input.
topUsers=pearsonDF.sort_values(by='similarityIndex', ascending=False)[0:50] topUsers.head()
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Now, let's start recommending movies to the input user. Rating of selected users to all moviesWe're going to do this by taking the weighted average of the ratings of the movies using the Pearson Correlation as the weight. But to do this, we first need to get the movies watched by the users in our **pearsonDF** from the...
topUsersRating=topUsers.merge(ratings_df, left_on='userId', right_on='userId', how='inner') topUsersRating.head()
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Now all we need to do is simply multiply the movie rating by its weight (The similarity index), then sum up the new ratings and divide it by the sum of the weights.We can easily do this by simply multiplying two columns, then grouping up the dataframe by movieId and then dividing two columns:It shows the idea of all si...
#Multiplies the similarity by the user's ratings topUsersRating['weightedRating'] = topUsersRating['similarityIndex']*topUsersRating['rating'] topUsersRating.head() #Applies a sum to the topUsers after grouping it up by userId tempTopUsersRating = topUsersRating.groupby('movieId').sum()[['similarityIndex','weightedRati...
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
Now let's sort it and see the top 20 movies that the algorithm recommended!
recommendation_df = recommendation_df.sort_values(by='weighted average recommendation score', ascending=False) recommendation_df.head(10) movies_df.loc[movies_df['movieId'].isin(recommendation_df.head(10)['movieId'].tolist())]
_____no_output_____
BSD-4-Clause-UC
ML0101EN-RecSys-Collaborative-Filtering-movies-py-v1.ipynb
CosmiX-6/Mahine-Learning-with-Python
_Speech Processing Labs 2021: SIGNALS 2: Building the Source_
## Run this first! %matplotlib inline import matplotlib.pyplot as plt import numpy as np import cmath from math import floor from matplotlib.animation import FuncAnimation from IPython.display import HTML plt.style.use('ggplot') from dspMisc import *
_____no_output_____
MIT
signals/signals-lab-2/signals-2-1-impulse-as-source.ipynb
laic/uoe_speech_processing_course
Building the Source Learning Outcomes* Be able to describe what an impulse train is* Be able to explain why an impulse train is used to model the voice source* Be able to describe the frequency response of single impulse and and impulse train Need to Know* Topic Videos: Harmonics, Impulse Train, Frequency Domain* [Int...
## Set the number of samples N, sampling rate f_s ## As usual all our interpretation of the DFT outputs will depend on the values of these parameters N=64 #sampling rate: f_s = 64 ## sample time t_s = 1/f_s ## Check our parameters print("Number of samples: N = %d" % N) print("sampling rate: f_s = %f\nsampling time...
_____no_output_____
MIT
signals/signals-lab-2/signals-2-1-impulse-as-source.ipynb
laic/uoe_speech_processing_course
The plot above shows an time vs amplitude graph of input $x[n]$, where all but 1 of the $N=64$ input points are zero, and $x[1]=1$. Now let's look at the DFT of this single impulse.
## Now let's look at the DFT outputs of the impulse: mag_impulse, phase_impulse = get_dft_mag_phase(x_impulse, N) ## Note: in this case N=f_s so the DFT output frequencies are the same as the DFT output indices ## We'll look at cases where this differs later dft_freqs = get_dft_freqs_all(f_s, N) ## plot the magnitud...
_____no_output_____
MIT
signals/signals-lab-2/signals-2-1-impulse-as-source.ipynb
laic/uoe_speech_processing_course
Exercise: **Question*** What does the magnitude spectrum show? * What does the phase spectrum show? * How might this be useful for modelling the vocal source? Notes 2 From Impulse to Impulse TrainThe DFT analysis above showed us that a single impulse can potentially be linked to any frequency! This might not seem v...
## Let's keep the number of samples and the sampling rate the same as above N=64 f_s = 64 t_s = 1/f_s nsteps = np.array(range(N)) time_steps = t_s * nsteps ## Now let's create an impulse response: # create a sequence of length N but all zeros x_impulse_train = np.zeros(N) # set the impulse period to be 1 impulse eve...
_____no_output_____
MIT
signals/signals-lab-2/signals-2-1-impulse-as-source.ipynb
laic/uoe_speech_processing_course
You should see a repeated sequence over 1 second where every 4th sample has amplitude 1, and all the rest have value 0. DFT of an impulse trainNow let's look at the DFT of this impulse train.
## Get the DFT outputs: magnitude and phase mag_impulse_train, phase_impulse_train = get_dft_mag_phase(x_impulse_train, N) ## Get the DFT output frequencies, for plotting dft_freqs = get_dft_freqs_all(f_s, N) ## plot the magnitudes, but this time we're going to need to zoom in a bit on the y-axis: fig, fdom = plt.s...
_____no_output_____
MIT
signals/signals-lab-2/signals-2-1-impulse-as-source.ipynb
laic/uoe_speech_processing_course
The magnitude (top) plot indicates that the impulse train has frequency components at multiples of 8 Hz.The phase plot (bottom) doesn't show a phase shift. This also makes sense since our input sequence started with a 1, so acts like cosine with no phase shift. **Note** We only plotted the first $N/2$ DFT outputs sin...
def make_impulse_train(sample_rate, frequency, n_samples): # make an arrange of n_samples, all zeros to start x = np.zeros(n_samples) # Determine where the impulses go based on the sample rate # The time between samples: sample_time = 1/sample_rate #A frequency of f cycles/second means...
_____no_output_____
MIT
signals/signals-lab-2/signals-2-1-impulse-as-source.ipynb
laic/uoe_speech_processing_course
Neuromatch Academy 2020 -- Bayes Day (dry run) Tutorial 4 - Marginalization & Fitting to dataPlease execute the cell below to initialize the notebook environment
# @title import time # import time import numpy as np # import numpy import scipy as sp # import scipy import math # import basic math functions import random # import basic random number generator functions import matp...
_____no_output_____
CC-BY-4.0
tutorials/Bayes/TA_solutions/BayesDay_Tutorial_4_solutions.ipynb
sanchobarriga/course-content
--- Tutorial objectives In this notebook we'll have a look at computing the Marginalization Matrix and the Marginal in order to perform model inversion (i.e.: recovering the model parameters given a participant's data). The generative model will be the same Bayesian model we have been using in Tutorial 3 (Mixture of G...
hypothetical_stim = np.linspace(-8,8,1000) x = np.arange(-10,10,0.1) ################## ## Insert your code here to: ## - Generate a mixture of gaussian prior with mean 0 and std 0.5 and 10 respectively ## - Tile that row prior in order to make a matrix of 1000 row priors ## (Hint: use np.tile() an...
_____no_output_____
CC-BY-4.0
tutorials/Bayes/TA_solutions/BayesDay_Tutorial_4_solutions.ipynb
sanchobarriga/course-content
--- EXERCISE 2: Implement a Likelihood Matrix We now want to create a Likelihood matrix that is made up of a Gaussian on each row of the matrix. Each row represents a different hypothetically presented stimulus with a different stimulus offset (i.e. a different likelihood mean).**Suggestions** Using the equation fo...
likelihood_matrix = np.zeros_like(prior_matrix) ################## ## Insert your code here to: ## - Generate a likelihood matrix using `my_gaussian` function, with sigma = 1, ## and varying the mean using `hypothetical_stim` values. ## - Plot the Prior Matrix using the code snippet commented-out b...
_____no_output_____
CC-BY-4.0
tutorials/Bayes/TA_solutions/BayesDay_Tutorial_4_solutions.ipynb
sanchobarriga/course-content
--- EXERCISE 3: Implement the Posterior Matrix We now want to create the Posterior matrix. To do so, we will compute the posterior using *Bayes rule* for each trial (i.e. row_wise).That is, each row of the posterior matrix will be the posterior resulting from the multiplication of the prior and likelihood of the equ...
posterior_matrix = np.zeros_like(likelihood_matrix) ############################################################################### ## Insert your code here to: ## For each row of the Prior & Likelihood Matrices, calculate the resulting posterior ## Fill the Posterior Matrix with the row_posterior ## ...
_____no_output_____
CC-BY-4.0
tutorials/Bayes/TA_solutions/BayesDay_Tutorial_4_solutions.ipynb
sanchobarriga/course-content
--- EXERCISE 4: Implement the Binary Decision Matrix We now want to create the a Binary Decision Matrix. To do so, we will scan the Posterior matrix (i.e. row_wise), and set the matrix cell to 1 at the mean of the row posterior.This, effectively encodes the *decision* that a participant may make on a given trial (i....
binary_decision_matrix = np.zeros_like(posterior_matrix) ############################################################################### ## Insert your code here to: ## Create a matrix of the same size as the Posterior matrix and fill it with zeros (Hint: use np.zeros_like()) ## For each row of the Poste...
_____no_output_____
CC-BY-4.0
tutorials/Bayes/TA_solutions/BayesDay_Tutorial_4_solutions.ipynb
sanchobarriga/course-content
--- EXERCISE 5: Implement the Input Matrix We now want to create the Input Matrix from the true presented stimulus. That is, we will now create a Gaussian centered around the true presented stimulus, with sigma = 1. and repeat that gaussian distribution across x values. That is we want to make a *Column* gaussian ce...
input_matrix = np.zeros_like(posterior_matrix) ################## ## Insert your code here to: ## - Generate a gaussian centered on the true stimulus -2.5 with sigma = 1 ## - Tile that column input Gaussian in order to complete the matrix ## (Hint: use np.tile() and np.reshape()) ## - Plot th...
_____no_output_____
CC-BY-4.0
tutorials/Bayes/TA_solutions/BayesDay_Tutorial_4_solutions.ipynb
sanchobarriga/course-content
--- EXERCISE 5: Implement the Marginalization Matrix We now want to compute the Marginalization Matrix from the true presented stimulus, and our Binary decision matrix over hypothetical stimulus inputs. Mathematically, this means that we want to compute:\begin{eqnarray} Marginalization Matrix = Input Matrix \odot...
marginalization_matrix = np.zeros_like(posterior_matrix) ############################################################################### ## Insert your code here to: ## Compute the Marginalization matrix by multiplying pointwise the Binary decision matrix over hypothetical stimuli and the Input Matrix ## ...
_____no_output_____
CC-BY-4.0
tutorials/Bayes/TA_solutions/BayesDay_Tutorial_4_solutions.ipynb
sanchobarriga/course-content
--- EXERCISE 6: Generate some DataNow that we've seen how to calculate the posterior and marginalize to get $p(\hat{x} \mid x)$ we will generate some artificial data for a single participant using the `generate_data()` function provided, and mixing parameter $\alpha$ = 0.1Please run the code below:
def generate_data(x_stim, alpha): """ DO NOT EDIT THIS FUNCTION !!! Returns the mean, median and mode of an arbitrary function Args : x_stim (numpy array of floats) - x values at which stimuli are presented alpha (scalar) - mixture component for the Mixture of Gaussian prior Returns: (numpy ar...
_____no_output_____
CC-BY-4.0
tutorials/Bayes/TA_solutions/BayesDay_Tutorial_4_solutions.ipynb
sanchobarriga/course-content
--- EXERCISE 7: Model fitting to generated dataNow that we have generated some data and that we have seen how to calculate the posterior and marginalize to get $p(\hat{x} \mid x)$ we will attempt to recover the parameter alpha = 0.05 that was use to generate the data.We have provided you with an incomplete function cal...
def my_Bayes_model_mse(params): """ Function fits the Bayesian model from Tutorial 3 Args : params (list of positive floats): parameters used by the model (params[0] = posterior scaling) Returns : (scalar) negative log-likelihood :sum of log probabilities """ trial_ll = np.ze...
_____no_output_____
CC-BY-4.0
tutorials/Bayes/TA_solutions/BayesDay_Tutorial_4_solutions.ipynb
sanchobarriga/course-content
**Nguyễn Tiến Dũng**20170062KSTN Toán Tin - K62*Đại học Bách khoa Hà Nội*
import processviz as pvz
[[1.61486158 1.02476931 0.63137445 0.36911122 0.19426906 0.07770763] [1.53715396 2.56192326 1.57843613 0.92277805 0.48567266 0.19426906] [1.42059252 2.3676542 2.99902865 1.75327829 0.92277805 0.36911122] [1.24575036 2.07625061 2.62991744 2.99902865 1.57843613 0.63137445] [0.98348713 1.63914522 2.07625061 2.3676542...
BSD-3-Clause
assignment/.ipynb_checkpoints/Assignment_4.2-checkpoint.ipynb
jurgendn/processviz
**Câu 1:**Đầu tiên, dễ thấy $(X_n)$ là một xích Markov.Ta tìm ma trận xác suất chuyển của xích:$$P = \left(\begin{matrix}0& \frac{1}{2} & 0 & \frac{1}{2}\\\frac{1}{2} & 0 & \frac{1}{2} & 0 \\0& \frac{1}{2} & 0 & \frac{1}{2}\\\frac{1}{2} & 0 & \frac{1}{2} & 0\end{matrix}\right)$$*a.* Dễ thấy xích Markov trên là tối giản...
G1 = pvz.MarkovChain() G1.from_file('./ass4.2/input_1.csv') G1.classify_state()
_____no_output_____
BSD-3-Clause
assignment/.ipynb_checkpoints/Assignment_4.2-checkpoint.ipynb
jurgendn/processviz
*b.*Gọi 1 dãy các bước đi ngẫu nhiên của con châu chấu là $(x_0,...,x_{100})$. Dễ thây để con châu chấu trở lại $x_0$ sau đúng 100 bước thì cần có $x_0 = x_{100}$ và $x_i \ne x_0,\forall i = \overline{1,99}$. Ta có $x_0 = 0$. Điều này dẫn đến $x_1 = 2$. Tại thời điểm $2n$ thấy rằng $x_{2n} \in \{1,3\}$ và $x_{2n+1} = ...
G2 = pvz.MarkovChain() G2.from_file('./ass4.2/input_2.csv') G2.get_period('NSN')
_____no_output_____
BSD-3-Clause
assignment/.ipynb_checkpoints/Assignment_4.2-checkpoint.ipynb
jurgendn/processviz
Vậy trung bình mất số lần tung như trên để đạt đến trạng thái $NSN$--- **Câu 3:**Không gian trạng thái `I = {CS_THONGTHUONG, CS_DACBIET,CS_TANGCUONG,DONG_HOP, KHOI_BENH}`Ma trận xác suất chuyển| CS_THONGTHUONG | CS_DACBIET | CS_TANGCUONG | DONG_HOP | KHOI_BENH || -------------- | ---------- | ------------ | -------- | ...
G3 = pvz.MarkovChain() G3.from_file('./ass4.2/input_3.csv') G3.get_mean_time(source='CS_TANGCUONG', target='CS_TANGCUONG', type='transient')
_____no_output_____
BSD-3-Clause
assignment/.ipynb_checkpoints/Assignment_4.2-checkpoint.ipynb
jurgendn/processviz
*b.* Xác suất một bệnh nhân ở phòng ICU liên tiếp $k$ ngày là $0.55^k$Do đó số ngày trung bình để bệnh nhân đó tiếp tục phải ở lại chăm sóc tại phòng ICU là$$E(X|) = \underset{n \to \infty}{lim}\sum_{k = 1}^{n}k*0.55^k$$Xét $$\begin{aligned}f(x) & = \sum_{i = 1}^{n}x^i \\\Rightarrow f'(x) & = \sum_{i = 1}^{n-1}ix^{i-1}...
G4 = pvz.MarkovChain() G4.from_file('./ass4.2/input_4.csv')
_____no_output_____
BSD-3-Clause
assignment/.ipynb_checkpoints/Assignment_4.2-checkpoint.ipynb
jurgendn/processviz
! pip3 install face_recognition ! pip3 install tensorflow-gpu==1.15 import numpy as np import argparse import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, models, transforms from PIL import Image import face_recognition PATH = "http://www.robots.ox.ac.uk/~albanie/model...
Collecting torchfile Downloading https://files.pythonhosted.org/packages/91/af/5b305f86f2d218091af657ddb53f984ecbd9518ca9fe8ef4103a007252c9/torchfile-0.1.0.tar.gz Building wheels for collected packages: torchfile Building wheel for torchfile (setup.py) ... [?25l[?25hdone Created wheel for torchfile: filename=to...
MIT
old-notebooks/Decoder_damaged.ipynb
antoniomuso/speech2face
Dataloader
from os.path import join import torch import numpy as np from torch.utils.data import Dataset, DataLoader import cv2 from time import time import face_recognition from random import randint from google.colab.patches import cv2_imshow class Decoder_Dataset(Dataset): def __init__(self, Folder, VggL, sample, d...
---------------------------------------------------------------- Layer (type) Output Shape Param # ================================================================ Linear-1 [-1, 1000] 4,097,000 ReLU-2 [-1, 1000] ...
MIT
old-notebooks/Decoder_damaged.ipynb
antoniomuso/speech2face
Training
import os optimizer = torch.optim.Adam(model.parameters(), lr=0.009) criterion_1 = nn.MSELoss() criterion_2 = nn.L1Loss() criterion_3 = nn.CosineEmbeddingLoss() alpha = 0.0002 beta = 1.0 gamma = 1.5 l = 10 BATCH = 10 WORKER = 0 SAMPLE = 20 num_epochs = 5 sim = torch.ones((BATCH,1, 128 )) train_dataset = Decoder_Datase...
_____no_output_____
MIT
old-notebooks/Decoder_damaged.ipynb
antoniomuso/speech2face
Getting only data of 4s and 9s
new_labels_4 = [] new_images_4 = [] new_labels_9 = [] new_images_9 = [] for images, labels in train: images = Variable(images.view(-1, 28*28)) for i,label in enumerate(labels): if label == 4: new_labels_4.append(label) new_images_4.append(images[i].numpy()) elif label =...
_____no_output_____
Apache-2.0
fdm/fdm_code/failure_in_4_9.ipynb
yurilavinas/failure_diversity_maximisation
How the output is like after mixing 4s with some 9 data
fig = plt.figure(figsize=(8,8)); columns = 4; rows = 5; for i in range(1, columns*rows +1): img_xy = np.random.randint(len(new_images_4)) img = torch.from_numpy(new_images_4[img_xy]) img.resize_(28,28) fig.add_subplot(rows, columns, i) plt.axis('off') plt.imshow(img, cmap='gray') plt.show() thr...
_____no_output_____
Apache-2.0
fdm/fdm_code/failure_in_4_9.ipynb
yurilavinas/failure_diversity_maximisation
How the output is like after mixing 9s with some 4 data
fig = plt.figure(figsize=(8,8)); columns = 4; rows = 5; for i in range(1, columns*rows +1): img_xy = np.random.randint(len(new_images_9)) img = torch.from_numpy(new_images_9[img_xy]) img.resize_(28,28) fig.add_subplot(rows, columns, i) plt.axis('off') plt.imshow(img, cmap='gray') plt.show() cla...
_____no_output_____
Apache-2.0
fdm/fdm_code/failure_in_4_9.ipynb
yurilavinas/failure_diversity_maximisation
Net with mixed data
net3 = Net(input_size, hidden_size, num_classes) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(net3.parameters(), lr=learning_rate) losses = [] for epoch in range(num_epochs): for i in range(int(len(f_images)/batch_size)): idx = list(range(batch_size*i,(batch_size*(i+1)))) images =...
Accuracy of the network on the 10K test images: 91 %
Apache-2.0
fdm/fdm_code/failure_in_4_9.ipynb
yurilavinas/failure_diversity_maximisation
Problem Set - Dynamic life-cycle models of human capital accumulation with respyIn this problem set, we will work with Eckstein-Keane-Wolpin (EKW) models, a class of dynamic discrete choice models that are used to address economic questions in the realm of labor and education economics. Prominent examples of such mode...
import timeit import respy as rp import pandas as pd import numpy as np import matplotlib.pyplot as plt
_____no_output_____
MIT
respy-problem-set.ipynb
amageh/respy-tut
Economic Setting: Robinson Crusoe on an island- Robinson chooses every period $t = 0, \dots, T$ to either go fishing, $a = 0$, or spend the day in the hammock, $a = 1$.- If Robinson chooses to go fishing, he gains one additional unit of experience in the next period. Experience starts at zero.- The utility of a choice...
params, options, data = rp.get_example_model("robinson_crusoe_basic")
_____no_output_____
MIT
respy-problem-set.ipynb
amageh/respy-tut
Working with Sequence files using BiopythonThe code boxes below will increase in complexity as we go on. Comments in the code begin with s. Read these if you want help understanding the code.In the first code box below, the first line "turns on" the SeqIO function of Biopython, a package (set of tools) built for biolo...
from Bio import SeqIO # imports the SeqIO function from Biopython records = list(SeqIO.parse("<<<your file here>>>", "fasta")) # reads the fasta file into a list of records print("Finished storing the FASTA file in the list called \"records\".")
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
While this did read the fasta file into a list of records, it isn't obvious how this helps us. Let's see how we can access different information about the sequence records stored in the list, records.STEP 2: The first line below will tell us how many sequences were in the fasta file, and then the information stored in ...
print("There are %i sequences in your file.\n" % len(records)) # prints the number of sequences, that is, the length of the list, named records print(records[0]) #prints the information in the first record
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
You should be able to see that first record includes several things: an ID, Name, Description, and a Sequence.We can access each of those items specificallySTEP 3: Run the code below to print only the sequence of the first record.
print(records[0].seq)
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
The next code box shows us how to list the first 10 ids. Then it lists the first record id and its sequence.STEP 4: Run the code box below.
print("The first 10 sequence record ids are:\n") for i in range(10): # this creates a variable i and counts to 10 print(records[i].id) # prints the id for record i print("\nThe record: %s has a sequence of: %s\n" % (records[-1...
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
***Great! The code above finds the first record (recall in Python we start counting at zero), so records[0].id gets the identification of the first record. STEP 5: Edit the last print statement in the code above to give the id and sequence of the 100th record.We can also look at the last record id. You could put in the...
import re # imports the re (Regular Expressions) functions search_term = "<<<search term here>>>" # in between the quotes we can add a search term. counter = 0 # a variable to keep track of how many times we find the term for item in records: # thi...
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
***STEP 9: Edit the code above to search the description rather than the ID. Make sure to change it in both places!***Using Biopython's SeqIO function allows us to store lots of data in a way that is rapidly accessible.As you have seen above, the IDs are a little long and redundant with the name. The code below simplif...
original_file = "files/uniprot-dtxr.fasta" # original file path simple_file = "files/uniprot-dtxr_simple.fasta" # new file path with open(original_file) as original, open(simple_file, 'w') as simple: #opens the file to read and one to write records = SeqIO.parse(original, 'fasta') # here we use the Bi...
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
There is no output given for the above code. Let's consider how we changed this file by looking at the simplfied file.STEP 11: You can find the new file in the file browser in the left of your screen and double click to open it. *** Big Data Strategies - Filtering and Reducing Redundancy in DatasetsNow that we have a s...
import matplotlib.pyplot as plt records = list(SeqIO.parse("files/uniprot-dtxr_simple.fasta", "fasta")) lengths = [] for i in records: #print(i.seq) lengths.append(len(i.seq)) lengths.sort() #print(lengths) plt.hist(lengths, bins = 100) plt.xlabel('seq length') plt.ylabel('count') plt.show()
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
STEP 13: Answer the question: 1. Using the histogram, what are the most common lengths of proteins in this dataset?***We will further reduce the complexity of this dataset by removing sequences that are much larger and much smaller than the most common lengths shown. Those variables can be determined using a histogr...
from Bio import SeqIO original_file = "files/uniprot-dtxr_simple.fasta" trimmed_file = "files/uniprot-dtxr_simple_trim.fasta" small_len = 115 large_len = 250 with open(original_file) as original, open(trimmed_file, 'w') as trimmed: records = SeqIO.parse(original_file, 'fasta') for record in records: ...
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
The above procedure removed about 5,000 sequences. This is a good start, but still a lot of sequences to visualize.*** Reducing sequence redundancy using CD-HITWe will use the program CD-HIT to remove sequence within a given sequence similarity to another sequence. For example, the flag "-c 0.4" given below will keep o...
!cd-hit -i files/uniprot-dtxr_simple_trim.fasta -o files/uniprot-dtxr_40.fasta -c 0.4 -n 2
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
CD-HIT has reduced over 30,000 sequences to under 2000 at 40% sequence identity! This is one strategy for dealing with very large datasets - they can be reduced. However, reduction needs to be done in a logical and reproducible manner. CD-HIT does just that. Again, depending on how closely related these proteins are, w...
!cat "files/uniprot-dtxr_40.fasta" "files/dtxr_pdbs.fasta" > "files/final_40.fasta"
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
STEP 17: Run the code below to determine the final number of sequences in your file!
records = list(SeqIO.parse("files/final_40.fasta", "fasta")) # use SeqIO to process the file print("There are %i sequences in your file.\n" % len(records)) # print the number of sequences
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
*** Making a BLAST-able database and performing an all-by-all BLAST searchNow that we have our dataset we are going to use some of the NCBI BLAST tools to 1) create a searchable database using our processed set of sequences and 2) use protein BLAST to complete an all-by-all search of that database using each of those s...
!makeblastdb -help
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
The output above tells us the application of the program and how to indicate input and outout files.STEP 19: In the code box below we have added input and output files and told the program it is a protein database. The input is the files/final_40.fasta file. We will name the output files files/finalpro_40. Go ahead and...
!makeblastdb -in files/final_40.fasta -dbtype prot -out files/finalpro_40
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
That last step was really quite fast given the smaller number of sequences. You can try this with more sequences, it will be slower, but you might need to use more sequences to find connections among your proteins. We should be good with this number for the exercise today.STEP 20: Next we want to use blastp (Basic Loca...
!blastp -help
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
STEP 21: This is the final step in generating new data to visualize in the next Jupyter Notebook. We will run the code below to use blastp to search the files/finalpro_40 database using each of the sequences in the files/final_40.fasta file. To be very clear - this will run almost 2000 BLAST searches!!!The outfmt contr...
!blastp -db files/finalpro_40 -query files/final_40.fasta -outfmt "6 qseqid sseqid evalue" -out files/BLASTe40_out -num_threads 4 -evalue 10e-40
_____no_output_____
CC0-1.0
2 - Sequences_and_BLAST - v9.ipynb
CassTerrell/my-first-binder
Working with RNNs**Authors:** Scott Zhu, Francois Chollet**Date created:** 2019/07/08**Last modified:** 2020/04/14**Description:** Complete guide to using & customizing RNN layers. IntroductionRecurrent neural networks (RNN) are a class of neural networks that is powerful formodeling sequence data such as time series...
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
Built-in RNN layers: a simple example There are three built-in RNN layers in Keras:1. `keras.layers.SimpleRNN`, a fully-connected RNN where the output from previoustimestep is to be fed to next timestep.2. `keras.layers.GRU`, first proposed in[Cho et al., 2014](https://arxiv.org/abs/1406.1078).3. `keras.layers.LSTM`, ...
model = keras.Sequential() # Add an Embedding layer expecting input vocab of size 1000, and # output embedding dimension of size 64. model.add(layers.Embedding(input_dim=1000, output_dim=64)) # Add a LSTM layer with 128 internal units. model.add(layers.LSTM(128)) # Add a Dense layer with 10 units. model.add(layers.De...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
Built-in RNNs support a number of useful features:- Recurrent dropout, via the `dropout` and `recurrent_dropout` arguments- Ability to process an input sequence in reverse, via the `go_backwards` argument- Loop unrolling (which can lead to a large speedup when processing short sequences onCPU), via the `unroll` argumen...
model = keras.Sequential() model.add(layers.Embedding(input_dim=1000, output_dim=64)) # The output of GRU will be a 3D tensor of shape (batch_size, timesteps, 256) model.add(layers.GRU(256, return_sequences=True)) # The output of SimpleRNN will be a 2D tensor of shape (batch_size, 128) model.add(layers.SimpleRNN(128)...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
In addition, a RNN layer can return its final internal state(s). The returned statescan be used to resume the RNN execution later, or[to initialize another RNN](https://arxiv.org/abs/1409.3215).This setting is commonly used in theencoder-decoder sequence-to-sequence model, where the encoder final state is used asthe in...
encoder_vocab = 1000 decoder_vocab = 2000 encoder_input = layers.Input(shape=(None,)) encoder_embedded = layers.Embedding(input_dim=encoder_vocab, output_dim=64)( encoder_input ) # Return states in addition to output output, state_h, state_c = layers.LSTM(64, return_state=True, name="encoder")( encoder_embedd...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
RNN layers and RNN cellsIn addition to the built-in RNN layers, the RNN API also provides cell-level APIs.Unlike RNN layers, which processes whole batches of input sequences, the RNN cell onlyprocesses a single timestep.The cell is the inside of the `for` loop of a RNN layer. Wrapping a cell inside a`keras.layers.RNN`...
paragraph1 = np.random.random((20, 10, 50)).astype(np.float32) paragraph2 = np.random.random((20, 10, 50)).astype(np.float32) paragraph3 = np.random.random((20, 10, 50)).astype(np.float32) lstm_layer = layers.LSTM(64, stateful=True) output = lstm_layer(paragraph1) output = lstm_layer(paragraph2) output = lstm_layer(pa...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
RNN State Reuse The recorded states of the RNN layer are not included in the `layer.weights()`. If youwould like to reuse the state from a RNN layer, you can retrieve the states value by`layer.states` and use it as theinitial state for a new layer via the Keras functional API like `new_layer(inputs,initial_state=layer...
paragraph1 = np.random.random((20, 10, 50)).astype(np.float32) paragraph2 = np.random.random((20, 10, 50)).astype(np.float32) paragraph3 = np.random.random((20, 10, 50)).astype(np.float32) lstm_layer = layers.LSTM(64, stateful=True) output = lstm_layer(paragraph1) output = lstm_layer(paragraph2) existing_state = lstm...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
Bidirectional RNNsFor sequences other than time series (e.g. text), it is often the case that a RNN modelcan perform better if it not only processes sequence from start to end, but alsobackwards. For example, to predict the next word in a sentence, it is often useful tohave the context around the word, not only just t...
model = keras.Sequential() model.add( layers.Bidirectional(layers.LSTM(64, return_sequences=True), input_shape=(5, 10)) ) model.add(layers.Bidirectional(layers.LSTM(32))) model.add(layers.Dense(10)) model.summary()
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
Under the hood, `Bidirectional` will copy the RNN layer passed in, and flip the`go_backwards` field of the newly copied layer, so that it will process the inputs inreverse order.The output of the `Bidirectional` RNN will be, by default, the sum of the forward layeroutput and the backward layer output. If you need a dif...
batch_size = 64 # Each MNIST image batch is a tensor of shape (batch_size, 28, 28). # Each input sequence will be of size (28, 28) (height is treated like time). input_dim = 28 units = 64 output_size = 10 # labels are from 0 to 9 # Build the RNN model def build_model(allow_cudnn_kernel=True): # CuDNN is only ava...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
Let's load the MNIST dataset:
mnist = 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 sample, sample_label = x_train[0], y_train[0]
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
Let's create a model instance and train it.We choose `sparse_categorical_crossentropy` as the loss function for the model. Theoutput of the model has shape of `[batch_size, 10]`. The target for the model is ainteger vector, each of the integer is in the range of 0 to 9.
model = build_model(allow_cudnn_kernel=True) model.compile( loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer="sgd", metrics=["accuracy"], ) model.fit( x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1 )
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
Now, let's compare to a model that does not use the CuDNN kernel:
noncudnn_model = build_model(allow_cudnn_kernel=False) noncudnn_model.set_weights(model.get_weights()) noncudnn_model.compile( loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer="sgd", metrics=["accuracy"], ) noncudnn_model.fit( x_train, y_train, validation_data=(x_test, y_test...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
When running on a machine with a NVIDIA GPU and CuDNN installed,the model built with CuDNN is much faster to train compared to themodel that use the regular TensorFlow kernel.The same CuDNN-enabled model can also be use to run inference in a CPU-onlyenvironment. The `tf.device` annotation below is just forcing the devi...
import matplotlib.pyplot as plt with tf.device("CPU:0"): cpu_model = build_model(allow_cudnn_kernel=True) cpu_model.set_weights(model.get_weights()) result = tf.argmax(cpu_model.predict_on_batch(tf.expand_dims(sample, 0)), axis=1) print( "Predicted result is: %s, target result is: %s" % (result...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
RNNs with list/dict inputs, or nested inputsNested structures allow implementers to include more information within a singletimestep. For example, a video frame could have audio and video input at the sametime. The data shape in this case could be:`[batch, timestep, {"video": [height, width, channel], "audio": [freque...
class NestedCell(keras.layers.Layer): def __init__(self, unit_1, unit_2, unit_3, **kwargs): self.unit_1 = unit_1 self.unit_2 = unit_2 self.unit_3 = unit_3 self.state_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])] self.output_size = [tf.TensorShape([unit_...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
Build a RNN model with nested input/outputLet's build a Keras model that uses a `keras.layers.RNN` layer and the custom cellwe just defined.
unit_1 = 10 unit_2 = 20 unit_3 = 30 i1 = 32 i2 = 64 i3 = 32 batch_size = 64 num_batches = 10 timestep = 50 cell = NestedCell(unit_1, unit_2, unit_3) rnn = keras.layers.RNN(cell) input_1 = keras.Input((None, i1)) input_2 = keras.Input((None, i2, i3)) outputs = rnn((input_1, input_2)) model = keras.models.Model([inp...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
Train the model with randomly generated dataSince there isn't a good candidate dataset for this model, we use random Numpy data fordemonstration.
input_1_data = np.random.random((batch_size * num_batches, timestep, i1)) input_2_data = np.random.random((batch_size * num_batches, timestep, i2, i3)) target_1_data = np.random.random((batch_size * num_batches, unit_1)) target_2_data = np.random.random((batch_size * num_batches, unit_2, unit_3)) input_data = [input_1_...
_____no_output_____
Apache-2.0
guides/ipynb/working_with_rnns.ipynb
miykael/keras-io
1) GET LIBRARY
import numpy as np import random import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LinearRegression import pandas as pd
_____no_output_____
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
2) GENERATE DATA
np.random.seed(1234) def generate_toy_data(n, lam, a, b): '''Generate random number from poisson distribution. Input: n = number of data points to generate lam = lambda of the poisson distribution a, b = any positive coefficient (since we want to simulate demand) Output: x = independen...
_____no_output_____
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
3) IMPLEMENT SIMPLE PREDICTION
# split data to training and testing set train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.2) df_train = pd.DataFrame({'train_x': train_x.flatten(), 'train_y': train_y.flatten()}) df_test = pd.DataFrame({'test_x': test_x.flatten(), 'test_y': test_y.flatten()})
_____no_output_____
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
a) RANDOM FOREST
rf = RandomForestRegressor(n_estimators = 1000, random_state = 42) rf.fit(train_x, train_y) test_y_rfpred = (rf.predict(test_x)).astype(int) err_rf = abs(test_y_rfpred - test_y) print('Mean Absolute Error:', round(np.mean(err_rf), 2), 'degrees.')
Mean Absolute Error: 3.05 degrees.
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
b) LINEAR REGRESSION
lr = LinearRegression() lr.fit(train_x, train_y) test_y_lrpred = (rf.predict(test_x)).astype(int) err_lr = abs(test_y_lrpred - test_y) print('Mean Absolute Error:', round(np.mean(err_lr), 2), 'degrees.') # check coefficient print(lr.coef_) print(lr.intercept_)
[[0.25079062]] [1.54812364]
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
c) SUMMARIZE RESULT & CHECK GRAPH (RANDOM FOREST & LINREG)
df_summ = pd.DataFrame({'test_x': test_x.flatten(), 'test_y': test_y.flatten(), 'test_y_rfpred': test_y_rfpred.flatten(), 'test_y_lrpred': test_y_lrpred.flatten()}) df_summ['diff_rf_actual'] = df_summ['test_y_rfpred'] - df_summ['test_y'] df_summ[...
_____no_output_____
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
4) STOCHASTIC PROGRAMMING a) DISCRETIZING DEMAND: TO CAPTURE PROBABILITY OF EACH POSSIBLE SCENARIO
# capturing probability of each possible scenario can be done in many ways, # ranging from simple descriptive analytics to more complicated things like # moment matching, monte carlo simulation, etc. # we do the easiest here: do clustering to generate scenario (max 100 scenario for now) from sklearn.cluster import KM...
_____no_output_____
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
b) USING PULP TO SOLVE STOCHASTIC PROGRAMMING
# !pip install pulp pygmo deap from pulp import * N = 100 # maximum item to purchase cost_price = 20 # amount paid to the supplier sell_price = 21 # amount paid by the customer waste_price = 0 # amount paid if we sell the remaining goods (ie. when we have more stock as prediction > demand) ####################...
Status = Optimal x = 22.000000 z_1 = 19.000000 z_2 = 20.000000 z_3 = 21.000000 z_4 = 22.000000 z_5 = 22.000000 z_6 = 22.000000 z_7 = 22.000000 z_8 = 22.000000 z_9 = 22.000000 z_10 = 22.000000 z_11 = 22.000000 z_12 = 22.000000 z_13 = 22.000000 z_14 = 22.000000 z_15 = 22.000000 z_16 = 22.000000 Objective = 21.396250
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
c) CHECK AS TABLE (MANUAL CALCULATION): TO SEE CLEARLY WHAT HAPPENS
def result_summ(cluster_proportion_df, demand, weight, sell_price, cost_price, waste_price): '''Summarize result by comparing possible scenario (example_df) with its possible execution (purchase_df). We want to look how much profit we can get given a pair of scenario and its execution, weighted with the pr...
_____no_output_____
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
d) VISUAL CHECK
# limit the table, we don't want to be overwhelmed temp = example_df[(example_df['item_to_purchase'] >= 20) & (example_df['item_to_purchase'] <= 25)] temp.loc[:,'item_to_purchase'] = temp['item_to_purchase'].astype('str') # check the weighted profit per possible scenario: # we can see how higher execution causes great...
_____no_output_____
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
5) PREDICTION + STOCHASTIC PROGRAMMING a) BOOTSTRAPPING
size_bstrap = 50 iter = 100 idx_check = 172 test_y_bstrap = [] coef_bstrap = [] intercept_bstrap = [] for i in range(iter): # sampling with replacement idx = np.random.choice(np.arange(0,train_x.shape[0]), size_bstrap, replace=True) train_x_temp = train_x[idx] train_y_temp = train_y[idx] ...
_____no_output_____
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
b) DISCRETIZING DEMAND
cluster_proportion_df_bstrap, demand_bstrap, weight_bstrap, scenarios_bstrap = cluster_summ(df=result_bstrap['test_y_bstrap']) print(demand_bstrap) print(weight_bstrap) print(scenarios_bstrap)
{1: 26.0} {1: 1.0} range(1, 2)
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase
c) USING PULP TO SOLVE STOCHASTIC PROGRAMMING
########################################## # DEFINE VARIABLES ########################################## M_bstrap = LpProblem("Newsvendor2", LpMaximize) x_bstrap = LpVariable('x_bstrap', lowBound=0) z_bstrap = LpVariable.dicts('z_bstrap', scenarios_bstrap, 0) ########################################## # DEFINE MODE...
33.0 0.13 34.0 0.87 Status = Optimal x_bstrap = 33.000000 z_bstrap_1 = 33.000000 z_bstrap_2 = 33.000000 Objective = 33.000000
BSD-3-Clause
misc - work/stochastic_ml_blend.ipynb
jkapila/paper-codebase