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
Shapiro-Wilk Test
# define Shapiro Wilk Test function def shapiro_test(data): '''calculate K-S Test for and out results in table''' data = data._get_numeric_data() data_shapiro_test = pd.DataFrame() # Iterate over columns, calculate test statistic & create table for column in data: column_shapiro_t...
_____no_output_____
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses
Histograms **Histograms: Likert-scale variables**
for column in df._get_numeric_data().drop(columns=['assessed PEB','age']): sns.set(rc={'figure.figsize':(5,5)}) data = df[column] sns.histplot(data, bins=np.arange(1,9)-.5) plt.xlabel(column) plt.show()
_____no_output_____
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses
**Histogramm: age**
sns.histplot(df['age'], bins=10)
_____no_output_____
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses
**Histogramm: assessed PEB**
sns.histplot(df['assessed PEB'], bins=np.arange(0,8)-.5)
_____no_output_____
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses
Kendall's Tau correlation
# create df with correlation coefficient and p-value indication def kendall_pval(x,y): return kendalltau(x,y)[1] # calculate kendall's tau correlation with p values ( < .01 = ***, < .05 = **, < .1 = *) tau = df.corr(method = 'kendall').round(decimals=2) pval = df.corr(method=kendall_pval) - np.eye(*tau.shape) p =...
_____no_output_____
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses
Correlation Heatmap All not significant correlations (p < .05) are not shown.
# calculate correlation coefficient corr = df.corr(method='kendall') # calculate column correlations and make a seaborn heatmap sns.set(rc={'figure.figsize':(12,12)}) ax = sns.heatmap( corr, vmin=-1, vmax=1, center=0, cmap=sns.diverging_palette(20, 220, n=200), square=True ) ax.set_xticklabels( ...
_____no_output_____
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses
Cherry Blossoms!If we travel back in time a few months, [cherry blossoms](https://en.wikipedia.org/wiki/Cherry_blossom) were in full bloom! We don't live in Japan or DC, but we do have our fair share of the trees - buuut you sadly missed [Brooklyn Botanic Garden's annual festival](https://www.bbg.org/visit/event/sakur...
import pandas as pd import numpy as np %matplotlib inline
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
1. Read in the file using pandas, and look at the first five rows
df = pd.read_excel("KyotoFullFlower7.xls") df.head(5)
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
2. Read in the file using pandas CORRECTLY, and look at the first five rowsHrm, how do your column names look? Read the file in again but this time add a parameter to make sure your columns look right.**TIP: The first year should be 801 AD, and it should not have any dates or anything.**
df=df[25:] df df.dtypes df.head(5)
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
3. Look at the final five rows of the data
df.tail(5)
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
4. Add some more NaN values It looks like you should probably have some NaN/missing values earlier on in the dataset under "Reference name." Read in the file *one more time*, this time making sure all of those missing reference names actually show up as `NaN` instead of `-`.
df.replace("-", np.nan, inplace=True) df df.rename(columns={'Full-flowering dates of Japanese cherry (Prunus jamasakura) at Kyoto, Japan. (Latest version, Jun. 12, 2012)': 'AD', 'Unnamed:_1': 'Full-flowering date'}, inplace=True) df.rename(columns={'Unnamed: 1': 'DOY', 'Unnamed: 2': 'Full_flowering_date', 'Unnamed: 3':...
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
5. What source is the most common as a reference?
df.dtypes df.Source_code.value_counts()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
6. Filter the list to only include columns where the `Full-flowering date (DOY)` is not missingIf you'd like to do it in two steps (which might be easier to think through), first figure out how to test whether a column is empty/missing/null/NaN, get the list of `True`/`False` values, and then later feed it to your `df...
df.DOY.value_counts(dropna=False)
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
7. Make a histogram of the full-flowering dateIs it not showing up? Remember the "magic" command that makes graphs show up in matplotlib notebooks!
df.DOY.value_counts().hist()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
8. Make another histogram of the full-flowering date, but with 39 bins instead of 10
df.DOY.value_counts().hist(bins=39)
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
9. What's the average number of days it takes for the flowers to blossom? And how many records do we have?Answer these both with one line of code.
df.DOY.describe()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
10. What's the average days into the year cherry flowers normally blossomed before 1900?
(df.AD>=1900).mean()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
11. How about after 1900?
(df.AD<=1900).mean()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
12. How many times was our data from a title in Japanese poetry?You'll need to read the documentation inside of the Excel file.
#Data_type_code #4=poetry df.Data_type_code.value_counts()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
13. Show only the years where our data was from a title in Japanese poetry
df[df.Data_type_code == 4]
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
14. Graph the full-flowering date (DOY) over time
df.DOY.plot(x="DOY", y="AD", figsize=(10,7))
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
15. Smooth out the graphIt's so jagged! You can use `df.rolling` to calculate a rolling average.The following code calculates a **10-year mean**, using the `AD` column as the anchor. If there aren't 20 samples to work with in a row, it'll accept down to 5. Neat, right?(We're only looking at the final 5)
df.rolling(10, on='AD', min_periods=5)['DOY'].mean().tail() df.rolling(10, on='AD', min_periods=5)['DOY'].mean().tail().plot(ylim=(80, 120))
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
Use the code above to create a new column called `rolling_date` in our dataset. It should be the 20-year rolling average of the flowering date. Then plot it, with the year on the x axis and the day of the year on the y axis.Try adding `ylim=(80, 120)` to your `.plot` command to make things look a little less dire. 16....
df.loc[df['Full_flowering_date'] < 400, 'month'] = 'March' df.loc[df['Full_flowering_date'] < 500, 'month'] = 'April' df.loc[df['Full_flowering_date'] < 600, 'month'] = 'May'
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
17. Using your new column, how many blossomings happened in each month?
df.month.value_counts()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
18. Graph how many blossomings happened in each month.
df.month.value_counts().hist()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
19. Adding a day-of-month columnNow we're going to add a new column called "day of month." It's actually a little tougher than it should be since the `Full-flowering date` column is a *float* instead of an integer.
df.Full_flowering_date.astype(int)
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
And if you try to convert it to an int, **pandas yells at you!** That's because, as you can read, you can't have an `NaN` be an integer. But, for some reason, it *can* be a float. Ugh! So what we'll do is **drop all of the na values, then convert them to integers to get rid of the decimals.**I'll show you the first 5 h...
df['Full_flowering_date'].dropna().astype(int).head()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
On the next line, I take the first character of the row and add a bunch of exclamation points on it. I want you to edit this code to **return the last TWO digits of the number**. This only shows you the first 5, by the way.You might want to look up 'list slicing.'
df['Full_flowering_date'].dropna().astype(int).astype(str).apply(lambda value: value[0] + "!!!").head()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
Now that you've successfully extracted the last two letters, save them into a new column called `'day-of-month'`
df['day-of-month'] = df['Full_flowering_date'].dropna().astype(int).astype(str).apply(lambda value: value[0] + "!!!") df.head()
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
20. Adding a date columnNow take the `'month'` and `'day-of-month'` columns and combine them in order to create a new column called `'date'`
df["date"] = df["month"] + df["day-of-month"] df
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
YOU ARE DONE.And **incredible.**
!!!!!!!!!!!
_____no_output_____
MIT
07-homework/cherry-blossoms/Cherry Blossoms.ipynb
giovanafleck/foundations_homework
Tarea N°02 Instrucciones1.- Completa tus datos personales (nombre y rol USM) en siguiente celda.**Nombre**: Fabián Rubilar Álvarez **Rol**: 201510509-K2.- Debes pushear este archivo con tus cambios a tu repositorio personal del curso, incluyendo datos, imágenes, scripts, etc.3.- Se evaluará:- Soluciones- Código- Que B...
import numpy as np import pandas as pd from sklearn import datasets import matplotlib.pyplot as plt %matplotlib inline digits_dict = datasets.load_digits() print(digits_dict["DESCR"]) digits_dict.keys() digits_dict["target"]
_____no_output_____
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
A continuación se crea dataframe declarado como `digits` con los datos de `digits_dict` tal que tenga 65 columnas, las 6 primeras a la representación de la imagen en escala de grises (0-blanco, 255-negro) y la última correspondiente al dígito (`target`) con el nombre _target_.
digits = ( pd.DataFrame( digits_dict["data"], ) .rename(columns=lambda x: f"c{x:02d}") .assign(target=digits_dict["target"]) .astype(int) ) digits.head()
_____no_output_____
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
Ejercicio 1**Análisis exploratorio:** Realiza tu análisis exploratorio, no debes olvidar nada! Recuerda, cada análisis debe responder una pregunta.Algunas sugerencias:* ¿Cómo se distribuyen los datos?* ¿Cuánta memoria estoy utilizando?* ¿Qué tipo de datos son?* ¿Cuántos registros por clase hay?* ¿Hay registros que no ...
#Primero veamos los tipos de datos del DF y cierta información que puede ser de utilidad digits.info() #Veamos si hay valores nulos en las columnas if True not in digits.isnull().any().values: print('No existen valores nulos') #Veamos que elementos únicos tenemos en la columna target del DF digits.target.unique(...
El total de los datos es: 1797 El máximo de los datos es: 183 El mínimo de los datos es: 174 El promedio de los datos es: 179.70000000000002
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
Por lo tanto, tenemos un promedio de 180 (aproximando por arriba) donde el menor valor es de 174 y el mayor valor es de 183.
#Para mejorar la visualización, construyamos un histograma digits.target.plot.hist(bins=12, alpha=0.5)
_____no_output_____
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
Sabemos que cada dato corresponde a una matriz cuadrada de dimensión 8 con entradas de 0 a 16. Cada dato proviene de otra matriz cuadrada de dimensión 32, el cual ha sido procesado por un método de reducción de dimensiones. Además, cada dato es una imagen de un número entre 0 a 9, por lo tanto se utilizan 8$\times$8 = ...
digits_dict["images"][0]
_____no_output_____
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
Visualiza imágenes de los dígitos utilizando la llave `images` de `digits_dict`. Sugerencia: Utiliza `plt.subplots` y el método `imshow`. Puedes hacer una grilla de varias imágenes al mismo tiempo!
nx, ny = 5, 5 fig, axs = plt.subplots(nx, ny, figsize=(12, 12)) for x in range(0,5): for y in range(0,5): axs[x,y].imshow(digits_dict['images'][5*x+y], cmap = 'plasma') axs[x,y].text(3,4,s = digits['target'][5*x+y], fontsize = 30)
_____no_output_____
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
Ejercicio 3**Machine Learning**: En esta parte usted debe entrenar los distintos modelos escogidos desde la librería de `skelearn`. Para cada modelo, debe realizar los siguientes pasos:* **train-test** * Crear conjunto de entrenamiento y testeo (usted determine las proporciones adecuadas). * Imprimir por pantalla el ...
X = digits.drop(columns="target").values y = digits["target"].values from sklearn import datasets from sklearn.model_selection import train_test_split #Ahora vemos los conjuntos de testeo y entrenamiento X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=42) print('El conjunto de test...
{'criterion': ['gini', 'entropy'], 'max_depth': array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20, 30, 40, 50, 70, 90, 120, 150])} 0.8761308281141267 {'criterion': 'entropy', 'max_depth': 11}
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
Ejercicio 4__Comprensión del modelo:__ Tomando en cuenta el mejor modelo entontrado en el `Ejercicio 3`, debe comprender e interpretar minuciosamente los resultados y gráficos asocados al modelo en estudio, para ello debe resolver los siguientes puntos: * **Cross validation**: usando **cv** (con n_fold = 10), sacar un...
#Cross Validation from sklearn.model_selection import cross_val_score model = KNeighborsClassifier() precision = cross_val_score(estimator = model, X = X_train, y = y_train, cv = 10) med = precision.mean()#Media desv = precision.std()#Desviación estandar a = med - desv b = med + desv print('(',a,',', b,')') #Curva...
_____no_output_____
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
Ejercicio 5__Reducción de la dimensión:__ Tomando en cuenta el mejor modelo encontrado en el `Ejercicio 3`, debe realizar una reducción de dimensionalidad del conjunto de datos. Para ello debe abordar el problema ocupando los dos criterios visto en clases: * **Selección de atributos*** **Extracción de atributos**__Pr...
#Selección de atributos from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif df = pd.DataFrame(X) df.columns = [f'P{k}' for k in range(1,X.shape[1]+1)] df['y']=y print('Vemos que el df respectivo es de la forma:') print('\n') print(df.head()) # Separamos las columnas obj...
_____no_output_____
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
Ejercicio 6__Visualizando Resultados:__ A continuación se provee código para comparar las etiquetas predichas vs las etiquetas reales del conjunto de _test_.
def mostar_resultados(digits,model,nx=5, ny=5,label = "correctos"): """ Muestra los resultados de las prediciones de un modelo de clasificacion en particular. Se toman aleatoriamente los valores de los resultados. - label == 'correcto': retorna los valores en que el modelo acierta. - label...
_____no_output_____
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
**Pregunta*** Tomando en cuenta el mejor modelo entontrado en el `Ejercicio 3`, grafique los resultados cuando: * el valor predicho y original son iguales * el valor predicho y original son distintos * Cuando el valor predicho y original son distintos , ¿Por qué ocurren estas fallas?
mostar_resultados(digits, KNeighborsClassifier(), nx=5, ny=5,label = "correctos") mostar_resultados(digits, neighbors.KNeighborsClassifier(), nx=5, ny=5,label = "incorrectos")
_____no_output_____
MIT
homeworks/tarea_02/tarea_02.ipynb
FabianSaulRubilarAlvarez/mat281_portfolio_template
Ocean heat transport in CMIP5 models Read data
import matplotlib.pyplot as plt import iris import iris.plot as iplt import iris.coord_categorisation import cf_units import numpy %matplotlib inline infile = '/g/data/ua6/DRSv2/CMIP5/NorESM1-M/rcp85/mon/ocean/r1i1p1/hfbasin/latest/hfbasin_Omon_NorESM1-M_rcp85_r1i1p1_200601-210012.nc' cube = iris.load_cube(infile) pri...
_____no_output_____
MIT
development/hfbasin.ipynb
DamienIrving/ocean-analysis
So for any given year, the annual mean shows ocean heat transport away from the tropics. Trends
def convert_to_seconds(time_axis): """Convert time axis units to seconds. Args: time_axis(iris.DimCoord) """ old_units = str(time_axis.units) old_timestep = old_units.split(' ')[0] new_units = old_units.replace(old_timestep, 'seconds') new_unit = cf_units.Unit(new_units, c...
_____no_output_____
MIT
development/hfbasin.ipynb
DamienIrving/ocean-analysis
So the trends in ocean heat transport suggest reduced transport in the RCP 8.5 simulation (i.e. the trend plot is almost the inverse of the climatology plot). Convergence
print(global_cube_annual) diffs_data = numpy.diff(global_cube_annual.data, axis=1) lats = global_cube_annual.coord('latitude').points diffs_lats = (lats[1:] + lats[:-1]) / 2. print(diffs_data.shape) print(len(diffs_lats)) plt.plot(diffs_lats, diffs_data[0, :]) plt.plot(lats, global_cube_annual[0, ::].data / 10.0) plt.s...
_____no_output_____
MIT
development/hfbasin.ipynb
DamienIrving/ocean-analysis
Convergence trend
time_axis = global_cube_annual.coord('time') time_axis = convert_to_seconds(time_axis) diffs_trend = numpy.ma.apply_along_axis(linear_trend, 0, diffs_data, time_axis.points) diffs_trend = numpy.ma.masked_values(diffs_trend, global_cube_annual.data.fill_value) print(diffs_trend.shape) plt.plot(diffs_lats, diffs_trend *...
_____no_output_____
MIT
development/hfbasin.ipynb
DamienIrving/ocean-analysis
Baseline
def customVectorizer(df, toRemove): # leEmbarked.fit(df_raw['Embarked']) leSex = preprocessing.LabelEncoder() leEmbarked = preprocessing.LabelEncoder() df.fillna(inplace=True, value=0) leSex.fit(df['Sex']) # leEmbarked.fit(df['Embarked']) # df['Embarked'] = leEmbarked.transform(df['Embarked']) ...
_____no_output_____
MIT
titanic/Titanic Clean.ipynb
bhi5hmaraj/Applied-ML
Train a classifer for Age and use it to fill gapsSo first we split the train.csv into 2 parts (one with non null age and the other with null) . We train a regressor on the non null data points to predict age and use this trained regressor to fill the missing ages. Now we combine the 2 split data sets into a single dat...
X = pd.read_csv('train.csv') age_present = X['Age'] > 0 age_present.describe() False in age_present X_age_p = X[age_present] X_age_p.shape age = X_age_p['Age'] # X_age_p X_age_p = customVectorizer(X_age_p, ['Embarked', 'Age', 'PassengerId', 'Name', 'Ticket', 'Cabin']) from sklearn.linear_model import LinearRegression...
[0.76666667 0.76666667 0.85393258 0.7752809 0.80898876 0.78651685 0.79775281 0.80898876 0.86516854 0.79545455]
MIT
titanic/Titanic Clean.ipynb
bhi5hmaraj/Applied-ML
Try ensemble with LR, SVC, RF
# taken from https://machinelearningmastery.com/ensemble-machine-learning-algorithms-python-scikit-learn/ from sklearn import model_selection from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn.ensemble import VotingClassifier kfold = model_selection.KFold(n_splits=10, random_state...
/home/bhishma/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:433: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning. FutureWarning) /home/bhishma/anaconda3/lib/python3.7/site-packages/sklearn/svm/base.py:196: FutureWarning: The default v...
MIT
titanic/Titanic Clean.ipynb
bhi5hmaraj/Applied-ML
Notebook BasicsIn this lesson we'll learn how to work with **notebooks**. Notebooks allow us to do interactive and visual computing which makes it a great learning tool. We'll use notebooks to code in Python and learn the basics of machine learning. View on practicalAI Run in Google Colab View code on GitHub...
print ("Hello world!")
Hello world!
MIT
notebooks/00_Notebooks.ipynb
raidery/practicalAI
&nbsp; Tutorial 2: Learning Hyperparameters**Week 1, Day 2: Linear Deep Learning****By Neuromatch Academy**__Content creators:__ Saeed Salehi, Andrew Saxe__Content reviewers:__ Polina Turishcheva, Antoine De Comite, Kelson Shilling-Scrivo__Content editors:__ Anoop Kulkarni__Production editors:__ Khalid Almubarak, Sp...
# @title Tutorial slides # @markdown These are the slides for the videos in the tutorial # @markdown If you want to locally dowload the slides, click [here](https://osf.io/sne2m/download) from IPython.display import IFrame IFrame(src=f"https://mfr.ca-1.osf.io/render?url=https://osf.io/sne2m/?direct%26mode=render%26act...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
--- SetupThis a GPU-Free tutorial!
# @title Install dependencies !pip install git+https://github.com/NeuromatchAcademy/evaltools --quiet from evaltools.airtable import AirtableForm # Imports import time import numpy as np import matplotlib import matplotlib.pyplot as plt # @title Figure settings from ipywidgets import interact, IntSlider, FloatSlider,...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
--- Section 1: A Shallow Narrow Linear Neural Network*Time estimate: ~30 mins*
# @title Video 1: Shallow Narrow Linear Net from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = "https://player.bilibili.com/player.html?bvid={...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
Section 1.1: A Shallow Narrow Linear Net To better understand the behavior of neural network training with gradient descent, we start with the incredibly simple case of a shallow narrow linear neural net, since state-of-the-art models are impossible to dissect and comprehend with our current mathematical tools.The mod...
class ShallowNarrowExercise: """Shallow and narrow (one neuron per layer) linear neural network """ def __init__(self, init_weights): """ Args: init_weights (list): initial weights """ assert isinstance(init_weights, (list, np.ndarray, tuple)) assert len(init_weights) == 2 self.w1 = ...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D2_LinearDeepLearning/solutions/W1D2_Tutorial2_Solution_46492cd6.py)*Example output:* Section 1.2: Learning landscapes
# @title Video 2: Training Landscape from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = "https://player.bilibili.com/player.html?bvid={0}&page...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
As you may have already asked yourself, we can analytically find $w_1$ and $w_2$ without using gradient descent:\begin{equation}w_1 \cdot w_2 = \dfrac{y}{x}\end{equation}In fact, we can plot the gradients, the loss function and all the possible solutions in one figure. In this example, we use the $y = 1x$ mapping:**Blu...
plot_vector_field('all')
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
Here, we also visualize the loss landscape in a 3-D plot, with two training trajectories for different initial conditions.Note: the trajectories from the 3D plot and the previous plot are independent and different.
plot_loss_landscape() # @title Student Response from ipywidgets import widgets text=widgets.Textarea( value='Type your answer here and click on `Submit!`', placeholder='Type something', description='', disabled=False ) button = widgets.Button(description="Submit!") display(text,button) def on_button_cl...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
--- Section 2: Depth, Learning rate, and initialization*Time estimate: ~45 mins* Successful deep learning models are often developed by a team of very clever people, spending many many hours "tuning" learning hyperparameters, and finding effective initializations. In this section, we look at three basic (but often not ...
# @title Video 4: Effect of Depth from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = "https://player.bilibili.com/player.html?bvid={0}&page={1...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
Why might depth be useful? What makes a network or learning system "deep"? The reality is that shallow neural nets are often incapable of learning complex functions due to data limitations. On the other hand, depth seems like magic. Depth can change the functions a network can represent, the way a network learns, and h...
# @markdown Make sure you execute this cell to enable the widget! _ = interact(depth_widget, depth = IntSlider(min=0, max=51, step=5, value=0, continuous_update=False)) # @title Video 5: Effect of Depth - Discussion from ipywidgets import widgets out2 = widgets.Output()...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
Section 2.2: Choosing a learning rate The learning rate is a common hyperparameter for most optimization algorithms. How should we set it? Sometimes the only option is to try all the possibilities, but sometimes knowing some key trade-offs will help guide our search for good hyperparameters.
# @title Video 6: Learning Rate from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = "https://player.bilibili.com/player.html?bvid={0}&page={1}"...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
Interactive Demo 2.2: Learning rate widgetHere, we fix the network depth to 50 layers. Use the widget to explore the impact of learning rate $\eta$ on the training curve (loss evolution) of a deep but narrow neural network.**Think!**Can we say that larger learning rates always lead to faster learning? Why not?
# @markdown Make sure you execute this cell to enable the widget! _ = interact(lr_widget, lr = FloatSlider(min=0.005, max=0.045, step=0.005, value=0.005, continuous_update=False, readout_format='.3f', description='eta')) # @title Video 7: Learning Rate - Discussion from ip...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
Section 2.3: Depth vs Learning Rate
# @title Video 8: Depth and Learning Rate from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = "https://player.bilibili.com/player.html?bvid={0}...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
Interactive Demo 2.3: Depth and Learning-Rate **Important instruction**The exercise starts with 10 hidden layers. Your task is to find the learning rate that delivers fast but robust convergence (learning). When you are confident about the learning rate, you can **Register** the optimal learning rate for the given dep...
# @markdown Make sure you execute this cell to enable the widget! intpl_obj = InterPlay() intpl_obj.slider = FloatSlider(min=0.005, max=0.105, step=0.005, value=0.005, layout=Layout(width='500px'), continuous_update=False, rea...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
Section 2.4: Why initialization is important
# @title Video 10: Initialization Matters from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = "https://player.bilibili.com/player.html?bvid={0}...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
We’ve seen, even in the simplest of cases, that depth can slow learning. Why? From the chain rule, gradients are multiplied by the current weight at each layer, so the product can vanish or explode. Therefore, weight initialization is a fundamentally important hyperparameter.Although in practice initial values for lear...
# @markdown Make sure you execute this cell to see the figure! plot_init_effect() # @title Video 11: Initialization Matters Explained from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=3...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
--- SummaryIn the second tutorial, we have learned what is the training landscape, and also we have see in depth the effect of the depth of the network and the learning rate, and their interplay. Finally, we have seen that initialization matters and why we need smart ways of initialization.
# @title Video 12: Tutorial 2 Wrap-up from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = "https://player.bilibili.com/player.html?bvid={0}&pag...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
--- Bonus Hyperparameter interactionFinally, let's put everything we learned together and find best initial weights and learning rate for a given depth. By now you should have learned the interactions and know how to find the optimal values quickly. If you get `numerical overflow` warnings, don't be discouraged! They ...
# @markdown Make sure you execute this cell to enable the widget! _ = interact(depth_lr_init_interplay, depth = IntSlider(min=10, max=51, step=5, value=25, continuous_update=False), lr = FloatSlider(min=0.001, max=0.1, step=0.005, v...
_____no_output_____
CC-BY-4.0
tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial2.ipynb
eduardojdiniz/course-content-dl
Web scraping with PythonThis notebook demonstrates how you can use the Python programming language to scrape information from a web page. The goal today: Scrape the main table on [the first page of Maryland's list of WARN letters](https://www.dllr.state.md.us/employment/warn.shtml) and, if time, write the data to a CS...
import requests import bs4
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Request the pageNext, we'll use the `get()` method of the `requests` library (which we just imported) to grab the web page.While we're at it, we'll _assign_ all the stuff that comes back to a new variable using `=`.The variable name is arbitrary, but it's usually good to pick something that describes the value it's po...
URL = 'http://www.dllr.state.md.us/employment/warn.shtml' warn_page = requests.get(URL)
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Nothing appears to have happened, which is (usually) a good sign.If you want to make sure that your request was successful, you can check the `status_code` attribute of the Python object that was returned:
warn_page.status_code
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
A `200` code means all is well. `404` means the page wasn't found, etc. ([Here's one of our favorite lists of HTTP status codes](https://http.cat/) ([or here, if you prefer dogs](https://httpstatusdogs.com/)).)The object being stored as the `warn_page` variable came back with a lot of potentially useful information we ...
warn_page.text
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
✍️ Try it yourselfUse the code blocks below to experiment with requesting web pages and checking out the HTML that gets returned.Some ideas to get you started:- `'http://ire.org'`- `'https://web.archive.org/web/20031202214318/http://www.tdcj.state.tx.us:80/stat/finalmeals.htm'`- `'https://www.nrc.gov/reactors/operatin...
soup = bs4.BeautifulSoup(warn_page.text, 'html.parser')
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Nothing happened, which is good! You can take a look at what `soup` is, but it looks pretty much like `warn_page.text`:
soup
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
If you want to be sure, you can use the Python function `type()` to check what sort of object you're dealing with:
# the `str` type means a string, or text type(warn_page.text) # the `bs4.BeautifulSoup` type means we successfully created the object type(soup)
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
✍️ Try it yourselfUse the code blocks below to experiment fetching HTML and turning it into soup (if you fetched some pages earlier and saved them as variables, that'd be a good start). Targeting and extracting dataNow that we have BeautifulSoup object loaded up, we can go hunting for the specific HTML elements that ...
table = soup.find('table') table
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Find the rows in the tableNext, use the `find_all()` method to drill down and get a list of rows in the table:
rows = table.find_all('tr') rows
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
To see how many items are in this list -- in other words, how many rows are in the table -- you can use the `len()` function:
len(rows)
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Loop through the rows and extract the dataNext, we can use a [`for` loop](Python%20syntax%20cheat%20sheet.ipynbfor-loops) to go through the list of rows and start grabbing data from each one.Quick refresher on _for loop_ syntax: Start with the word `for` (lowercase), then a variable name to stand in for each item in t...
for row in rows: print(row) print('='*80)
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Notice that the first item that prints is the header row with the column labels. You are free to keep these headers if you want, but I typically skip that row and define my own list of column names.(Another thing to consider: On better-constructed web pages, the cells in the header row will be represented by `th` ("tab...
for row in rows[1:]: print(row) print('='*80)
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Now we're cooking with gas. Let's start pulling out the data in each row. Start by using `find_all()` to grab a list of `td` tags:
for row in rows[1:]: cells = row.find_all('td') print(cells) print('='*80)
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Now we have, for each row, a _list_ of `td` tags. Next step is to look at the table and start grabbing specific values based on their position in the list and assigning them to human-readable variable names.Quick refresher on list syntax: To access a specific item in a list, use square brackets `[]` and the index numbe...
for row in rows[1:]: cells = row.find_all('td') warn_date = cells[0] print(warn_date) print('='*80)
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
This is returning the entire `Tag` object -- we just want the contents inside it. You can access the `.text` attribute of the tag to get the text inside:
for row in rows[1:]: cells = row.find_all('td') warn_date = cells[0].text print(warn_date)
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
In the next cell (`[1]`), the `.text` attribute will give you the NAICS code. In the third cell (`[2]`) you'll get the name of the business. Etc.It's also generally good practice to trim off external whitespace for each value, and you can use the Python built-in string method `strip()` to accomplish this as you march a...
for row in rows[1:]: cells = row.find_all('td') warn_date = cells[0].text.strip() naics_code = cells[1].text.strip() biz = cells[2].text.strip() print(warn_date, naics_code, biz)
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
✍️ Try it yourselfNow that you've gotten this far, see if you can isolate the other pieces of data in each row.
for row in rows[1:]: cells = row.find_all('td') warn_date = cells[0].text.strip() naics_code = cells[1].text.strip() biz = cells[2].text.strip() # address # wia_code # total_employees # effective_date # type_code # print()
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Write the results to fileNow that we've targeted our lists of data for each row, we can use Python's built-in [`csv`](https://docs.python.org/3/library/csv.html) module to write each list to a CSV file.First, import the csv module.
import csv
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Now define a list of headers to match the data (each column header will be a string) -- run this cell:
HEADERS = [ 'warn_date', 'naics_code', 'biz', 'address', 'wia_code', 'total_employees', 'effective_date', 'type_code' ]
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Now, using something called a `with` block, open a new CSV file to write to and write some code to do the following things:- Create a `csv.writer` object- Write out the list of headers using the `writerow()` method of the `csv.writer` object- Drop in the `for` loop you just wrote and, instead of just printing the conte...
# create a file called 'warn-data.csv' in write ('w') mode # specify that newlines are terminated by an empty string (this deals with a PC-specific problem) # and use the `as` keyword to name the open file handler (the variable name `outfile` is arbitrary) with open('warn-data.csv', 'w', newline='') as outfile: # g...
_____no_output_____
MIT
Web scraping with Python.ipynb
allanjamesvestal/teaching-guide-python-scraping
Lambda School Data Science, Unit 2: Predictive Modeling Kaggle Challenge, Module 3 Assignment- [ ] [Review requirements for your portfolio project](https://lambdaschool.github.io/ds/unit2/portfolio-project/ds6), then choose your dataset, and [submit this form](https://forms.gle/nyWURUg65x1UTRNV9), due today at 4pm Paci...
# If you're in Colab... import os, sys in_colab = 'google.colab' in sys.modules if in_colab: # Install required python packages: # category_encoders, version >= 2.0 # eli5, version >= 0.9 # pandas-profiling, version >= 2.0 # plotly, version >= 4.0 !pip install --upgrade category_encoders eli5 p...
_____no_output_____
MIT
module3/assignment_kaggle_challenge_3.ipynb
mikedcurry/DS-Unit-2-Kaggle-Challenge
Dealing with Outliers Sometimes outliers can mess up an analysis; you usually don't want a handful of data points to skew the overall results. Let's revisit our example of income data, with some random billionaire thrown in:
%matplotlib inline import numpy as np incomes = np.random.normal(27000, 15000, 10000) incomes = np.append(incomes, [1000000000]) import matplotlib.pyplot as plt plt.hist(incomes, 50) plt.show()
_____no_output_____
MIT
Outliers.ipynb
wf539/MLDataSciDeepLearningPython
That's not very helpful to look at. One billionaire ended up squeezing everybody else into a single line in my histogram. Plus it skewed my mean income significantly:
incomes.mean()
_____no_output_____
MIT
Outliers.ipynb
wf539/MLDataSciDeepLearningPython
It's important to dig into what is causing your outliers, and understand where they are coming from. You also need to think about whether removing them is a valid thing to do, given the spirit of what it is you're trying to analyze. If I know I want to understand more about the incomes of "typical Americans", filtering...
def reject_outliers(data): u = np.median(data) s = np.std(data) filtered = [e for e in data if (u - 2 * s < e < u + 2 * s)] return filtered filtered = reject_outliers(incomes) plt.hist(filtered, 50) plt.show()
_____no_output_____
MIT
Outliers.ipynb
wf539/MLDataSciDeepLearningPython
That looks better. And, our mean is more, well, meangingful now as well:
np.mean(filtered)
_____no_output_____
MIT
Outliers.ipynb
wf539/MLDataSciDeepLearningPython
Building your Recurrent Neural Network - Step by StepWelcome to Course 5's first assignment! In this assignment, you will implement your first Recurrent Neural Network in numpy.Recurrent Neural Networks (RNN) are very effective for Natural Language Processing and other sequence tasks because they have "memory". They c...
import numpy as np from rnn_utils import *
_____no_output_____
MIT
Course-5-Sequence-Models/week1/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb
xnone/coursera-deep-learning
1 - Forward propagation for the basic Recurrent Neural NetworkLater this week, you will generate music using an RNN. The basic RNN that you will implement has the structure below. In this example, $T_x = T_y$. **Figure 1**: Basic RNN model Here's how you can implement an RNN: **Steps**:1. Implement the calculations...
# GRADED FUNCTION: rnn_cell_forward def rnn_cell_forward(xt, a_prev, parameters): """ Implements a single forward step of the RNN-cell as described in Figure (2) Arguments: xt -- your input data at timestep "t", numpy array of shape (n_x, m). a_prev -- Hidden state at timestep "t-1", numpy array o...
a_next[4] = [ 0.59584544 0.18141802 0.61311866 0.99808218 0.85016201 0.99980978 -0.18887155 0.99815551 0.6531151 0.82872037] a_next.shape = (5, 10) yt_pred[1] = [ 0.9888161 0.01682021 0.21140899 0.36817467 0.98988387 0.88945212 0.36920224 0.9966312 0.9982559 0.17746526] yt_pred.shape = (2, 10)...
MIT
Course-5-Sequence-Models/week1/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb
xnone/coursera-deep-learning
**Expected Output**: **a_next[4]**: [ 0.59584544 0.18141802 0.61311866 0.99808218 0.85016201 0.99980978 -0.18887155 0.99815551 0.6531151 0.82872037] **a_next.shape**: (5, 10) ...
# GRADED FUNCTION: rnn_forward def rnn_forward(x, a0, parameters): """ Implement the forward propagation of the recurrent neural network described in Figure (3). Arguments: x -- Input data for every time-step, of shape (n_x, m, T_x). a0 -- Initial hidden state, of shape (n_a, m) parameters -- ...
a[4][1] = [-0.99999375 0.77911235 -0.99861469 -0.99833267] a.shape = (5, 10, 4) y_pred[1][3] = [ 0.79560373 0.86224861 0.11118257 0.81515947] y_pred.shape = (2, 10, 4) caches[1][1][3] = [-1.1425182 -0.34934272 -0.20889423 0.58662319] len(caches) = 2
MIT
Course-5-Sequence-Models/week1/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb
xnone/coursera-deep-learning
**Expected Output**: **a[4][1]**: [-0.99999375 0.77911235 -0.99861469 -0.99833267] **a.shape**: (5, 10, 4) **y[1][3]**: [ 0.79560373 0.8622...
# GRADED FUNCTION: lstm_cell_forward def lstm_cell_forward(xt, a_prev, c_prev, parameters): """ Implement a single forward step of the LSTM-cell as described in Figure (4) Arguments: xt -- your input data at timestep "t", numpy array of shape (n_x, m). a_prev -- Hidden state at timestep "t-1", num...
a_next[4] = [-0.66408471 0.0036921 0.02088357 0.22834167 -0.85575339 0.00138482 0.76566531 0.34631421 -0.00215674 0.43827275] a_next.shape = (5, 10) c_next[2] = [ 0.63267805 1.00570849 0.35504474 0.20690913 -1.64566718 0.11832942 0.76449811 -0.0981561 -0.74348425 -0.26810932] c_next.shape = (5, 10) ...
MIT
Course-5-Sequence-Models/week1/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb
xnone/coursera-deep-learning
**Expected Output**: **a_next[4]**: [-0.66408471 0.0036921 0.02088357 0.22834167 -0.85575339 0.00138482 0.76566531 0.34631421 -0.00215674 0.43827275] **a_next.shape**: (5, 10) ...
# GRADED FUNCTION: lstm_forward def lstm_forward(x, a0, parameters): """ Implement the forward propagation of the recurrent neural network using an LSTM-cell described in Figure (3). Arguments: x -- Input data for every time-step, of shape (n_x, m, T_x). a0 -- Initial hidden state, of shape (n_a, ...
a[4][3][6] = 0.172117767533 a.shape = (5, 10, 7) y[1][4][3] = 0.95087346185 y.shape = (2, 10, 7) caches[1][1[1]] = [ 0.82797464 0.23009474 0.76201118 -0.22232814 -0.20075807 0.18656139 0.41005165] c[1][2][1] -0.855544916718 len(caches) = 2
MIT
Course-5-Sequence-Models/week1/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb
xnone/coursera-deep-learning
**Expected Output**: **a[4][3][6]** = 0.172117767533 **a.shape** = (5, 10, 7) **y[1][4][3]** = 0.95087346185 ...
def rnn_cell_backward(da_next, cache): """ Implements the backward pass for the RNN-cell (single time-step). Arguments: da_next -- Gradient of loss with respect to next hidden state cache -- python dictionary containing useful values (output of rnn_cell_forward()) Returns: gradients -- pyt...
gradients["dxt"][1][2] = -0.460564103059 gradients["dxt"].shape = (3, 10) gradients["da_prev"][2][3] = 0.0842968653807 gradients["da_prev"].shape = (5, 10) gradients["dWax"][3][1] = 0.393081873922 gradients["dWax"].shape = (5, 3) gradients["dWaa"][1][2] = -0.28483955787 gradients["dWaa"].shape = (5, 5) gradients["dba"]...
MIT
Course-5-Sequence-Models/week1/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb
xnone/coursera-deep-learning
**Expected Output**: **gradients["dxt"][1][2]** = -0.460564103059 **gradients["dxt"].shape** = (3, 10) **gradients["da_prev"][2][3]** = 0.084...
def rnn_backward(da, caches): """ Implement the backward pass for a RNN over an entire sequence of input data. Arguments: da -- Upstream gradients of all hidden states, of shape (n_a, m, T_x) caches -- tuple containing information from the forward pass (rnn_forward) Returns: gradients ...
gradients["dx"][1][2] = [-2.07101689 -0.59255627 0.02466855 0.01483317] gradients["dx"].shape = (3, 10, 4) gradients["da0"][2][3] = -0.314942375127 gradients["da0"].shape = (5, 10) gradients["dWax"][3][1] = 11.2641044965 gradients["dWax"].shape = (5, 3) gradients["dWaa"][1][2] = 2.30333312658 gradients["dWaa"].shape ...
MIT
Course-5-Sequence-Models/week1/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb
xnone/coursera-deep-learning
**Expected Output**: **gradients["dx"][1][2]** = [-2.07101689 -0.59255627 0.02466855 0.01483317] **gradients["dx"].shape** = (3, 10, 4) **gradients["da0"][2][3]** = ...
def lstm_cell_backward(da_next, dc_next, cache): """ Implement the backward pass for the LSTM-cell (single time-step). Arguments: da_next -- Gradients of next hidden state, of shape (n_a, m) dc_next -- Gradients of next cell state, of shape (n_a, m) cache -- cache storing information from the f...
gradients["dxt"][1][2] = 3.23055911511 gradients["dxt"].shape = (3, 10) gradients["da_prev"][2][3] = -0.0639621419711 gradients["da_prev"].shape = (5, 10) gradients["dc_prev"][2][3] = 0.797522038797 gradients["dc_prev"].shape = (5, 10) gradients["dWf"][3][1] = -0.147954838164 gradients["dWf"].shape = (5, 8) gradients["...
MIT
Course-5-Sequence-Models/week1/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb
xnone/coursera-deep-learning