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 |
|---|---|---|---|---|---|
Visualize the new (upsampled) raw data: | fig,axes=plt.subplots(nrows=2,figsize=(8,6),sharex=True)
iiplot=np.arange(0,60*upsampfactor) # bins of stimulus to plot
ttplot=iiplot*dtStimhi # time bins of stimulus
axes[0].plot(ttplot,Stimhi[iiplot])
axes[0].set_title('raw stimulus (fine time bins)')
axes[0].set_ylabel('stim intensity')
# Should notice stimulus now ... | <ipython-input-36-97db7153fd27>:9: UserWarning: In Matplotlib 3.3 individual lines on a stem plot will be added as a LineCollection instead of individual lines. This significantly improves the performance of a stem plot. To remove this warning and switch to the new behaviour, set the "use_line_collection" keyword argum... | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Divide data into "training" and "test" sets for cross-validation | trainfrac = .8 # fraction of data to use for training
ntrain = int(np.ceil(nThi*trainfrac)) # number of training samples
ntest = int(nThi-ntrain) # number of test samples
iitest = np.arange(ntest).astype(int) # time indices for test
iitrain = np.arange(ntest,nThi).astype(int) # time indices for training
stimtrain =... | Dividing data into training and test sets:
Training: 28800 samples (2109 spikes)
Test: 7200 samples (557 spikes)
| MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Set the number of time bins of stimulus to use for predicting spikes | ntfilt = 20*upsampfactor # Try varying this, to see how performance changes! | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
build the design matrix, training data | Xtrain = np.c_[
np.ones((ntrain,1)),
hankel(np.r_[np.zeros(ntfilt-1),stimtrain[:-ntfilt+1]].reshape(-1,1),stimtrain[-ntfilt:])] | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Build design matrix for test data | Xtest = np.c_[
np.ones((ntest,1)),
hankel(np.r_[np.zeros(ntfilt-1),stimtest[:-ntfilt+1]].reshape(-1,1),stimtest[-ntfilt:])] | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Fit poisson GLM using ML Compute maximum likelihood estimate (using `scipy.optimize.fmin` instead of `sm.GLM`) | sta = (Xtrain.T@spstrain)/np.sum(spstrain) # compute STA for initialization | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Make loss function and minimize | jac_neglogli_poissGLM?
lossfun=lambda prs:neglogli_poissGLM(prs,Xtrain,spstrain,dtStimhi)
jacfun=lambda prs:jac_neglogli_poissGLM(prs,Xtrain,spstrain,dtStimhi)
hessfun=lambda prs:hess_neglogli_poissGLM(prs,Xtrain,spstrain,dtStimhi)
filtML=minimize(lossfun,x0=sta,method='trust-ncg',jac=jacfun, hess=hessfun).x
ttk=np.ar... | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Ridge regression prior Now let's regularize by adding a penalty on the sum of squared filtercoefficients w(i) of the form: penalty(lambda) = lambda*(sum_i w(i).^2),where lambda is known as the "ridge" parameter. As noted in tutorial3,this is equivalent to placing an iid zero-mean Gaussian prior on the RFcoef... | lamvals = 2.**np.arange(0,11,1) # it's common to use a log-spaced set of values
nlam = len(lamvals) | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Precompute some quantities (X'X and X'*y) for training and test data | Imat = np.eye(ntfilt+1) # identity matrix of size of filter + const
Imat[0,0] = 0 # remove penalty on constant dc offset | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Allocate space for train and test errors | negLtrain = np.zeros(nlam) # training error
negLtest = np.zeros(nlam) # test error
w_ridge = np.zeros((ntfilt+1,nlam)) # filters for each lambda | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Define train and test log-likelihood funcs | negLtrainfun = lambda prs:neglogli_poissGLM(prs,Xtrain,spstrain,dtStimhi)
jac_negLtrainfun = lambda prs:jac_neglogli_poissGLM(prs,Xtrain,spstrain,dtStimhi)
hess_negLtrainfun = lambda prs:hess_neglogli_poissGLM(prs,Xtrain,spstrain,dtStimhi)
negLtestfun = lambda prs:neglogli_poissGLM(prs,Xtest,spstest,dtStimhi)
jac_negLt... | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Now compute MAP estimate for each ridge parameter | wmap = filtML # initialize parameter estimate
fig,axes=plt.subplots()
axes.plot(ttk,ttk*0,'k') # initialize plot
for jj in range(nlam):
# Compute ridge-penalized MAP estimate
Cinv = lamvals[jj]*Imat # set inverse prior covariance
lossfun = lambda prs:neglogposterior(prs,negLtrainfun,Cinv)
jacfun=la... | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Plot filter estimates and errors for ridge estimates | fig,axes=plt.subplots(nrows=2,ncols=2,figsize=(8,8))
axes[0,1].plot(ttk,w_ridge[1:,:])
axes[0,1].set_title('all ridge estimates')
axes[0,0].semilogx(lamvals,-negLtrain,'o-')
axes[0,0].set_title('training logli')
axes[1,0].semilogx(lamvals,-negLtest,'o-')
axes[1,0].set_title('test logli')
axes[1,0].set_xlabel('lambda')
... | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
L2 smoothing prior Use penalty on the squared differences between filter coefficients,penalizing large jumps between successive filter elements. This isequivalent to placing an iid zero-mean Gaussian prior on the incrementsbetween filter coeffs. (See tutorial 3 for visualization of the priorcovariance).This matrix co... | Dx1 = (np.diag(-np.ones(ntfilt),0)+np.diag(np.ones(ntfilt-1),1))[:-1,:]
Dx = Dx1.T@Dx1 # computes squared diffs | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Select smoothing penalty by cross-validation | lamvals = 2**np.arange(1,15) # grid of lambda values (ridge parameters)
nlam = len(lamvals) | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Embed `Dx` matrix in matrix with one extra row/column for constant coeff | D = block_diag(0,Dx) | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Allocate space for train and test errors | negLtrain_sm = np.zeros(nlam) # training error
negLtest_sm = np.zeros(nlam) # test error
w_smooth = np.zeros((ntfilt+1,nlam)) # filters for each lambda | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Now compute MAP estimate for each ridge parameter | fig,axes=plt.subplots()
axes.plot(ttk,ttk*0,'k') # initialize plot
wmap=filtML # initialize with ML fit
for jj in range(nlam):
# Compute MAP estimate
Cinv=lamvals[jj]*D # set inverse prior covariance
lossfun = lambda prs:neglogposterior(prs,negLtrainfun,Cinv)
jacfun=lambda prs:jac_neglogposterior(p... | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Plot filter estimates and errors for smoothing estimates | fig,axes=plt.subplots(nrows=2,ncols=2,figsize=(8,8))
axes[0,1].plot(ttk,w_smooth[1:,:])
axes[0,1].set_title('all smoothing estimates')
axes[0,0].semilogx(lamvals,-negLtrain_sm,'o-')
axes[0,0].set_title('training LL')
axes[1,0].semilogx(lamvals,-negLtest_sm,'o-')
axes[1,0].set_title('test LL')
axes[1,0].set_xlabel('lamb... | _____no_output_____ | MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Last, lets see which one actually achieved lower test error | print('\nBest ridge test error: %.5f'%(-min(negLtest)))
print('Best smoothing test error: %.5f'%(-min(negLtest_sm))) |
Best ridge test error: 2093.80432
Best smoothing test error: 2095.67887
| MIT | mypython/t4_regularization_PoissonGLM.ipynb | disadone/GLMspiketraintutorial |
Bank Note AuthenticationData were extracted from images that were taken from genuine and forged banknote-like specimens. For digitization, an industrial camera usually used for inspection was used. The final images have 400 pixles. Due to the object lens and distance to the investigated object gray-scale pictures with... | #dataset link: https://kaggle.com/ritesaluja/bank-note-authentication-uci-data
import pandas as pd
import numpy as np
df = pd.read_csv('BankNote_Authentication.csv')
df.head()
df.tail()
df.describe()
#y=dependent and x=independent features
x=df.iloc[:,:-1] #present everything in the datasset except the last column
y=df... | _____no_output_____ | MIT | bank_note_auth.ipynb | josh-boat365/docker-ml |
Curso Python Programación Contenidos 📚Este curso se separa en varios notebooks (capítulos)* [00](00.ipynb) Introducción a Python y como empezar a correrlo en Google Colab* [01](01.ipynb) Tipos básicos de datos y operaciones (Numeros y Strings)* [02](02.ipynb) Manipulación de Strings * [03](03.ipynb) Estructuras de d... | print("Hello World!") | Hello World!
| CC-BY-3.0 | 00.ipynb | domingo2000/Python-Lectures |
!Genial, acabas de correr tu primer programa de python! 😀 💻💻 Markdown ️⃣️⃣Markdown es un tipo de lenguaje de formateo de texto que busca que el texto sea fácil de leer tanto en el "codigo" como en la salida que este produce, todo el texto de este tutorial está escrito en markdown para que tengas una idea de que co... | import this | The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality... | CC-BY-3.0 | 00.ipynb | domingo2000/Python-Lectures |
Josephson Junction (Dolan) We'll be creating a Dolan style Josephson Junction. | # So, let us dive right in. For convenience, let's begin by enabling
# automatic reloading of modules when they change.
%load_ext autoreload
%autoreload 2
import qiskit_metal as metal
from qiskit_metal import designs, draw
from qiskit_metal import MetalGUI, Dict, open_docs
# Each time you create a new quantum circuit d... | _____no_output_____ | Apache-2.0 | docs/circuit-examples/A.Qubits/08-JJ-Dolan.ipynb | Antonio-Aguiar/qiskit-metal |
A dolan style josephson junctionYou can create a dolan style josephson junction from the QComponent Library, `qiskit_metal.qlibrary.qubits`. `jj_dolan.py` is the file containing our josephson junction so `jj_dolan` is the module we import. The `jj_dolan` class is our josephson junction. Like all quantum components, `... | from qiskit_metal.qlibrary.qubits.JJ_Dolan import jj_dolan
# Be aware of the default_options that can be overridden by user.
design.overwrite_enabled = True
jj2 = jj_dolan(design, 'JJ2', options=dict(x_pos="0.1", y_pos="0.0"))
gui.rebuild()
gui.autoscale()
gui.zoom_on_components(['JJ2'])
# Save screenshot as a .png fo... | _____no_output_____ | Apache-2.0 | docs/circuit-examples/A.Qubits/08-JJ-Dolan.ipynb | Antonio-Aguiar/qiskit-metal |
Closing the Qiskit Metal GUI | gui.main_window.close() | _____no_output_____ | Apache-2.0 | docs/circuit-examples/A.Qubits/08-JJ-Dolan.ipynb | Antonio-Aguiar/qiskit-metal |
Creating VariablesUnlike other programming languages, Python has no command for declaring a variable.A variable is created the moment you first assign a value to it. | x = 5
y = "I TRAIN TECHNOLOGY"
print(x)
print(y)
# Variables do not need to be declared with any particular type and can even change type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x) | Sally
| MIT | 1. Python Variables.ipynb | sivacheetas/matplotlib |
Variable Names1. A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:2. A variable name must start with a letter or the underscore character3. A variable name cannot start with a number4. A variable name can only contain alpha-numeric char... | # # Output Variables
# The Python print statement is often used to output variables.
#To combine both text and a variable, Python uses the + character:
x = "Scripting Programing"
print("Python is ",x, "Language")
x = "Python is "
y = "awesome"
z = x + y
print(z)
# For numbers, the + character works as a mathematical... | Volvo
| MIT | 1. Python Variables.ipynb | sivacheetas/matplotlib |
Converting Rating.dat to Rating.csv | ratings_dataframe=pd.read_table("ratings.dat",sep="::")
ratings_dataframe.to_csv("ratings.csv",index=False)
ratings_dataframe=pd.read_csv("ratings.csv",header=None)
ratings_dataframe.columns=["UserID","MovieID","Rating","Timestamp"]
ratings_dataframe.columns
print(ratings_dataframe.shape)
ratings_dataframe.to_csv("rati... | _____no_output_____ | MIT | DatfiletoCSV.ipynb | karangupta26/Movie-Recommendation-system |
Converting Movies.dat to Movies.csv | movies_dataframe=pd.read_table("movies.dat",sep="::")
movies_dataframe.to_csv("movies.csv",index=False)
movies_dataframe=pd.read_csv("movies.csv",header=None)
movies_dataframe.columns=["MovieID","Title","Genres"]
movies_dataframe.columns
print(movies_dataframe.shape)
movies_dataframe.to_csv("movies.csv",index=False) | (3883, 3)
| MIT | DatfiletoCSV.ipynb | karangupta26/Movie-Recommendation-system |
Converting User.dat to User.csv | users_dataframe=pd.read_table("users.dat",sep="::")
users_dataframe.to_csv("users.csv",index=False)
users_dataframe=pd.read_csv("users.csv",header=None)
users_dataframe.columns=["UserID","Gender","Age","Occupation","Zip-code"]
users_dataframe.columns
users_dataframe.to_csv("users.csv",index=False) | _____no_output_____ | MIT | DatfiletoCSV.ipynb | karangupta26/Movie-Recommendation-system |
WeatherPy----Observations:1. In the northern hemisphere the tempature increases as the latitude increases. So as the we move away from the equator to the north - the tempature decreases. 2. In the southern hemisphere, the tempature increases as you get closer to the equator. 3. In the northern hemishere, the humidity ... | # Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import time
from scipy.stats import linregress
# Import API key
from api_keys import weather_api_key
# Incorporated citipy to determine city based on latitude and longitude
from citipy import citipy
# Sa... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Generate Cities List | # List for holding lat_lngs and cities
lat_lngs = []
cities = []
# Create a set of random lat and lng combinations
lats = np.random.uniform(low=-90.000, high=90.000, size=1500)
lngs = np.random.uniform(low=-180.000, high=180.000, size=1500)
lat_lngs = zip(lats, lngs)
# Identify nearest city for each lat, lng combinat... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Perform API Calls* Perform a weather check on each city using a series of successive API calls.* Include a print log of each city as it'sbeing processed (with the city number and city name). | # set lists for the dataframe
city_two = []
cloudinesses = []
dates = []
humidities = []
lats = []
lngs = []
max_temps = []
wind_speeds = []
countries = []
# set initial count quantities for organization
count_one = 0
set_one = 1
# loops for creating dataframe columns
for city in cities:
try:
response = r... | Processing Record 1 of Set 1 | vaini
Processing Record 2 of Set 1 | punta arenas
Processing Record 3 of Set 1 | cruzilia
Processing Record 4 of Set 1 | mahibadhoo
Processing Record 5 of Set 1 | mys shmidta
Processing Record 6 of Set 1 | castro
Processing Record 7 of Set 1 | lebu
Processing Record 8 of Set 1 | butaritar... | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame |
# create a dictionary for establishing dataframe
weather_dict = {
"City":city_two,
"Cloudiness":cloudinesses,
"Country":countries,
"Date":dates,
"Humidity":humidities,
"Lat":lats,
"Lng":lngs,
"Max Temp":max_temps,
"Wind Speed":wind_speeds
}
weather_dict
# establish dataframe
weathe... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Plotting the Data* Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.* Save the plotted figures as .pngs. Latitude vs. Temperature Plot | time.strftime('%x')
plt.scatter(weather_dataframe["Lat"],weather_dataframe["Max Temp"],edgecolors="black",facecolors="skyblue")
plt.title(f"City Latitude vs. Max Temperature {time.strftime('%x')}")
plt.xlabel("Latitude")
plt.ylabel("Max Temperature (F)")
plt.grid (b=True,which="major",axis="both",linestyle="-",color="... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Latitude vs. Humidity Plot |
plt.scatter(weather_dataframe["Lat"],weather_dataframe["Humidity"],edgecolors="black",facecolors="skyblue")
plt.title("City Latitude vs. Humidity (%s)" % time.strftime('%x') )
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.ylim(15,105)
plt.grid (b=True,which="major",axis="both",linestyle="-",color="lightgrey")
... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Latitude vs. Cloudiness Plot | plt.scatter(weather_dataframe["Lat"],weather_dataframe["Cloudiness"],edgecolors="black",facecolors="skyblue")
plt.title("City Latitude vs. Cloudiness (%s)" % time.strftime('%x') )
plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
plt.grid (b=True,which="major",axis="both",linestyle="-",color="lightgrey... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Latitude vs. Wind Speed Plot | plt.scatter(weather_dataframe["Lat"],weather_dataframe["Wind Speed"],edgecolors="black",facecolors="skyblue")
plt.title("City Latitude vs. Wind Speed (%s)" % time.strftime('%x') )
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.ylim(-2,34)
plt.grid (b=True,which="major",axis="both",linestyle="-",color="lightg... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Linear Regression | #Define x and y values
x_values = weather_dataframe['Lat']
y_values = weather_dataframe['Max Temp']
# Perform a linear regression on temperature vs. latitude
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
# Get regression values
regress_values = x_values * slope + intercept
print(regress... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Northern Hemisphere - Max Temp vs. Latitude Linear Regression | def linear_agression(x,y):
print(f'The r-squared is : {round(linregress(x, y)[0],2)}')
(slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)
regress_values = x * slope + intercept
line_eq = 'y = ' + str(round(slope,2)) + 'x + ' + str(round(intercept,2))
plt.scatter(x, y)
plt.plot(x,regre... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Southern Hemisphere - Max Temp vs. Latitude Linear Regression | def linear_agression(x,y):
print(f'The r-squared is : {round(linregress(x, y)[0],2)}')
(slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)
regress_values = x * slope + intercept
line_eq = 'y = ' + str(round(slope,2)) + 'x + ' + str(round(intercept,2))
plt.scatter(x, y)
plt.plot(x,regre... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression | def linear_agression(x,y):
print(f'The r-squared is : {round(linregress(x, y)[0],2)}')
(slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)
regress_values = x * slope + intercept
line_eq = 'y = ' + str(round(slope,2)) + 'x + ' + str(round(intercept,2))
plt.scatter(x, y)
plt.plot(x,regre... | The r-squared is : 0.41
| ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression | def linear_agression(x,y):
print(f'The r-squared is : {round(linregress(x, y)[0],2)}')
(slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)
regress_values = x * slope + intercept
line_eq = 'y = ' + str(round(slope,2)) + 'x + ' + str(round(intercept,2))
plt.scatter(x, y)
plt.plot(x,regre... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression | def linear_agression(x,y):
print(f'The r-squared is : {round(linregress(x, y)[0],2)}')
(slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)
regress_values = x * slope + intercept
line_eq = 'y = ' + str(round(slope,2)) + 'x + ' + str(round(intercept,2))
plt.scatter(x, y)
plt.plot(x,regre... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression | def linear_agression(x,y):
print(f'The r-squared is : {round(linregress(x, y)[0],2)}')
(slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)
regress_values = x * slope + intercept
line_eq = 'y = ' + str(round(slope,2)) + 'x + ' + str(round(intercept,2))
plt.scatter(x, y)
plt.plot(x,regre... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression | def linear_agression(x,y):
print(f'The r-squared is : {round(linregress(x, y)[0],2)}')
(slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)
regress_values = x * slope + intercept
line_eq = 'y = ' + str(round(slope,2)) + 'x + ' + str(round(intercept,2))
plt.scatter(x, y)
plt.plot(x,regre... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression | def linear_agression(x,y):
print(f'The r-squared is : {round(linregress(x, y)[0],2)}')
(slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)
regress_values = x * slope + intercept
line_eq = 'y = ' + str(round(slope,2)) + 'x + ' + str(round(intercept,2))
plt.scatter(x, y)
plt.plot(x,regre... | _____no_output_____ | ADSL | starter_code/WeatherPy.ipynb | sruelle/python-api-challenge |
[모듈 6.1] 모델 배포 파이프라인 개발 (SageMaker Model Building Pipeline 모든 스텝)이 노트북은 아래와 같은 목차로 진행 됩니다. 전체를 모두 실행시에 완료 시간은 **약 5분** 소요 됩니다.- 0. SageMaker Model Building Pipeline 개요- 1. 파이프라인 변수 및 환경 설정- 2. 파이프라인 스텝 단계 정의 - (1) 모델 승인 상태 변경 람다 스텝 - (2) 배포할 세이지 메이커 모델 스텝 생성 - (3) 모델 앤드 포인트 배포를 위한 람다 스텝 생성 - 3. 모델 ... | import boto3
import sagemaker
import pandas as pd
region = boto3.Session().region_name
sagemaker_session = sagemaker.session.Session()
role = sagemaker.get_execution_role()
sm_client = boto3.client('sagemaker', region_name=region)
%store -r | _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
(1) 모델 빌딩 파이프라인 변수 생성파이프라인에 인자로 넘길 변수는 아래 크게 3가지 종류가 있습니다.- 모델 레지스트리에 모델 등록시에 모델 승인 상태 값 | from sagemaker.workflow.parameters import (
ParameterInteger,
ParameterString,
ParameterFloat,
)
model_approval_status = ParameterString(
name="ModelApprovalStatus", default_value="PendingManualApproval"
)
| _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
2. 파이프라인 스텝 단계 정의 (1) 모델 승인 상태 변경 람다 스텝- 모델 레지스트리에서 해당 모델 패키지 그룹을 조회하고, 가장 최신 버전의 모델에 대해서 '모델 승인 상태 변경' 을 합니다. [에러] 아래와 같은 데러가 발생시에 `0.0.Setup-Environment.ipynb` 의 정책 추가 부분을 진행 해주세요.```ClientError: An error occurred (AccessDenied) when calling the CreateRole operation: User: arn:aws:sts::0287032915XX:assumed-role/Ama... | from src.iam_helper import create_lambda_role
lambda_role = create_lambda_role("lambda-deployment-role")
print("lambda_role: \n", lambda_role)
from sagemaker.lambda_helper import Lambda
from sagemaker.workflow.lambda_step import (
LambdaStep,
LambdaOutput,
LambdaOutputTypeEnum,
)
import time
current_tim... | _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
(2) 배포할 세이지 메이커 모델 스텝 생성- 위의 람다 스텝에서 "모델 승인 상태" 를 변경한 모델에 대하여 '모델 레지스트리'에서 저장된 도커 컨테이너 이미지, 모델 아티펙트의 위치를 가져 옵니다.- 이후에 이 두개의 인자를 가지고 세이지 메이커 모델을 생성 합니다. | import boto3
sm_client = boto3.client('sagemaker')
# 위에서 생성한 model_package_group_name 을 인자로 제공 합니다.
response = sm_client.list_model_packages(ModelPackageGroupName= model_package_group_name)
ModelPackageArn = response['ModelPackageSummaryList'][0]['ModelPackageArn']
sm_client.describe_model_package(ModelPackageName=Mo... | _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
(3) 모델 앤드 포인트 배포를 위한 람다 스텝 생성- 람다 함수는 입력으로 세이지 메이커 모델, 앤드 포인트 컨피그 및 앤드 포인트 이름을 받아서, 앤드포인트를 생성 함. | # model_name = project_prefix + "-lambda-model" + current_time
endpoint_config_name = "lambda-deploy-endpoint-config-" + current_time
endpoint_name = "lambda-deploy-endpoint-" + current_time
function_name = "sagemaker-lambda-step-endpoint-deploy-" + current_time
# print("model_name: \n", model_name)
print("endpoint_c... | _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
3.모델 빌딩 파이프라인 정의 및 실행위에서 정의한 아래의 4개의 스텝으로 파이프라인 정의를 합니다.- steps=[step_process, step_train, step_create_model, step_deploy],- 아래는 약 1분 정도 소요 됩니다. 이후 아래와 같이 실행 결과를 스튜디오에서 확인할 수 있습니다.-  | from sagemaker.workflow.pipeline import Pipeline
project_prefix = 'sagemaker-pipeline-phase2-deployment-step-by-step'
pipeline_name = project_prefix
pipeline = Pipeline(
name=pipeline_name,
parameters=[
model_approval_status,
],
steps=[step_approve_lambda, step_create_best_model, s... | _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
파이프라인을 SageMaker에 제출하고 실행하기 | pipeline.upsert(role_arn=role) | _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
디폴트값을 이용하여 파이프라인을 샐행합니다. | execution = pipeline.start() | _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
파이프라인 운영: 파이프라인 대기 및 실행상태 확인워크플로우의 실행상황을 살펴봅니다. 실행이 완료될 때까지 기다립니다. | execution.wait() | _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
실행된 단계들을 리스트업합니다. 파이프라인의 단계실행 서비스에 의해 시작되거나 완료된 단계를 보여줍니다. | execution.list_steps() | _____no_output_____ | Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
5. 정리 작업 변수 저장 | depolyment_endpoint_name = endpoint_name
%store depolyment_endpoint_name
all_deployment_pipeline_name = pipeline_name
%store all_deployment_pipeline_name | Stored 'depolyment_endpoint_name' (str)
Stored 'all_deployment_pipeline_name' (str)
| Apache-2.0 | phase02/6.1.deployment-pipeline.ipynb | gonsoomoon-ml/SageMaker-Pipelines-Step-By-Step |
**Chapter 9 – Up and running with TensorFlow** _This notebook contains all the sample code and solutions to the exercises in chapter 9._ Setup First, let's make sure this notebook works well in both python 2 and 3, import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the f... | # To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
def reset_graph(seed=42):
tf.reset_default_graph()
tf.set_random_seed(seed)
np.random.seed(seed)
# To... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Creating and running a graph | import tensorflow as tf
reset_graph()
x = tf.Variable(3, name="x")
y = tf.Variable(4, name="y")
f = x*x*y + y + 2
f
sess = tf.Session()
sess.run(x.initializer)
sess.run(y.initializer)
result = sess.run(f)
print(result)
sess.close()
with tf.Session() as sess:
x.initializer.run()
y.initializer.run()
result ... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Managing graphs | reset_graph()
x1 = tf.Variable(1)
x1.graph is tf.get_default_graph()
graph = tf.Graph()
with graph.as_default():
x2 = tf.Variable(2)
x2.graph is graph
x2.graph is tf.get_default_graph()
w = tf.constant(3)
x = w + 2
y = x + 5
z = x * 3
with tf.Session() as sess:
print(y.eval()) # 10
print(z.eval()) # 15... | 10
15
| Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Linear Regression Using the Normal Equation | import numpy as np
from sklearn.datasets import fetch_california_housing
reset_graph()
housing = fetch_california_housing()
m, n = housing.data.shape
housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
X = tf.constant(housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshap... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Compare with pure NumPy | X = housing_data_plus_bias
y = housing.target.reshape(-1, 1)
theta_numpy = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
print(theta_numpy) | [[ -3.69419202e+01]
[ 4.36693293e-01]
[ 9.43577803e-03]
[ -1.07322041e-01]
[ 6.45065694e-01]
[ -3.97638942e-06]
[ -3.78654266e-03]
[ -4.21314378e-01]
[ -4.34513755e-01]]
| Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Compare with Scikit-Learn | from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(housing.data, housing.target.reshape(-1, 1))
print(np.r_[lin_reg.intercept_.reshape(-1, 1), lin_reg.coef_.T]) | [[ -3.69419202e+01]
[ 4.36693293e-01]
[ 9.43577803e-03]
[ -1.07322041e-01]
[ 6.45065694e-01]
[ -3.97638942e-06]
[ -3.78654265e-03]
[ -4.21314378e-01]
[ -4.34513755e-01]]
| Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Using Batch Gradient Descent Gradient Descent requires scaling the feature vectors first. We could do this using TF, but let's just use Scikit-Learn for now. | from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaled_housing_data = scaler.fit_transform(housing.data)
scaled_housing_data_plus_bias = np.c_[np.ones((m, 1)), scaled_housing_data]
print(scaled_housing_data_plus_bias.mean(axis=0))
print(scaled_housing_data_plus_bias.mean(axis=1))
print(scaled... | [ 1.00000000e+00 6.60969987e-17 5.50808322e-18 6.60969987e-17
-1.06030602e-16 -1.10161664e-17 3.44255201e-18 -1.07958431e-15
-8.52651283e-15]
[ 0.38915536 0.36424355 0.5116157 ..., -0.06612179 -0.06360587
0.01359031]
0.111111111111
(20640, 9)
| Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Manually computing the gradients | reset_graph()
n_epochs = 1000
learning_rate = 0.01
X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y")
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")
y_pred = tf.matmul(X, theta, nam... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Using autodiff Same as above except for the `gradients = ...` line: | reset_graph()
n_epochs = 1000
learning_rate = 0.01
X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y")
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")
y_pred = tf.matmul(X, theta, nam... | Epoch 0 MSE = 9.16154
Epoch 100 MSE = 0.714501
Epoch 200 MSE = 0.566705
Epoch 300 MSE = 0.555572
Epoch 400 MSE = 0.548812
Epoch 500 MSE = 0.543636
Epoch 600 MSE = 0.539629
Epoch 700 MSE = 0.536509
Epoch 800 MSE = 0.534068
Epoch 900 MSE = 0.532147
Best theta:
[[ 2.06855249]
[ 0.88740271]
[ 0.14401658]
[-0.34770882]
... | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
How could you find the partial derivatives of the following function with regards to `a` and `b`? | def my_func(a, b):
z = 0
for i in range(100):
z = a * np.cos(z + i) + z * np.sin(b - i)
return z
my_func(0.2, 0.3)
reset_graph()
a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
z = a * tf.cos(z + i) + z * tf.sin(b - i)
grads = ... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Let's compute the function at $a=0.2$ and $b=0.3$, and the partial derivatives at that point with regards to $a$ and with regards to $b$: | with tf.Session() as sess:
init.run()
print(z.eval())
print(sess.run(grads)) | -0.212537
[-1.1388494, 0.19671395]
| Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Using a `GradientDescentOptimizer` | reset_graph()
n_epochs = 1000
learning_rate = 0.01
X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y")
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")
y_pred = tf.matmul(X, theta, nam... | Epoch 0 MSE = 9.16154
Epoch 100 MSE = 0.714501
Epoch 200 MSE = 0.566705
Epoch 300 MSE = 0.555572
Epoch 400 MSE = 0.548812
Epoch 500 MSE = 0.543636
Epoch 600 MSE = 0.539629
Epoch 700 MSE = 0.536509
Epoch 800 MSE = 0.534068
Epoch 900 MSE = 0.532147
Best theta:
[[ 2.06855249]
[ 0.88740271]
[ 0.14401658]
[-0.34770882]
... | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Using a momentum optimizer | reset_graph()
n_epochs = 1000
learning_rate = 0.01
X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y")
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")
y_pred = tf.matmul(X, theta, nam... | Best theta:
[[ 2.06855798]
[ 0.82962859]
[ 0.11875337]
[-0.26554456]
[ 0.30571091]
[-0.00450251]
[-0.03932662]
[-0.89986444]
[-0.87052065]]
| Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Feeding data to the training algorithm Placeholder nodes | reset_graph()
A = tf.placeholder(tf.float32, shape=(None, 3))
B = A + 5
with tf.Session() as sess:
B_val_1 = B.eval(feed_dict={A: [[1, 2, 3]]})
B_val_2 = B.eval(feed_dict={A: [[4, 5, 6], [7, 8, 9]]})
print(B_val_1)
print(B_val_2) | [[ 9. 10. 11.]
[ 12. 13. 14.]]
| Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Mini-batch Gradient Descent | n_epochs = 1000
learning_rate = 0.01
reset_graph()
X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X")
y = tf.placeholder(tf.float32, shape=(None, 1), name="y")
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")
y_pred = tf.matmul(X, theta, name="predictions")
error = y_pred... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Saving and restoring a model | reset_graph()
n_epochs = 1000 # not shown in the book
learning_rate = 0.01 # not shown
X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X") # not show... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
If you want to have a saver that loads and restores `theta` with a different name, such as `"weights"`: | saver = tf.train.Saver({"weights": theta}) | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
By default the saver also saves the graph structure itself in a second file with the extension `.meta`. You can use the function `tf.train.import_meta_graph()` to restore the graph structure. This function loads the graph into the default graph and returns a `Saver` that can then be used to restore the graph state (i.e... | reset_graph()
# notice that we start with an empty graph.
saver = tf.train.import_meta_graph("/tmp/my_model_final.ckpt.meta") # this loads the graph structure
theta = tf.get_default_graph().get_tensor_by_name("theta:0") # not shown in the book
with tf.Session() as sess:
saver.restore(sess, "/tmp/my_model_final.c... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
This means that you can import a pretrained model without having to have the corresponding Python code to build the graph. This is very handy when you keep tweaking and saving your model: you can load a previously saved model without having to search for the version of the code that built it. Visualizing the graph ins... | from IPython.display import clear_output, Image, display, HTML
def strip_consts(graph_def, max_const_size=32):
"""Strip large constant values from graph_def."""
strip_def = tf.GraphDef()
for n0 in graph_def.node:
n = strip_def.node.add()
n.MergeFrom(n0)
if n.op == 'Const':
... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Using TensorBoard | reset_graph()
from datetime import datetime
now = datetime.utcnow().strftime("%Y%m%d%H%M%S")
root_logdir = "tf_logs"
logdir = "{}/run-{}/".format(root_logdir, now)
n_epochs = 1000
learning_rate = 0.01
X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X")
y = tf.placeholder(tf.float32, shape=(None, 1), name="... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Name scopes | reset_graph()
now = datetime.utcnow().strftime("%Y%m%d%H%M%S")
root_logdir = "tf_logs"
logdir = "{}/run-{}/".format(root_logdir, now)
n_epochs = 1000
learning_rate = 0.01
X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X")
y = tf.placeholder(tf.float32, shape=(None, 1), name="y")
theta = tf.Variable(tf.ran... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Modularity An ugly flat code: | reset_graph()
n_features = 3
X = tf.placeholder(tf.float32, shape=(None, n_features), name="X")
w1 = tf.Variable(tf.random_normal((n_features, 1)), name="weights1")
w2 = tf.Variable(tf.random_normal((n_features, 1)), name="weights2")
b1 = tf.Variable(0.0, name="bias1")
b2 = tf.Variable(0.0, name="bias2")
z1 = tf.add... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Much better, using a function to build the ReLUs: | reset_graph()
def relu(X):
w_shape = (int(X.get_shape()[1]), 1)
w = tf.Variable(tf.random_normal(w_shape), name="weights")
b = tf.Variable(0.0, name="bias")
z = tf.add(tf.matmul(X, w), b, name="z")
return tf.maximum(z, 0., name="relu")
n_features = 3
X = tf.placeholder(tf.float32, shape=(None, n_f... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Even better using name scopes: | reset_graph()
def relu(X):
with tf.name_scope("relu"):
w_shape = (int(X.get_shape()[1]), 1) # not shown in the book
w = tf.Variable(tf.random_normal(w_shape), name="weights") # not shown
b = tf.Variable(0.0, name="bias") # not shown
... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Sharing Variables Sharing a `threshold` variable the classic way, by defining it outside of the `relu()` function then passing it as a parameter: | reset_graph()
def relu(X, threshold):
with tf.name_scope("relu"):
w_shape = (int(X.get_shape()[1]), 1) # not shown in the book
w = tf.Variable(tf.random_normal(w_shape), name="weights") # not shown
b = tf.Variable(0.0, name="bias") # not sho... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Extra material | reset_graph()
with tf.variable_scope("my_scope"):
x0 = tf.get_variable("x", shape=(), initializer=tf.constant_initializer(0.))
x1 = tf.Variable(0., name="x")
x2 = tf.Variable(0., name="x")
with tf.variable_scope("my_scope", reuse=True):
x3 = tf.get_variable("x")
x4 = tf.Variable(0., name="x")
wit... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
The first `variable_scope()` block first creates the shared variable `x0`, named `my_scope/x`. For all operations other than shared variables (including non-shared variables), the variable scope acts like a regular name scope, which is why the two variables `x1` and `x2` have a name with a prefix `my_scope/`. Note howe... | reset_graph()
text = np.array("Do you want some café?".split())
text_tensor = tf.constant(text)
with tf.Session() as sess:
print(text_tensor.eval()) | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Implementing a Home-Made Computation Graph | class Const(object):
def __init__(self, value):
self.value = value
def evaluate(self):
return self.value
def __str__(self):
return str(self.value)
class Var(object):
def __init__(self, init_value, name):
self.value = init_value
self.name = name
def evaluate(s... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Computing gradients Mathematical differentiation | df_dx = Mul(Const(2), Mul(x, y)) # df/dx = 2xy
df_dy = Add(Mul(x, x), Const(1)) # df/dy = x² + 1
print("df/dx(3,4) =", df_dx.evaluate())
print("df/dy(3,4) =", df_dy.evaluate()) | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Numerical differentiation | def gradients(func, vars_list, eps=0.0001):
partial_derivatives = []
base_func_eval = func.evaluate()
for var in vars_list:
original_value = var.value
var.value = var.value + eps
tweaked_func_eval = func.evaluate()
var.value = original_value
derivative = (tweaked_func... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Symbolic differentiation | Const.derive = lambda self, var: Const(0)
Var.derive = lambda self, var: Const(1) if self is var else Const(0)
Add.derive = lambda self, var: Add(self.a.derive(var), self.b.derive(var))
Mul.derive = lambda self, var: Add(Mul(self.a, self.b.derive(var)), Mul(self.a.derive(var), self.b))
x = Var(3.0, name="x")
y = Var(4... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Automatic differentiation (autodiff) – forward mode | class DualNumber(object):
def __init__(self, value=0.0, eps=0.0):
self.value = value
self.eps = eps
def __add__(self, b):
return DualNumber(self.value + self.to_dual(b).value,
self.eps + self.to_dual(b).eps)
def __radd__(self, a):
return self.to_dual... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
$3 + (3 + 4 \epsilon) = 6 + 4\epsilon$ | 3 + DualNumber(3, 4) | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
$(3 + 4ε)\times(5 + 7ε) = 3 \times 5 + 3 \times 7ε + 4ε \times 5 + 4ε \times 7ε = 15 + 21ε + 20ε + 28ε^2 = 15 + 41ε + 28 \times 0 = 15 + 41ε$ | DualNumber(3, 4) * DualNumber(5, 7)
x.value = DualNumber(3.0)
y.value = DualNumber(4.0)
f.evaluate()
x.value = DualNumber(3.0, 1.0) # 3 + ε
y.value = DualNumber(4.0) # 4
df_dx = f.evaluate().eps
x.value = DualNumber(3.0) # 3
y.value = DualNumber(4.0, 1.0) # 4 + ε
df_dy = f.evaluate().eps
df_dx
df_dy | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Autodiff – Reverse mode | class Const(object):
def __init__(self, value):
self.value = value
def evaluate(self):
return self.value
def backpropagate(self, gradient):
pass
def __str__(self):
return str(self.value)
class Var(object):
def __init__(self, init_value, name):
self.value = in... | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Autodiff – reverse mode (using TensorFlow) | reset_graph()
x = tf.Variable(3., name="x")
y = tf.Variable(4., name="y")
f = x*x*y + y + 2
gradients = tf.gradients(f, [x, y])
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
f_val, gradients_val = sess.run([f, gradients])
f_val, gradients_val | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Exercise solutions 1. to 11. See appendix A. 12. Logistic Regression with Mini-Batch Gradient Descent using TensorFlow First, let's create the moons dataset using Scikit-Learn's `make_moons()` function: | from sklearn.datasets import make_moons
m = 1000
X_moons, y_moons = make_moons(m, noise=0.1, random_state=42) | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Let's take a peek at the dataset: | plt.plot(X_moons[y_moons == 1, 0], X_moons[y_moons == 1, 1], 'go', label="Positive")
plt.plot(X_moons[y_moons == 0, 0], X_moons[y_moons == 0, 1], 'r^', label="Negative")
plt.legend()
plt.show() | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
We must not forget to add an extra bias feature ($x_0 = 1$) to every instance. For this, we just need to add a column full of 1s on the left of the input matrix $\mathbf{X}$: | X_moons_with_bias = np.c_[np.ones((m, 1)), X_moons] | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Let's check: | X_moons_with_bias[:5] | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Looks good. Now let's reshape `y_train` to make it a column vector (i.e. a 2D array with a single column): | y_moons_column_vector = y_moons.reshape(-1, 1) | _____no_output_____ | Apache-2.0 | 09_up_and_running_with_tensorflow.ipynb | JeffRisberg/SciKit_and_Data_Science |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.