markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
G Write a function, not_in_between, which takes three parameters: a NumPy array a lower threshold, a floating point value an upper threshold, a floating point value You should use a boolean mask to return only the values in the NumPy array that are NOT in between the two specified threshold values, lower and upper. N...
import numpy as np np.random.seed(475185) x = np.random.random((10, 20, 30)) lo = 0.001 hi = 0.999 y = np.array([ 9.52511605e-04, 8.62993716e-04, 3.70243252e-04, 9.99945849e-01, 7.21751759e-04, 9.36931041e-04, 5.10792605e-04, 6.44911672e-04]) np.testing.assert_allclose(y, not_in_between(x,...
assignments/A6/A6_Q2.ipynb
eds-uga/csci1360-fa16
mit
H Write a function, reverse_array, which takes one parameter: a 1D NumPy array of data This function uses fancy indexing to reverse the ordering of the elements in the input array, and returns the reversed array. You cannot use the [::-1] notation, nor the built-in reversed method, or any other Python function or loo...
import numpy as np np.random.seed(5748) x1 = np.random.random(75) y1 = x1[::-1] # Sorry, you're not allowed to do this! np.testing.assert_allclose(y1, reverse_array(x1)) x2 = np.random.random(581) y2 = x2[::-1] # Sorry, you're not allowed to do this! np.testing.assert_allclose(y2, reverse_array(x2))
assignments/A6/A6_Q2.ipynb
eds-uga/csci1360-fa16
mit
US income mobility example Similar to Markov Based Methods notebook, we will demonstrate the usage of the mobility methods by an application to data on per capita incomes observed annually from 1929 to 2009 for the lower 48 US states.
import libpysal import numpy as np import mapclassify as mc income_path = libpysal.examples.get_path("usjoin.csv") f = libpysal.io.open(income_path) pci = np.array([f.by_col[str(y)] for y in range(1929, 2010)]) #each column represents an state's income time series 1929-2010 q5 = np.array([mc.Quantiles(y).yb for y in p...
notebooks/MobilityMeasures.ipynb
sjsrey/giddy
bsd-3-clause
After acquiring the estimate of transition probability matrix, we could call the method $markov_mobility$ to estimate any of the five Markov-based summary mobility indice. 1. Shorrock1's mobility measure \begin{equation} M_{P} = \frac{m-\sum_{i=1}^m P_{ii}}{m-1} \end{equation} python measure = "P"
mobility.markov_mobility(m.p, measure="P")
notebooks/MobilityMeasures.ipynb
sjsrey/giddy
bsd-3-clause
2. Shorroks2's mobility measure \begin{equation} M_{D} = 1 - |\det(P)| \end{equation} python measure = "D"
mobility.markov_mobility(m.p, measure="D")
notebooks/MobilityMeasures.ipynb
sjsrey/giddy
bsd-3-clause
3. Sommers and Conlisk's mobility measure \begin{equation} M_{L2} = 1 - |\lambda_2| \end{equation} python measure = "L2"
mobility.markov_mobility(m.p, measure = "L2")
notebooks/MobilityMeasures.ipynb
sjsrey/giddy
bsd-3-clause
4. Bartholomew1's mobility measure \begin{equation} M_{B1} = \frac{m-m \sum_{i=1}^m \pi_i P_{ii}}{m-1} \end{equation} $\pi$: the inital income distribution python measure = "B1"
pi = np.array([0.1,0.2,0.2,0.4,0.1]) mobility.markov_mobility(m.p, measure = "B1", ini=pi)
notebooks/MobilityMeasures.ipynb
sjsrey/giddy
bsd-3-clause
5. Bartholomew2's mobility measure \begin{equation} M_{B2} = \frac{1}{m-1} \sum_{i=1}^m \sum_{j=1}^m \pi_i P_{ij} |i-j| \end{equation} $\pi$: the inital income distribution python measure = "B1"
pi = np.array([0.1,0.2,0.2,0.4,0.1]) mobility.markov_mobility(m.p, measure = "B2", ini=pi)
notebooks/MobilityMeasures.ipynb
sjsrey/giddy
bsd-3-clause
We can query results from the database based off a variety of values, but for this example we will query a known result from the database.
record = client.query_procedures(id=1683293)[0] record
docs/qcportal/source/record-optimization-example.ipynb
psi4/DatenQM
bsd-3-clause
There are a variety of helper functions on this object to find quantities related to the computation.
record.get_final_molecule() record.show_history()
docs/qcportal/source/record-optimization-example.ipynb
psi4/DatenQM
bsd-3-clause
We can also observe the program, method, and basis for which the optimization was executed under.
record.qc_spec.dict()
docs/qcportal/source/record-optimization-example.ipynb
psi4/DatenQM
bsd-3-clause
We can also find all keywords passed into the geometry optimization. Here we see that this geometry optimization was evaluated under a dihedral constraint.
record.keywords
docs/qcportal/source/record-optimization-example.ipynb
psi4/DatenQM
bsd-3-clause
Finally, every Result generated in the computational trajectory can be queried and observed. Here we will obtain the very last computed Result.
record.get_trajectory()[-1]
docs/qcportal/source/record-optimization-example.ipynb
psi4/DatenQM
bsd-3-clause
To run a optimization on this methane molecule we need to specify the full input as shown below. It should be noted that this function is also organized in such a way where the optimization of many molecules with the same level of theory is most efficient.
options = { "keywords": {'coordsys': 'tric'}, # Geometry optimization program options "qc_spec": { # Quantum chemistry specifications "driver": "gradient", "method": "HF", "basis": "sto-3g", "keywords": None, "program": "psi4" }, } compute = clien...
docs/qcportal/source/record-optimization-example.ipynb
psi4/DatenQM
bsd-3-clause
The ids of the submitted optimization can then be queried and examined. As a note the computation is not instantaneous, you may need to wait a moment and requery for this small molecule.
result = client.query_procedures(id=compute.ids)[0] result ch_bond_original = result.get_initial_molecule().measure([0, 1]) ch_bond_optimized = result.get_final_molecule().measure([0, 1]) print(f"Optimized/Original C-H bond {ch_bond_original}/{ch_bond_optimized} (bohr)") result.show_history()
docs/qcportal/source/record-optimization-example.ipynb
psi4/DatenQM
bsd-3-clause
1) Open your dataset up using pandas in a Jupyter notebook
df = pd.read_csv('Mother Jones US Mass Shootings 1982-2016 - US mass shootings.csv')
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
2) Do a .head() to get a feel for your data
df.head() df.columns
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
3) Write down 12 questions to ask your data, or 12 things to hunt for in the data Are more weapons obtained legally or illegally? Where are most weapons obtained? What state has the most mass shootings? Which mass shooting had the most wounded? / How many wounded? Which mass shootings had the most victims? What mass s...
df['Weapons obtained legally'] = df['Weapons obtained legally'].str.replace('\nYes', 'Yes') df['Weapons obtained legally'] = df['Weapons obtained legally'].str.replace('Yes\s.+','Yes') df['Weapons obtained legally'] = df['Weapons obtained legally'].str.replace('Yes ','Yes') df['Weapons obtained legally'].str.strip() a...
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
2) Where are most weapons obtained?
df['Gun Show'] = df['Where obtained'].str.contains('[Ss]how', na=False) df['Online'] = df['Where obtained'].str.contains('[Oo]nline') | df['Where obtained'].str.contains('[Ii]nternet') df['Family/Friends'] = df['Where obtained'].str.contains('[Gg]randfather')| df['Where obtained'].str.contains('[Mm]other') | df['Where ...
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
3) Where state has the most mass shootings?
# create empty list states = [] # split the string values in location such that city, state become tuples # iterate over list of tuples, appending only the state to the above list for item in df['Location'].str.split(','): states.append(item[1]) # create series by setting series equal to the list df['State'] ...
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
4) Which mass shooting had the most wounded? / How many were wounded?
df['Wounded'].idxmax() # returns index of maximum of values in a series df['Case'].iloc[23] df['Wounded'].iloc[23]
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
5) Which mass shootings had the most victims?
df['Total victims'].idxmax() df['Case'].iloc[23]
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
6) What mass shooting was most fatal?
df['Fatalities'].idxmax() # returns index of maximum of values in a series df['Case'].iloc[1]
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
7) What kind of weapons were used in the most fatal shootings? / Do shooters use a glock more often than not?
df['Weapon details'].iloc[1] #case = Orlando nightclub df['Glock'] = df['Weapon details'].str.contains('[Gg]locks') | df['Weapon details'].str.contains('[Gg]lock') df['Glock'].value_counts().plot(kind='bar', title = 'Shooter used a Glock?')
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
8) What kind of weapons were used in the shootings that had the most victims (wounded and fatal)?
df['Weapon details'].iloc[23]
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
9) How many shooters showed prior signs of mental illness?
df['Prior signs of possible mental illness'].value_counts() df['Prior signs of possible mental illness'] = df['Prior signs of possible mental illness'].str.replace('Unclear', 'Unknown') df['Prior signs of possible mental illness']= df['Prior signs of possible mental illness'].str.replace('unknown', 'Unknown') df['Prior...
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
10) In which kind of venue do most mass shootings occur?
df['Venue'] = df['Venue'].str.replace('Other\n', 'Other') df['Venue'] = df['Venue'].str.replace('\nWorkplace', 'Workplace') df['Venue'].value_counts()
08/Homework_8_Emelike.ipynb
mercye/foundations-homework
mit
Example: 2HDM w/ U(2) symmetry LO partial wave matrices
def My1s1(l1, l3): return -l1*np.identity(3)/(16*np.pi) def My1s0(l1, l3): return -(l1+2*l3)*np.identity(1)/(16*np.pi) def My0s1(l1, l3): return -np.array([[l1, l1-l3, 0, 0],[l1-l3, l1, 0, 0],[0, 0, l3, 0],[0, 0, 0, l3]])/(16*np.pi) def My0s0(l1, l3): return -np.array([[3*l1, l1+l3, 0, 0],[l1+l3, 3*l1, ...
NLOUnitarityBounds.ipynb
christopher-w-murphy/NLOUnitarityBounds
mit
Beta Functions
def betafunctions(l1, l3): # returns a list with the beta functions for the quartic couplings l1 and l3 return np.array([14*l1**2 + 2*l3**2, 6*l1**2 + 4*l1*l3 + 6*l3**2])/(16*np.pi**2)
NLOUnitarityBounds.ipynb
christopher-w-murphy/NLOUnitarityBounds
mit
Beta function contributions to the partial wave matrices (w/ factor of -3/2 included)
def bMy1s1(l1, l3): return -(3/2)*My1s1(*betafunctions(l1, l3)) def bMy1s0(l1, l3): return -(3/2)*My1s0(*betafunctions(l1, l3)) def bMy0s1(l1, l3): return -(3/2)*My0s1(*betafunctions(l1, l3)) def bMy0s0(l1, l3): return -(3/2)*My0s0(*betafunctions(l1, l3))
NLOUnitarityBounds.ipynb
christopher-w-murphy/NLOUnitarityBounds
mit
Plot compare against FIG. 1 (a) of arXiv:1502.08511, which was made entirely using Mathematica.
import matplotlib %matplotlib inline matplotlib.rc('text', usetex = True) matplotlib.rc('font', family = 'serif') matplotlib.rcParams['xtick.direction'] = 'in' matplotlib.rcParams['ytick.direction'] = 'in' delta = 0.3 x = np.arange(-15.0, 15.3, delta) y = np.arange(-15.0, 15.3, delta) X, Y = np.meshgrid(x, y) Z1 = (...
NLOUnitarityBounds.ipynb
christopher-w-murphy/NLOUnitarityBounds
mit
Preamble
import os, time as tm, warnings warnings.filterwarnings( "ignore" ) # from IPython.core.display import HTML from IPython.display import display, HTML import numpy as np import matplotlib.pyplot as plt %matplotlib inline np.random.seed( 569034853 ) ## This is the correct way to use the random number generator, ## si...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
EM and MNIST The $\TeX$ markup used here uses the "align*" environment and thus should not be viewed though nbViewer. Before proceeding, it seems pedagogically necessary (at least for myself) to revise the EM-slgorithm and show its "correctness", so to say. A brief description of the EM algorithm The EM algorithm seeks...
## A bunch of wrappers to match the task specifications def posterior( x, clusters ) : pi = np.ones( clusters.shape[ 0 ], dtype = np.float ) / clusters.shape[ 0 ] q, ll = __posterior( x, theta = clusters, pi = pi ) return q ## The likelihood is a byproduct of the E-step's minimization of Kullback-Leibler d...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Classify using the maximum aposteriori rule.
## Classifier def classify( x, theta, pi = None ) : pi = pi if pi is not None else np.ones( theta.shape[ 0 ], dtype = np.float ) / theta.shape[ 0 ] ## Compute the posterior probabilities of the data q_sk, ll_s = __posterior( x, theta = theta, pi = pi ) ## Classify according to max pasterior: c_s = np.argmax...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
A procedure to compute the log-likelihood of each observaton with respect to each mixture component. Used in the posterior computation.
def __component_likelihood( x, theta ) : ## Unfortunately sometimes there can be negative machine zeros, which ## spoil the log-likelihood computation by poisoning with NANs. ## That is why the theta array is restricted to [0,1]. theta_clipped = np.clip( theta, 0.0, 1.0 ) ## Iterate over classes ll_sk = np.zer...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
The actual procedure for computing the E*-step: the conditional distribution and the log-likelihood scores.
## The core procedure for computing the conditional density of classes def __posterior( x, theta, pi ) : ## Get the log-likelihoods of each observation in each mixture component. ll_sk = __component_likelihood( x, theta ) ## Find the largest unnormalized probability. llstar_s = np.reshape( np.max( ll_sk, axis =...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Analytic solution: M-step At the M-step for some fixed $q(Z)$ one solves $\mathbb{E}\log p(X,Z|\Theta)\to \max_\Theta$ subject to $\sum_{k=1}^K \pi_k = 1$ which is a convex optimization problem with respect to $\Theta$, since the log-likelihood as a linear combination of convex functions is convex. The first order cond...
## The E-step is simple: just compute the optimal parameters under ## the current conditional distribution of the latent variables. def __learn_clusters( x, z ) : ## The prior class probabilities pi = z.sum( axis = ( 0, ) ) ## Pixel probabilities conditional on the calss theta = np.tensordot( z, x, ( 0, 0 ) ) ...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
A wrapper to match the assignment specifications.
## A wrapper for the above function def learn_clusters( x, z ) : theta, pi = __learn_clusters( x, z ) ## Just return theta: in the condtional model the pi are fixed. return theta
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
A it has been mentioned eariler, the EM algorithm switches between E and M steps until convergence.
## A wrapper for the core em algorithm below def em_algorithm( x, K, maxiter, verbose = True, rel_eps = 1e-4, full = False ) : ## Initialize the model parameters with uniform [0.25,0.75] random numbers theta_1 = rand.uniform( size = ( K, x.shape[ 1 ] ) ) * 0.5 + 0.25 pi_1 = None if not full else np.ones( K, dty...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
The procedure above actually invokes the true EM core, defined below.
## The core of the EM algorithm def __em_algorithm( x, theta_1, pi_1 = None, niter = 1000, rel_eps = 1e-4, verbose = True ) : ## If we were supplied with an initial estimate of the prior distribution, ## then assume the full model is needed. full_model = pi_1 is not None ## If the prior cluster probabilities are n...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Define a convenient procedure for running experiments. By setting relative error to zero the algorithm is forced to exhaust all the allocated iterations.
def experiment( data, K, maxiter, verbose = True, until_convergence = False, full = False ) : ## Run the EM return em_algorithm( data, K, maxiter, rel_eps = 1.0e-4 if until_convergence else 0.0, verbose = verbose, full = full )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Miscellanea: visualization In order to be able to plot more flexibly, define another arranger.
## A more flexible image arrangement def arrange_flex( images, n_row = 10, n_col = 10, N = 28, M = 28, fill_value = 0 ) : ## Create the final grid of images row-by-row im_grid = np.full( ( n_row * N, n_col * M ), fill_value, dtype = images.dtype ) for k in range( min( images.shape[ 0 ], n_col * n_row ) ) : ## G...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
The folowing pair of procedures are used to plot the digits in a clear manner. The first one just creates a canvas for the image: it sets up both axes properly and adds labels to them.
def setup_canvas( axis, n_row, n_col, N = 28, M = 28 ) : ## Setup major tick marks to the seam between images and disable their labels axis.set_yticks( np.arange( 1, n_row + 1 ) * N, minor = False ) axis.set_xticks( np.arange( 1, n_col + 1 ) * M, minor = False ) axis.set_yticklabels( [ ], minor = False ) ; ...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
This procedure displays the images on a nice plot. Used for one-line visualization.
def show_data( data, n, n_col = 10, transpose = False, **kwargs ) : ## Get the number of rows necessary to plot the needed number of images n_row = ( n + n_col - 1 ) // n_col ## Transpose if necessary if transpose : n_col, n_row = n_row, n_col ## Set the dimensions of the figure fig = plt.figure( fi...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
MIscellanea: animating the EM This function creates an animation of successive iterations of a run of the EM.
def animate( theta, ll, pi = None, n_col = 10, n_row = 10, interval = 1, **kwargs ) : ## Create a background bg = arrange_flex( np.zeros_like( theta[ 0 ] ), n_col = n_col, n_row = n_row ) ## Compute log-likelihood differences and sanitize them. ll_diff = np.maximum( np.diff( ll ), np.finfo(np.float).eps ) l...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Define a function that produces (using ffmpeg) and embeds a video in HTML into IPython
## Make simple animations of the EM estimatora ## http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/ ## http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/ from matplotlib import animation from IPython.display import HTML from tempfile import NamedTemporaryFile def embed_vide...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Miscellanea: obtaining the data Try to download the MNIST data from the SciKit repository.
if False : ## Fetch MNIST dataset from SciKit and create a local copy. from sklearn.datasets import fetch_mldata mnist = fetch_mldata( "MNIST original", data_home = './data/' ) np.savez_compressed('./data/mnist/mnist_scikit.npz', data = mnist.data, labels = mnist.target )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Or obtain the data from the provided CSV files.
if False : ## The procedure below loads the MNIST data from a comma-separated text file. def load_mnist_from_csv( filename ) : ## Read the CSV file data = np.loadtxt( open( filename, "rb" ), dtype = np.short, delimiter = ",", skiprows = 0 ) ## Peel off the lables return data[:,1:], data[:,0] ## Fetc...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Study First of all load and binarize the training data using the value 127 as the threshold.
assert( os.path.exists( './data/mnist/mnist_train.npz' ) ) with np.load( './data/mnist/mnist_train.npz', 'r' ) as npz : mnist_labels, mnist_data = npz[ 'labels' ], np.array( npz[ 'data' ] > 127, np.int ) assert( os.path.exists( './data/mnist/mnist_test.npz' ) ) with np.load( './data/mnist/mnist_test.npz', 'r' ...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Case : $K=2$ Let's have a look at some 6s and 9s.
## Mask inx_sixes, inx_nines = np.where( mnist_labels == 6 )[ 0 ], np.where( mnist_labels == 9 )[ 0 ] ## Extract sixes = mnist_data[ rand.choice( inx_sixes, 90, replace = False ) ] nines = mnist_data[ rand.choice( inx_nines, 90, replace = False ) ] ## Show show_data( sixes, n = 45, n_col = 15, cmap = plt.cm.gray, inter...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
They do indeed look quite distinct. Now collect them into a single dataset and estimate the model.
data = mnist_data[ np.append( inx_sixes, inx_nines ) ] clusters, ll = experiment( data, 2, 30 )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
The estimate deltas show that the EM algorithm's E-step actually transfers the unlikely observations between classes, as is expected by constructon of the algorithm. Judging by the plot below, it turns out that 30 iterations is more than enough for the EM to get meaninful estimates the class ideals, represented by the ...
visualize( data, clusters, ll )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Now let's see how well the EM algorithm performs on a model with more classes. But before that let's have a look at a random sample of the handwritten digits.
indices = np.arange( mnist_data.shape[ 0 ] ) rand.shuffle( indices ) show_data( mnist_data[ indices[:100] ] , n = 100, n_col = 10, cmap = plt.cm.gray, interpolation = 'nearest' )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Case : $K=10, 15, 20, 30, 60$ and $90$ The original size of the trainig sample is too large to fit in these RAM banks :) That is why I had to limit the sample to a random subset of 2000 observations.
sub_sample = np.concatenate( tuple( [ rand.choice( np.where( mnist_labels == i )[ 0 ], size = 200 ) for i in range( 10 ) ] ) ) train_data, train_labels = mnist_data[ sub_sample ], mnist_labels[ sub_sample ] # train_data, train_labels = mnist_data, mnist_labels
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Run the procedure that perfoems EM algorithm and return the history of the parameter estimates as well as the dynamics of the log-likelihood lower bonud.
clusters_10, ll_10 = experiment( train_data, 10, 50 )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
One can clearly see, that $50$ iterations were not enough for the alogirithm to converge: though the changes are tiny, even on the log-scale, they are still unstable.
visualize( train_data, clusters_10, ll_10, n_col = 10, plot_ll = True )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Let's see if changing $K$ does the trick.
clusters_15, ll_15 = experiment( train_data, 15, 50, verbose = False, until_convergence = False ) clusters_20, ll_20 = experiment( train_data, 20, 50, verbose = False, until_convergence = False ) clusters_30, ll_30 = experiment( train_data, 30, 50, verbose = False, until_convergence = False )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
For what values of $K$ was it possible to infer the templates of all digits?
visualize( train_data, clusters_15, ll_15, n_col = 10, plot_ll = False ) visualize( train_data, clusters_20, ll_20, n_col = 10, plot_ll = False ) visualize( train_data, clusters_30, ll_30, n_col = 10, plot_ll = False )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Obviously, the model with more mixture components is more likely to produce "templates" for all digits. For larger $K$ this is indeed the case. Having run this algorithm for many times we are able to say that the digits $3$ and $8$, $4$ and $9$ and sometimes $5$ tend to be poorly separated. Furthermore due to there bei...
clusters_60, ll_60 = experiment( train_data, 60, 500, verbose = False, until_convergence = True )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
As one can see, increasing the number of iterations does not necessarily improve the results.
visualize( train_data, clusters_60, ll_60, n_col = 15 )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Judging by the plot of the log-likelihood, the fact that the EM is guaranteed to converge to local maxima and does so extremely fast, there was no need for more than 120-130 iterations. The chages in the log-likelihood around that number of iterations are of the order $10^{-4}$. Since we are working in finite precision...
## If you want to see this animation ensure that ffmpeg is installed and uncomment the following lines. anim_60 = animate( clusters_60, ll_60, n_col = 15, n_row = 4, interval = 1, cmap = plt.cm.hot, interpolation = 'nearest' ) embed_video( anim_60 )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
The parameter estimates of the EM stabilize pretty quickly. In fact most templates stabilize by iterations 100-120. Choosing $K$ Among many methods of model selection, let's use simple training sample fittness score, givne by the value of the log-likelihood. Becasue the models are nested with respect to the number of m...
## Test model with K from 12 up to 42 with a step of 4 classes = 12 + np.arange( 11, dtype = np.int ) * 3 ll_hist = np.full( len( classes ), -np.inf, dtype = np.float ) ## Store parameters parameter_hist = list( ) for i, K in enumerate( classes ) : ## Run the experiment c, l = experiment( train_data, K, 50, verbose...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Indeed the log-likelihood does not decrease with $K$ on average. Nevertheless the model with the highes likelihood turs out to have this many mixture components:
print classes[ np.argmax( ll_hist ) ]
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
A nice, yet expected coincidence :) Classification: label assignment Select a model ...
# clusters = parameter_hist[ np.argmax( ll_hist ) ] * 0.999 + 0.0005 clusters = clusters_60[-1]
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
... and get the posterior mixture component probabilities.
## Compute the posterior component probabilities, and use max-aposteriori ## for the best class selection. c_s, q_sk, ll_s = classify( train_data, clusters )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Use a simple majority rule to automatically assign lables to templates.
template_x_label_maj_60 = np.full( clusters.shape[ 0 ], -1, np.int ) for t in range( clusters.shape[ 0 ] ) : l, f = np.unique( train_labels[ c_s == t ], return_counts = True) if len( l ) > 0 : ## This is too blunt an approach: it does not guarantee surjectivity of the mapping. template_x_label_maj_60[ t...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Assign the labels $l$ to templates $t$ according to its score, based on the average of the top-$5$ log-likelihoods of observations with label $l$ and classfified with template $t$.
## there are 10 labels and K templates label_cluster_score = np.full( ( clusters.shape[ 0 ], 10 ), -np.inf, np.float ) ## Loop over each template for t in range( clusters.shape[ 0 ] ) : ## The selected templates are chosen according to max-aposteriori rule. inx = np.where( c_s == t )[ 0 ] ## Get the assigned lables...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Compare the label assignments. Here are the templates.
show_data( clusters, clusters.shape[ 0 ], 10, cmap = plt.cm.spectral, interpolation = 'nearest' )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
These are the templates, which were assigned different labels by the majority and "trust" methods.
mask = np.asarray( template_x_label_maj_60 != template_x_label_lik_60, dtype = np.float ).reshape( (-1,1) ) show_data( clusters * mask, clusters.shape[ 0 ], 10, cmap = plt.cm.spectral, interpolation = 'nearest' ) print "\nLikelihood based: ", template_x_label_lik_60[ mask[:,0] > 0 ] print "Majority bassed: "...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Here are the pictures of templates ordered according to their label.
show_data( clusters[ np.argsort( template_x_label_lik_60 ) ], clusters.shape[ 0 ], 10, cmap = plt.cm.spectral, interpolation = 'nearest' ) show_data( clusters[ np.argsort( template_x_label_maj_60 ) ], clusters.shape[ 0 ], 10, cmap = plt.cm.spectral, interpolation = 'nearest' )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Classification: test sample Shall we try running the classifier on the test data?
## Run the classifier on the test data c_s_60, q_sk, ll_s = classify( test_data, clusters )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Let's see the best template for each test observation in some sub-sample.
## Show a sample of images and their templates sample = np.random.permutation( test_data.shape[ 0 ] )[:64] ## Stack image and tis best template atop one another display_stack = np.empty( ( 2 * len( sample ), test_data.shape[ 1 ] ), dtype = np.float ) display_stack[0::2] = test_data[ sample ] * q_sk[ sample, c_s_60[ sam...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
The digits are shown in pairs: each first digit is the test observation (colour is determined by the confidence of the classifier -- the whiter the higher), and each second -- is the best template. Let's see how accurate the classification was. Recall that the component assignment was done using $$ \hat{t}_s = \mathop...
print "Accuracy of likelihood based labelling: %.2f" % ( 100 * np.average( template_x_label_lik_60[ c_s_60 ] == test_labels ), ) print "Accuracy of simple majority labelling: %.2f" % ( 100 * np.average( template_x_label_maj_60[ c_s_60 ] == test_labels ), )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Not surprisingly, majority- and likelihood-based classification accuracies are close. Let's see which test observations the model considers an artefact and for which it cannot reliably assign a template: i.e. the posterior class probablity for these cases coincides with the prior. This happens when the likelihood of an...
## Now display the test observations, which the model cold nor classify at all. bad_tests = np.where( np.isinf( ll_s ) )[ 0 ] show_data( test_data[ bad_tests ], n = max( len( bad_tests ), 10 ), n_col = 15, cmap = plt.cm.gray, interpolation = 'nearest' ) # print q_sk[ bad_tests ]
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
</hr> Let's see how more pasrimonious models fare with respect to accuracy on thte test sample. Accuracy of $K=30$
clusters = clusters_30[-1] c_s, q_sk, ll_s = classify( train_data, clusters ) template_x_label_maj_30 = np.full( clusters.shape[ 0 ], -1, np.int ) for t in range( clusters.shape[ 0 ] ) : l, f = np.unique( train_labels[ c_s == t ], return_counts = True) if len( l ) > 0 : template_x_label_maj_30[ t ] = l...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Accuracy of $K=20$
clusters = clusters_20[-1] c_s, q_sk, ll_s = classify( train_data, clusters ) template_x_label_maj_20 = np.full( clusters.shape[ 0 ], -1, np.int ) for t in range( clusters.shape[ 0 ] ) : l, f = np.unique( train_labels[ c_s == t ], return_counts = True) if len( l ) > 0 : template_x_label_maj_20[ t ] = l...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Accuracy of $K=15$
clusters = clusters_15[-1] c_s, q_sk, ll_s = classify( train_data, clusters ) template_x_label_maj_15 = np.full( clusters.shape[ 0 ], -1, np.int ) for t in range( clusters.shape[ 0 ] ) : l, f = np.unique( train_labels[ c_s == t ], return_counts = True) if len( l ) > 0 : template_x_label_maj_15[ t ] = l...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Accuracy of $K=10$
clusters = clusters_10[-1] c_s, q_sk, ll_s = classify( train_data, clusters ) template_x_label_maj_10 = np.full( clusters.shape[ 0 ], -1, np.int ) for t in range( clusters.shape[ 0 ] ) : l, f = np.unique( train_labels[ c_s == t ], return_counts = True) if len( l ) > 0 : template_x_label_maj_10[ t ] = l...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
As one can see test sample accuracy of the model falls drammatically for less number of mixture components. This was expected, since due to various reasons, one being thet the data is handwritten, it is higly unlikely, that a single digit would have only one template.
print "Model with K = 10: %.2f" % ( 100 * np.average( template_x_label_lik_10[ c_s_10 ] == test_labels ), ) print "Model with K = 15: %.2f" % ( 100 * np.average( template_x_label_lik_15[ c_s_15 ] == test_labels ), ) print "Model with K = 20: %.2f" % ( 100 * np.average( template_x_label_lik_20[ c_s_20 ] == test_labels )...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
<br/><p style="font-size: 20pt;font-weight: bold; text-align: center;font-family: Courier New"> Ignore everything below </p><br/> Let digress for a moment and consider the full model and create a video to see how the estimates are refined.
( clusters_full, pi_full ), ll_full = experiment( data, 30, 1000, False, True, True ) anim_full = animate( clusters_full, ll_full, pi = pi_full, n_col = 15, n_row = 2, interval = 1, cmap = plt.cm.hot, interpolation = 'nearest' ) embed_video( anim_full )
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
<hr/> A random variable $X\sim \text{Beta}(\alpha,\beta)$ if the law of $X$ has density $$p(u) = \frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)} u^{\alpha-1}(1-u)^{\beta-1} $$ $$ \log p(X,Z|\Theta) = \sum_{s=1}^n \log \prod_{k=1}^K \Bigl[ \pi_k \prod_{i=1}^N \prod_{j=1}^M \frac{\Gamma(\alpha_{kij}+\beta_{ki...
from sklearn.neighbors import KernelDensity from sklearn.decomposition import PCA from sklearn.grid_search import GridSearchCV pca = PCA( n_components = 50 ) X_train_pca = pca.fit_transform( X_train ) params = { 'bandwidth' : np.logspace( -1, 1, 20 ) } grid = GridSearchCV( KernelDensity( ), params ) grid.fit( X_train...
year_14_15/spring_2015/machine_learning/MNIST-assignment.ipynb
ivannz/study_notes
mit
Linear Discriminant Analysis Predict groupings in continuous data.
X = np.linspace(0, 20, 100) def f(x): if x < 7: return 'a', 2. + np.random.random() elif x < 14: return 'b', 4 + np.random.random() else: return 'c', 6 + np.random.random() K, Y = zip(*[f(x) for x in X]) colors = plt.get_cmap('Set1') categories = ['a', 'b', 'c'] plt.scatter(X, Y, c=[...
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
LDA is like inverted ANOVA: ANOVA looks for differences in a continuous response among categories, whereas LDA infers categories using a continuous predictor.
bycategory = [ [Y[i] for i in xrange(len(Y)) if K[i] == k] for k in categories ] plt.figure(figsize=(10, 5)) plt.subplot(121) plt.boxplot(bycategory) plt.ylim(0, 8) plt.title('ANOVA') plt.subplot(122) plt.boxplot(bycategory, 0, 'rs', 0) plt.title('LDA') plt.xlim(0, 8) plt.show()
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
LDA assumes that the variance in each group is the same, and that the predictor(s) are normally distributed for each group. In other words, different $\mu_k$, one shared $\sigma$.
X = [np.linspace(0, 7, 50), np.linspace(2, 10, 50), np.linspace(7, 16, 50)] plt.figure(figsize=(10, 4)) k = 1 for x in X: mu_k = x.mean() plt.plot(x, stats.norm.pdf(x, loc=mu_k)) plt.plot([mu_k, mu_k], [0, 0.5], c='k') plt.text(mu_k + 0.2, 0.5, "$\mu_%i$" % k, size=18) k += 1 plt.ylim(0, ...
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
Recall Bayes Theorem: this allows us to "flip" the predictor and the response. $P(A|B) = \frac{P(B|A)P(A)}{P(B|A) P(A) P(B|\bar{A}) P(\bar{A})}$ Therefore the probability of group $k$ given the continuous predictor B is: $P(A_k|B) = \frac{P(B|A_k) P(A_k)}{\sum_{l=1}^k P(B|A_l) P(A_l)}$ The probability that a value $X=x...
class LDAModel_1D(object): """ Linear Discriminant Analysis with one predictor. Parameters ---------- X_bound : list Boundary points between categories in ``K_ordered``. K_ordered : list Categories, ordered by mean. """ def __init__(self, mu, sigma, K_labels): ...
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
Iris Example
iris = pd.read_csv('data/iris.csv') iris_training = pd.concat([iris[iris.Species == 'setosa'].sample(25, random_state=8675309), iris[iris.Species == 'versicolor'].sample(25, random_state=8675309), iris[iris.Species == 'virginica'].sample(25, random_state=8675309)])...
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
$P(Y=k|X=x) \propto \frac{-(x-\mu_k)^2}{2\sigma_k^2} - log(\sigma_k\sqrt{2\pi})$ $-\sum_{x \in X} \frac{-(x-\mu_k)^2}{2\sigma_k^2} - log(\sigma_k\sqrt{2\pi})$ $\bigg|\bigg(\frac{-(x-\mu_k)^2}{2\sigma_k^2} - log(\sigma_k\sqrt{2\pi})\bigg) - \bigg(\frac{-(x-\mu_{k'})^2} {2\sigma_{k'}^2} - log(\sigma_{k'}\sqrt{2\pi})\bigg...
qpredictions = np.array([qmodel.predict(x) for x in iris_test['Sepal.Length']]) plt.figure(figsize=(15, 5)) X_ = np.linspace(0, 20, 200) iris_training.groupby('Species')['Sepal.Length'].hist() # iris_test.groupby('Species')['Sepal.Length'].hist() ax = plt.gca() ax2 = ax.twinx() for k in qmodel.K_labels: i = qmode...
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
The default approach was to predict 'Cheat' when $P(Cheater\big|X) > 0.5$.
# Histogram of hemocrit values for cheaters and non-cheaters. Hemocrit[Hemocrit.status == 'Cheat'].hemocrit.hist(histtype='step') Hemocrit[Hemocrit.status == 'Clean'].hemocrit.hist(histtype='step') plt.ylim(0, 40) plt.ylabel('N') # Probability of being a cheater (or not) as a function of hemocrit. ax = plt.gca() ax2 =...
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
Confusion matrix:
predictions = [model.predict(h) for h in Hemocrit.hemocrit] truth = Hemocrit.status.values confusion = pd.DataFrame(np.array([predictions, truth]).T, columns=('Prediction', 'Truth')) confusion.groupby('Prediction').Truth.value_counts()
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
Trying the same thing, but with QDA:
qmodel = qda(Hemocrit.status, Hemocrit.hemocrit) qpredictions = np.array([qmodel.predict(h) for h in Hemocrit.hemocrit]) truth = Hemocrit.status.values qconfusion = pd.DataFrame(np.array([qpredictions, truth]).T, columns=('Prediction', 'Truth'))
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
Receiver Operator Characteristic (ROC) curve Provides a visual summary of the confusion matrix over a range of criteria. Given a confusion matrix, $N=TN+FP$, $P=TP+FN$.
plt.figure(figsize=(5, 5)) plt.text(0.25, 0.75, 'TN', size=18) plt.text(0.75, 0.75, 'FP', size=18) plt.text(0.25, 0.25, 'FN', size=18) plt.text(0.75, 0.25, 'TN', size=18) plt.xticks([0.25, 0.75], ['Neg', 'Pos'], size=20) plt.yticks([0.25, 0.75], ['Pos', 'Neg'], size=20) plt.ylabel('Truth', size=24) plt.xlabel('Predict...
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
The true positive rate, or Power (or Sensitivity) is $\frac{TP}{P}$ and the Type 1 error is $\frac{FP}{N}$. The ROC curve shows Power vs. Type 1 error. Ideally, we can achieve a high true positive rate at a very low false positive rate:
plt.figure() X = np.linspace(0., 0.5, 200) f = lambda x: 0.001 if x < 0.01 else 0.8 plt.plot(X, map(f, X)) plt.ylabel('True positive rate (power)') plt.xlabel('False positive rate (type 1 error)') plt.show()
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
With the hemocrit example:
ROC = [] C = [] for p in np.arange(0.5, 1.0, 0.005): criterion = lambda posterior: 0 if posterior[0] > p else 1 predictions = [model.predict(h, criterion) for h in Hemocrit.hemocrit] truth = Hemocrit.status.values confusion = pd.DataFrame(np.array([predictions, truth]).T, columns=('Prediction', 'Truth')...
.ipynb_checkpoints/Linear and Quadratic Discriminant Analysis-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
Important Note: As you can see, we import Keras's backend as K. This means that to use a Keras function in this notebook, you will need to write: K.function(...). 1 - Problem Statement You are working on a self-driving car. As a critical component of this project, you'd like to first build a car detection system. To co...
# GRADED FUNCTION: yolo_filter_boxes def yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = .6): """Filters YOLO boxes by thresholding on object and class confidence. Arguments: box_confidence -- tensor of shape (19, 19, 5, 1) boxes -- tensor of shape (19, 19, 5, 4) box_clas...
course-deeplearning.ai/course4-cnn/week3-car-detection/Autonomous+driving+application+-+Car+detection+-+v1.ipynb
liufuyang/deep_learning_tutorial
mit
Expected Output: <table> <tr> <td> **scores[2]** </td> <td> 10.7506 </td> </tr> <tr> <td> **boxes[2]** </td> <td> [ 8.42653275 3.27136683 -0.5313437 -4.94137383] </td> </tr> <tr> ...
# GRADED FUNCTION: iou def iou(box1, box2): """Implement the intersection over union (IoU) between box1 and box2 Arguments: box1 -- first box, list object with coordinates (x1, y1, x2, y2) box2 -- second box, list object with coordinates (x1, y1, x2, y2) """ # Calculate the (y1, x1, y2, x...
course-deeplearning.ai/course4-cnn/week3-car-detection/Autonomous+driving+application+-+Car+detection+-+v1.ipynb
liufuyang/deep_learning_tutorial
mit
Expected Output: <table> <tr> <td> **iou = ** </td> <td> 0.14285714285714285 </td> </tr> </table> You are now ready to implement non-max suppression. The key steps are: 1. Select the box that has the highest score. 2. Compute its overlap with all other b...
# GRADED FUNCTION: yolo_non_max_suppression def yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5): """ Applies Non-max suppression (NMS) to set of boxes Arguments: scores -- tensor of shape (None,), output of yolo_filter_boxes() boxes -- tensor of shape (Non...
course-deeplearning.ai/course4-cnn/week3-car-detection/Autonomous+driving+application+-+Car+detection+-+v1.ipynb
liufuyang/deep_learning_tutorial
mit
Expected Output: <table> <tr> <td> **scores[2]** </td> <td> 6.9384 </td> </tr> <tr> <td> **boxes[2]** </td> <td> [-5.299932 3.13798141 4.45036697 0.95942086] </td> </tr> <tr> <...
# GRADED FUNCTION: yolo_eval def yolo_eval(yolo_outputs, image_shape = (720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5): """ Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes. Arguments: yolo_outputs...
course-deeplearning.ai/course4-cnn/week3-car-detection/Autonomous+driving+application+-+Car+detection+-+v1.ipynb
liufuyang/deep_learning_tutorial
mit
Import Data
continuous_distributions = "C:\\Users\\jdorvinen\\Documents\\ipynbs\\Hoboken\\continuous_distributions_.csv" dists_unindexed = pd.read_csv(continuous_distributions) dist_list = dists_unindexed.distribution.tolist() dists = dists_unindexed.set_index(dists_unindexed.distribution) file_name = 'montauk_combined_data.csv' ...
.ipynb_checkpoints/Distribution_Fit_MC-checkpoint.ipynb
jdorvi/MonteCarlos_SLC
mit
###References: Python <br> http://stackoverflow.com/questions/6615489/fitting-distributions-goodness-of-fit-p-value-is-it-possible-to-do-this-with/16651524#16651524 <br> http://stackoverflow.com/questions/6620471/fitting-empirical-distribution-to-theoretical-ones-with-scipy-python <br><br> Extreme wave stat...
dist = getattr(scipy.stats, 'genextreme') #param = dist.fit(y1)
.ipynb_checkpoints/Distribution_Fit_MC-checkpoint.ipynb
jdorvi/MonteCarlos_SLC
mit
The resulting model looks like half a parabola. Try on your own to see what the cubic looks like:
poly3_data = polynomial_sframe(sales['sqft_living'], 3) my_features3 = poly3_data.column_names() poly3_data['price'] = sales['price'] model3 = graphlab.linear_regression.create(poly3_data, target = 'price', features = my_features3, validation_set = None) plt.plot(poly3_data['power_1'],poly3_data['price'],'.', ...
Course 2 - ML, Regression/week-3-polynomial-regression-assignment-blank.ipynb
dennys-bd/Coursera-Machine-Learning-Specialization
mit