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
6. Prepare Random Forest classification model[Top](top) We instantiate a decision-tree based classification algorithm, namely, RandomForestClassifier. Next we define a pipeline to chain together the various transformers and estimators defined during the data preparation step before. Scikit-learn provides APIs that mak...
from sklearn.ensemble import RandomForestClassifier model_name = "Random Forest Classifier" randomForestClassifier = RandomForestClassifier(n_estimators=100, max_depth=2,random_state=0)
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
Pipelines are a convenient way of designing your data processing in a machine learning flow. The following code example shows how pipelines are set up using sklearn.Read more [Here](https://scikit-learn.org/stable/modules/classes.html?highlight=pipelinemodule-sklearn.pipeline)
rfc_model = Pipeline(steps=[('preprocessorAll',preprocessorForAllColumns),('classifier', randomForestClassifier)])
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
7. Train Random Forest classification model[Top](top)
# Build models rfc_model.fit(X_train,y_train)
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
8. Test Random Forest classification model[Top](top)
y_pred_rfc = rfc_model.predict(X_test)
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
9. Evaluate Random Forest classification model[Top](top) Model resultsIn a supervised classification problem such as churn risk classification, we have a true output and a model-generated predicted output for each data point. For this reason, the results for each data point can be assigned to one of four categories:1...
two_d_compare(y_test,y_pred_rfc,model_name) #three_d_compare(y_test,y_pred_rfc,model_name)
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
Confusion matrix In the graph below we have printed a confusion matrix and a self-explanotary classification report.The confusion matrix shows that, 42 mediums were wrongly predicted as high, 2 mediums were wrongly predicted as low and 52 mediums were accurately predicted as mediums.
y_test = label_encoder.inverse_transform(y_test) y_pred_rfc = label_encoder.inverse_transform(y_pred_rfc) model_metrics(y_test,y_pred_rfc)
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
[Precision Recall Fscore support](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_fscore_support.html) [Understanding the Confusion Matrix](https://towardsdatascience.com/confusion-matrix-for-your-multi-class-machine-learning-model-ff9aa3bf7826) Comparative studyIn the bar chart belo...
uniqueValues, occurCount = np.unique(y_test, return_counts=True) frequency_actual = (occurCount[0],occurCount[2],occurCount[1]) uniqueValues, occurCount = np.unique(y_pred_rfc, return_counts=True) frequency_predicted_rfc = (occurCount[0],occurCount[2],occurCount[1]) n_groups = 3 fig, ax = plt.subplots(figsize=(10,5))...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
10. Build K-Nearest classification model[Top](top)K number of nearest points around the data point to be predicted are taken into consideration. These K points at this time, already belong to a class. The data point under consideration, is said to belong to the class with which most number of points from these k point...
from sklearn.neighbors import KNeighborsClassifier model_name = "K-Nearest Neighbor Classifier" knnClassifier = KNeighborsClassifier(n_neighbors = 5, metric='minkowski', p=2) knn_model = Pipeline(steps=[('preprocessorAll',preprocessorForAllColumns),('classifier', knnClassifier)]) knn_model.fit(X_train,y_train) y_...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
11. Comparative study of both classification algorithms. [Top](top)
uniqueValues, occurCount = np.unique(y_test, return_counts=True) frequency_actual = (occurCount[0],occurCount[2],occurCount[1]) uniqueValues, occurCount = np.unique(y_pred_rfc, return_counts=True) frequency_predicted_rfc = (occurCount[0],occurCount[2],occurCount[1]) uniqueValues, occurCount = np.unique(y_pred_knn, re...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
Introduction to Python - available from https://gitlab.erc.monash.edu.au/andrease/Python4Maths.gitThe original version was written by Rajath Kumar and is available at https://github.com/rajathkumarmp/Python-Lectures.The notes have been updated for Python 3 and amended for use in Monash University mathematics courses by...
N={1,3,4,5,7,8} print('The sum of ∑_i∈N i*i =',sum( i**2 for i in N ) )
The sum of ∑_i∈N i*i = 164
CC-BY-3.0
Intro-to-Python/00.ipynb
koshikraj/PythonLectures
Overfitting demo Create a dataset based on a true sinusoidal relationshipLet's look at a synthetic dataset consisting of 30 points drawn from the sinusoid $y = \sin(4x)$:
import graphlab import math import random import numpy from matplotlib import pyplot as plt %matplotlib inline
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Create random values for x in interval [0,1)
random.seed(98103) n = 30 x = graphlab.SArray([random.random() for i in range(n)]).sort()
2016-04-25 03:15:49,473 [INFO] graphlab.cython.cy_server, 176: GraphLab Create v1.8.5 started. Logging: C:\Users\PHILIP~1\AppData\Local\Temp\graphlab_server_1461579348.log.0
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Compute y
y = x.apply(lambda x: math.sin(4*x))
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Add random Gaussian noise to y
random.seed(1) e = graphlab.SArray([random.gauss(0,1.0/3.0) for i in range(n)]) y = y + e
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Put data into an SFrame to manipulate later
data = graphlab.SFrame({'X1':x,'Y':y}) data
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Create a function to plot the data, since we'll do it many times
def plot_data(data): plt.plot(data['X1'],data['Y'],'k.') plt.xlabel('x') plt.ylabel('y') plot_data(data)
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Define some useful polynomial regression functions Define a function to create our features for a polynomial regression model of any degree:
def polynomial_features(data, deg): data_copy=data.copy() for i in range(1,deg): data_copy['X'+str(i+1)]=data_copy['X'+str(i)]*data_copy['X1'] return data_copy
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Define a function to fit a polynomial linear regression model of degree "deg" to the data in "data":
def polynomial_regression(data, deg): model = graphlab.linear_regression.create(polynomial_features(data,deg), target='Y', l2_penalty=0.,l1_penalty=0., validation_set=None,verbose=False) return model
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Define function to plot data and predictions made, since we are going to use it many times.
def plot_poly_predictions(data, model): plot_data(data) # Get the degree of the polynomial deg = len(model.coefficients['value'])-1 # Create 200 points in the x axis and compute the predicted value for each point x_pred = graphlab.SFrame({'X1':[i/200.0 for i in range(200)]}) y_pred = model...
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Create a function that prints the polynomial coefficients in a pretty way :)
def print_coefficients(model): # Get the degree of the polynomial deg = len(model.coefficients['value'])-1 # Get learned parameters as a list w = list(model.coefficients['value']) # Numpy has a nifty function to print out polynomials in a pretty way # (We'll use it, but it needs the parame...
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Fit a degree-2 polynomial Fit our degree-2 polynomial to the data generated above:
model = polynomial_regression(data, deg=2)
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Inspect learned parameters
print_coefficients(model)
Learned polynomial for degree 2: 2 -5.129 x + 4.147 x + 0.07471
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Form and plot our predictions along a grid of x values:
plot_poly_predictions(data,model)
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Fit a degree-4 polynomial
model = polynomial_regression(data, deg=4) print_coefficients(model) plot_poly_predictions(data,model)
Learned polynomial for degree 4: 4 3 2 23.87 x - 53.82 x + 35.23 x - 6.828 x + 0.7755
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Fit a degree-16 polynomial
model = polynomial_regression(data, deg=16) print_coefficients(model)
Learned polynomial for degree 16: 16 15 14 13 -4.537e+05 x + 1.129e+06 x + 4.821e+05 x - 3.81e+06 x 12 11 10 9 + 3.536e+06 x + 5.753e+04 x - 1.796e+06 x + 2.178e+06 x 8 7 6 ...
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Woah!!!! Those coefficients are *crazy*! On the order of 10^6.
plot_poly_predictions(data,model)
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Above: Fit looks pretty wild, too. Here's a clear example of how overfitting is associated with very large magnitude estimated coefficients. Ridge Regression Ridge regression aims to avoid overfitting by adding a cost to the RSS term of standard least squares that depends on the 2-norm of the coefficients ...
def polynomial_ridge_regression(data, deg, l2_penalty): model = graphlab.linear_regression.create(polynomial_features(data,deg), target='Y', l2_penalty=l2_penalty, validation_set=None,verbose=False) return model
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Perform a ridge fit of a degree-16 polynomial using a *very* small penalty strength
model = polynomial_ridge_regression(data, deg=16, l2_penalty=1e-25) print_coefficients(model) plot_poly_predictions(data,model)
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Perform a ridge fit of a degree-16 polynomial using a very large penalty strength
model = polynomial_ridge_regression(data, deg=16, l2_penalty=100) print_coefficients(model) plot_poly_predictions(data,model)
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Let's look at fits for a sequence of increasing lambda values
for l2_penalty in [1e-25, 1e-10, 1e-6, 1e-3, 1e2]: model = polynomial_ridge_regression(data, deg=16, l2_penalty=l2_penalty) print 'lambda = %.2e' % l2_penalty print_coefficients(model) print '\n' plt.figure() plot_poly_predictions(data,model) plt.title('Ridge, lambda = %.2e' % l2_penalty) da...
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Perform a ridge fit of a degree-16 polynomial using a "good" penalty strength We will learn about cross validation later in this course as a way to select a good value of the tuning parameter (penalty strength) lambda. Here, we consider "leave one out" (LOO) cross validation, which one can show approximates average m...
# LOO cross validation -- return the average MSE def loo(data, deg, l2_penalty_values): # Create polynomial features data = polynomial_features(data, deg) # Create as many folds for cross validatation as number of data points num_folds = len(data) folds = graphlab.cross_validation.KFold(data,nu...
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Run LOO cross validation for "num" values of lambda, on a log scale
l2_penalty_values = numpy.logspace(-4, 10, num=10) l2_penalty_mse,best_l2_penalty = loo(data, 16, l2_penalty_values)
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Plot results of estimating LOO for each value of lambda
plt.plot(l2_penalty_values,l2_penalty_mse,'k-') plt.xlabel('$\ell_2$ penalty') plt.ylabel('LOO cross validation error') plt.xscale('log') plt.yscale('log')
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Find the value of lambda, $\lambda_{\mathrm{CV}}$, that minimizes the LOO cross validation error, and plot resulting fit
best_l2_penalty model = polynomial_ridge_regression(data, deg=16, l2_penalty=best_l2_penalty) print_coefficients(model) plot_poly_predictions(data,model)
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Lasso Regression Lasso regression jointly shrinks coefficients to avoid overfitting, and implicitly performs feature selection by setting some coefficients exactly to 0 for sufficiently large penalty strength lambda (here called "L1_penalty"). In particular, lasso takes the RSS term of standard least squares ...
def polynomial_lasso_regression(data, deg, l1_penalty): model = graphlab.linear_regression.create(polynomial_features(data,deg), target='Y', l2_penalty=0., l1_penalty=l1_penalty, ...
_____no_output_____
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Explore the lasso solution as a function of a few different penalty strengths We refer to lambda in the lasso case below as "l1_penalty"
for l1_penalty in [0.0001, 0.01, 0.1, 10]: model = polynomial_lasso_regression(data, deg=16, l1_penalty=l1_penalty) print 'l1_penalty = %e' % l1_penalty print 'number of nonzeros = %d' % (model.coefficients['value']).nnz() print_coefficients(model) print '\n' plt.figure() plot_poly_predictio...
l1_penalty = 1.000000e-04 number of nonzeros = 17 Learned polynomial for degree 16: 16 15 14 13 12 11 29.02 x + 1.35 x - 12.72 x - 16.93 x - 13.82 x - 6.698 x 10 9 8 7 6 5 + 1.407 x + 8.939 x + 12.88 x + 11.44 x + 3....
Apache-2.0
Course2week5-Lasso/Overfitting_Demo_Ridge_Lasso.ipynb
bluove/Machine-Learning-Specialization
Gridworld ![gridworld](../pictures/gridworld.png)The Gridworld environment (inspired from Sutton and Barto, Reinforcement Learning: an Introduction) is represented in figure. The environment is a finite MDP in which states are represented by grid cells. The available actions are 4: left, right, up, down. Actions move ...
from enum import Enum, auto import matplotlib.pyplot as plt import numpy as np from scipy import linalg from typing import Tuple
_____no_output_____
MIT
Chapter02/Activity02_01/Activity02_01.ipynb
adityashah95/The-Reinforcement-Learning-Workshop
Visualization function:
# helper function def vis_matrix(M, cmap=plt.cm.Blues): fig, ax = plt.subplots() ax.matshow(M, cmap=cmap) for i in range(M.shape[0]): for j in range(M.shape[1]): c = M[j, i] ax.text(i, j, "%.2f" % c, va="center", ha="center") # Define the actions class Action(Enum): UP = ...
_____no_output_____
MIT
Chapter02/Activity02_01/Activity02_01.ipynb
adityashah95/The-Reinforcement-Learning-Workshop
Probability and reward matrix:
pi = Policy() env = Environment() # setup probability matrix and reward matrix P = np.zeros((env.grid_width * env.grid_height, env.grid_width * env.grid_height)) R = np.zeros_like(P) possible_actions = [action for action in Action] # Loop for all states and fill up P and R for i in range(env.grid_height): for j i...
_____no_output_____
MIT
Chapter02/Activity02_01/Activity02_01.ipynb
adityashah95/The-Reinforcement-Learning-Workshop
The previous figure is a color representation of the expected reward associated to each state considering the current policy. Notice the expected reward of bad states is exactly equal to -1. The expected reward of good states is exactly equal to 10 and 5 respectively.
# define the discount factor gamma = 0.9 # Now it is possible to solve the Bellman Equation A = np.eye(env.grid_width*env.grid_height) - gamma * P B = R_expected # solve using scipy linalg V = linalg.solve(A, B) # reshape the state values in a matrix V_square = V.reshape((env.grid_height,env.grid_width)) # visualize re...
_____no_output_____
MIT
Chapter02/Activity02_01/Activity02_01.ipynb
adityashah95/The-Reinforcement-Learning-Workshop
evaluation episodeのrewardsの結果を見るnotebook
# import csv # def text_csv_converter(datas): # file_csv = datas.replace("txt", "csv") # with open(datas) as rf: # with open(file_csv, "w") as wf: # readfile = rf.readlines() # for read_text in readfile: # read_text = read_text.split() # writer = c...
_____no_output_____
MIT
notebook/reward_result.ipynb
kuto5046/kaggle-football
Lambda School Data Science Module 142 Sampling, Confidence Intervals, and Hypothesis Testing Prepare - examine other available hypothesis testsIf you had to pick a single hypothesis test in your toolbox, t-test would probably be the best choice - but the good news is you don't have to pick just one! Here's some of t...
import numpy as np from scipy.stats import chisquare # One-way chi square test # Chi square can take any crosstab/table and test the independence of rows/cols # The null hypothesis is that the rows/cols are independent -> low chi square # The alternative is that there is a dependence -> high chi square # Be aware! Ch...
KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895) KruskalResult(statistic=7.0, pvalue=0.0301973834223185)
MIT
Copy_of_LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
zevan07/DS-Unit-1-Sprint-3-Statistical-Tests-and-Experiments
And there's many more! `scipy.stats` is fairly comprehensive, though there are even more available if you delve into the extended world of statistics packages. As tests get increasingly obscure and specialized, the importance of knowing them by heart becomes small - but being able to look them up and figure them out wh...
# Taking requests! Come to lecture with a topic or problem and we'll try it.
_____no_output_____
MIT
Copy_of_LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
zevan07/DS-Unit-1-Sprint-3-Statistical-Tests-and-Experiments
Assignment - Build a confidence intervalA confidence interval refers to a neighborhood around some point estimate, the size of which is determined by the desired p-value. For instance, we might say that 52% of Americans prefer tacos to burritos, with a 95% confidence interval of +/- 5%.52% (0.52) is the point estimate...
import pandas as pd import numpy as np from scipy import stats from scipy.stats import normaltest from scipy.stats import kruskal from random import randint import matplotlib.pyplot as plt from matplotlib.pyplot import figure # the data file does not have a header so we'll need to create one # attribute info copy and p...
_____no_output_____
MIT
Copy_of_LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
zevan07/DS-Unit-1-Sprint-3-Statistical-Tests-and-Experiments
InterpretationMost of the confidence intervals are pretty large. If you were trying to extrapolate this data to a population (sort of a nonsensical situation, because congress is the population), you might find a value much different from what you predicted. Using the handicapped infants bill as an example, the predi...
print(dem_means[0]) print(dem_er[0])
0.6179775280898876 0.117313652657326
MIT
Copy_of_LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
zevan07/DS-Unit-1-Sprint-3-Statistical-Tests-and-Experiments
Fitting distribution with R
x.norm <- rnorm(n=200,m=10,sd=2) hist(x.norm,main="Histogram of observed data") plot(density(x.norm),main="Density estimate of data") plot(ecdf(x.norm),main="Empirical cumulative distribution function") z.norm <- (x.norm-mean(x.norm))/sd(x.norm) # standardize data qqnorm(z.norm) ## drawing the QQplot abline(0,1) ## dra...
_____no_output_____
Unlicense
Applied Math/Y2S2/.ipynb_checkpoints/R Test-checkpoint.ipynb
darkeclipz/jupyter-notebooks
If data differ from a normal distribution (i.e. data belonging from a Weibull pdf) we cna use `qqplot()` in this way:
x.wei <- rweibull(n=200,shape=2.1,scale=1.1) ## sampling from a Weibull x.teo <- rweibull(n=200,shape=2,scale=1) ## theoretical quantiles from a Weibull population qqplot(x.teo,x.wei,main="QQ-plot distr. Weibull") abline(0,1)
_____no_output_____
Unlicense
Applied Math/Y2S2/.ipynb_checkpoints/R Test-checkpoint.ipynb
darkeclipz/jupyter-notebooks
Model choice Dealing with discrete data we can refer to Poisson's distribution with probability mass function:$$ f(x,\lambda)=e^{-\lambda\dfrac{\lambda^x}{x!}} \quad \text{where } x=0,1,2,\ldots$$
x.poi <- rpois(n=200, lambda=2.5) hist(x.poi, main="Poisson distribution")
_____no_output_____
Unlicense
Applied Math/Y2S2/.ipynb_checkpoints/R Test-checkpoint.ipynb
darkeclipz/jupyter-notebooks
As concern continuous data we have the normal (gaussian) dsitrubition:$$ f(x,\lambda,\sigma)=\dfrac{1}{\sqrt{2\pi}\sigma} e^{\dfrac{1(x-\mu)^2}{2\sigma^2}} $$with $x \in \mathbb{R}$.
curve(dnorm(x,m=10,sd=2),from=0,to=20,main="Normal distribution")
_____no_output_____
Unlicense
Applied Math/Y2S2/.ipynb_checkpoints/R Test-checkpoint.ipynb
darkeclipz/jupyter-notebooks
Gamma distribution:$$ f(x,\alpha,\lambda)=\dfrac{\lambda^\alpha}{\gamma(\alpha)}x^{\alpha-1}e^{-\lambda x} $$with $x \in \mathbb{R}^+$.
curve(dgamma(x, scale=1.5, shape=2), from=0, to=15, main="Gamma distribution")
_____no_output_____
Unlicense
Applied Math/Y2S2/.ipynb_checkpoints/R Test-checkpoint.ipynb
darkeclipz/jupyter-notebooks
Weibull distribition:$$ f(x,\alpha,\beta)=\alpha\beta^{-\alpha}x^{\alpha-1}e^{-\left[\left(\dfrac{x}{\beta}\right)^\alpha\right]} $$
curve(dweibull(x, scale=2.5, shape=1.5), from=0, to=15, main="Weibull distribution") h<-hist(x.norm,breaks=15) xhist<-c(min(h$breaks),h$breaks) yhist<-c(0,h$density,0) xfit<-seq(min(x.norm),max(x.norm),length=40) yfit<-dnorm(xfit,mean=mean(x.norm),sd=sd(x.norm)) plot(xhist,yhist,type="s",ylim=c(0,max(yhist,yfit)), main...
Warning message in ks.test(yfit, yhist): "cannot compute exact p-value with ties"
Unlicense
Applied Math/Y2S2/.ipynb_checkpoints/R Test-checkpoint.ipynb
darkeclipz/jupyter-notebooks
StackOverflow example The following is from this StackOverflow example: https://stats.stackexchange.com/questions/132652/how-to-determine-which-distribution-fits-my-data-bestThis requires you to install the following packages with the R package manager: `fitdistrplus` and `logspline`.
library(fitdistrplus) library(logspline) x <- c(37.50,46.79,48.30,46.04,43.40,39.25,38.49,49.51,40.38,36.98,40.00, 38.49,37.74,47.92,44.53,44.91,44.91,40.00,41.51,47.92,36.98,43.40, 42.26,41.89,38.87,43.02,39.25,40.38,42.64,36.98,44.15,44.91,43.40, 49.81,38.87,40.00,52.45,53.13,47.92,52.45,44.91,29.54,27.13,35.60, 45....
_____no_output_____
Unlicense
Applied Math/Y2S2/.ipynb_checkpoints/R Test-checkpoint.ipynb
darkeclipz/jupyter-notebooks
Kolmogorov-Smirnov test simulation
n.sims <- 5e4 stats <- replicate(n.sims, { r <- rweibull(n = length(x) , shape= fit.weibull$estimate["shape"] , scale = fit.weibull$estimate["scale"] ) as.numeric(ks.test(r , "pweibull" , shape= fit.weibull$estimate["shape"] ...
_____no_output_____
Unlicense
Applied Math/Y2S2/.ipynb_checkpoints/R Test-checkpoint.ipynb
darkeclipz/jupyter-notebooks
checking basic integrity
data.shape data.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 6398 entries, 0 to 6397 Data columns (total 19 columns): track 6398 non-null object artist 6398 non-null object uri 6398 non-null object danceability 6398 non-null float64 energy 6398 non-null float64 key ...
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
no. of rows = non null values for each column -> no null value
data.head()
_____no_output_____
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
checking unique records using uri
# extracting exact id def extract(x): splited_list = x.split(':') # spliting text at colons return splited_list[2] # returning third element data['uri'] = data['uri'].apply(extract) data.head() #successfully extracted the id
_____no_output_____
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
checking for duplicate rows
data['uri'].nunique(), data['uri'].value_counts() data['uri'].value_counts().unique() dupe_mask = data['uri'].value_counts()==2 dupe_ids = dupe_mask[dupe_mask] dupe_ids.value_counts, dupe_ids.shape #converting duplicate ids into a list dupe_ids = dupe_ids.index dupe_ids = dupe_ids.tolist() dupe_ids duplicate_in...
_____no_output_____
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
We will be removing all the duplication as they are few compared to data
data.drop(duplicate_index,axis=0,inplace=True) data.shape data.info() print("shape of data",data.shape ) print("no. of unique rows",data['uri'].nunique()) # no duplicates data.head()
_____no_output_____
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
now we will be dropping all the unnecessary columns which contain string which cant be eficiently converted into numerics
data.drop(['track','artist','uri'],axis=1,inplace=True) data.head()
_____no_output_____
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
Univariate analysis
#analysing class imbalance sns.countplot(data=data,x='target') data.columns # checking appropriate data type data[['danceability', 'energy', 'key', 'loudness']].info() # every feature have appropriate datatype # checking range of first 4 features data[['danceability', 'energy', 'key', 'loudness']].describe() plt.fig...
_____no_output_____
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
danceabilty is well inside the range(0,1) energy is well inside the range(0,1) there's no -1 for keys-> every track has been assigned respective keys loudness values are out of range(0,-60)db
loudness_error_idnex = data[data['loudness']>0].index loudness_error_idnex # removing rows with out of range values in loudness column data.drop(loudness_error_idnex,axis=0, inplace=True) data.shape # record is removed # checking appropriate datatype for next 5 columns data[['mode', 'speechiness', 'acousticne...
_____no_output_____
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
Performing F-test to know the relation between every feature and target
data.head() x = data.iloc[:,:-1].values y = data.iloc[:,-1].values x.shape,y.shape from sklearn.feature_selection import f_classif f_stat,p_value = f_classif(x,y) feat_list = data.iloc[:,:-1].columns.tolist() # making a dataframe dict = {'Features':feat_list,'f_statistics':f_stat,'p_value':p_value} relation = pd.DataF...
_____no_output_____
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
Multivariate analysis
correlation = data.corr() plt.figure(figsize=(15,12)) sns.heatmap(correlation, annot=True) plt.tight_layout
_____no_output_____
MIT
EDA-dataset10.ipynb
Rahulraj31/Spotify-Hit-Flop-Predictor-1960-2019
Python Language Basics, IPython, and Jupyter Notebooks
import numpy as np np.random.seed(12345) np.set_printoptions(precision=4, suppress=True)
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
The Python Interpreter ```python$ pythonPython 3.6.0 | packaged by conda-forge | (default, Jan 13 2017, 23:17:12)[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)] on linuxType "help", "copyright", "credits" or "license" for more information.>>> a = 5>>> print(a)5``` ```pythonprint('Hello world')``` ```python$ python hello_world...
import numpy as np data = {i : np.random.randn() for i in range(7)} data
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
>>> from numpy.random import randn>>> data = {i : randn() for i in range(7)}>>> print(data){0: -1.5948255432744511, 1: 0.10569006472787983, 2: 1.972367135977295,3: 0.15455217573074576, 4: -0.24058577449429575, 5: -1.2904897053651216,6: 0.3308507317325902} Running the Jupyter Notebook ```shell$ jupyter notebook[I 15:20...
a = [1, 2, 3] b = a a.append(4) b
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
```pythondef append_element(some_list, element): some_list.append(element)``` ```pythonIn [27]: data = [1, 2, 3]In [28]: append_element(data, 4)In [29]: dataOut[29]: [1, 2, 3, 4]``` Dynamic references, strong types
a = 5 type(a) a = 'foo' type(a) '5' + 5 a = 4.5 b = 2 # String formatting, to be visited later print('a is {0}, b is {1}'.format(type(a), type(b))) a / b a = 5 isinstance(a, int) a = 5; b = 4.5 isinstance(a, (int, float)) isinstance(b, (int, float))
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Attributes and methods ```pythonIn [1]: a = 'foo'In [2]: a.a.capitalize a.format a.isupper a.rindex a.stripa.center a.index a.join a.rjust a.swapcasea.count a.isalnum a.ljust a.rpartition a.titlea.decode a.isalpha a.lower a.rsplit a.translatea...
a = 'foo' getattr(a, 'split')
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Duck typing
def isiterable(obj): try: iter(obj) return True except TypeError: # not iterable return False isiterable('a string') isiterable([1, 2, 3]) isiterable(5)
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
if not isinstance(x, list) and isiterable(x): x = list(x) Imports ```python some_module.pyPI = 3.14159def f(x): return x + 2def g(a, b): return a + b``` import some_moduleresult = some_module.f(5)pi = some_module.PI from some_module import f, g, PIresult = g(5, PI) import some_module as smfrom some_module imp...
5 - 7 12 + 21.5 5 <= 2 a = [1, 2, 3] b = a c = list(a) a is b a is not c a == c a = None a is None
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Mutable and immutable objects
a_list = ['foo', 2, [4, 5]] a_list[2] = (3, 4) a_list a_tuple = (3, 5, (4, 5)) a_tuple[1] = 'four'
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Scalar Types Numeric types
ival = 17239871 ival ** 6 fval = 7.243 fval2 = 6.78e-5 3 / 2 3 // 2
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Strings a = 'one way of writing a string'b = "another way"
c = """ This is a longer string that spans multiple lines """ c.count('\n') a = 'this is a string' a[10] = 'f' b = a.replace('string', 'longer string') b a a = 5.6 s = str(a) print(s) s = 'python' list(s) s[:3] s = '12\\34' print(s) s = r'this\has\no\special\characters' s a = 'this is the first half ' b = 'and this is ...
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Bytes and Unicode
val = "español" val val_utf8 = val.encode('utf-8') val_utf8 type(val_utf8) val_utf8.decode('utf-8') val.encode('latin1') val.encode('utf-16') val.encode('utf-16le') bytes_val = b'this is bytes' bytes_val decoded = bytes_val.decode('utf8') decoded # this is str (Unicode) now
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Booleans
True and True False or True
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Type casting
s = '3.14159' fval = float(s) type(fval) int(fval) bool(fval) bool(0)
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
None
a = None a is None b = 5 b is not None
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
def add_and_maybe_multiply(a, b, c=None): result = a + b if c is not None: result = result * c return result
type(None)
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Dates and times
from datetime import datetime, date, time dt = datetime(2011, 10, 29, 20, 30, 21) dt.day dt.minute dt.date() dt.time() dt.strftime('%m/%d/%Y %H:%M') datetime.strptime('20091031', '%Y%m%d') dt.replace(minute=0, second=0) dt2 = datetime(2011, 11, 15, 22, 30) delta = dt2 - dt delta type(delta) dt dt + delta
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Control Flow if, elif, and else if x < 0: print('It's negative') if x < 0: print('It's negative')elif x == 0: print('Equal to zero')elif 0 < x < 5: print('Positive but smaller than 5')else: print('Positive and larger than or equal to 5')
a = 5; b = 7 c = 8; d = 4 if a < b or c > d: print('Made it') 4 > 3 > 2 > 1
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
for loops for value in collection: do something with value sequence = [1, 2, None, 4, None, 5]total = 0for value in sequence: if value is None: continue total += value sequence = [1, 2, 0, 4, 6, 5, 2, 1]total_until_5 = 0for value in sequence: if value == 5: break total_until_5 += value
for i in range(4): for j in range(4): if j > i: break print((i, j))
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
for a, b, c in iterator: do something while loops x = 256total = 0while x > 0: if total > 500: break total += x x = x // 2 pass if x < 0: print('negative!')elif x == 0: TODO: put something smart here passelse: print('positive!') range
range(10) list(range(10)) list(range(0, 20, 2)) list(range(5, 0, -1))
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
seq = [1, 2, 3, 4]for i in range(len(seq)): val = seq[i] sum = 0for i in range(100000): % is the modulo operator if i % 3 == 0 or i % 5 == 0: sum += i Ternary expressions value = if
x = 5 'Non-negative' if x >= 0 else 'Negative'
_____no_output_____
MIT
ch02.ipynb
RusWhang/pydata-book
Plots to check channels etc- took from old checkbathy and plotgrids files
import scipy.io as sio from IPython.core.display import display, HTML display(HTML("<style>.container { width:90% !important; }</style>")) from helpers import expandf, grid_angle # grid def load1(f): with nc.Dataset(f) as ncid: glamt = ncid.variables["glamt"][0, :, :].filled() gphit = ncid.variabl...
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...
MIT
code/.ipynb_checkpoints/Bathymetry and Coord Grid Generator (Py3)-checkpoint.ipynb
goldford/NEMO-Salish-Sea-2021
PART 3 - Metadata Knowledge Graph creation in Amazon Neptune.Amazon Neptune is a fast, reliable, fully managed graph database service that makes it easy to build and run applications that work with highly connected datasets. The core of Neptune is a purpose-built, high-performance graph database engine. This engine is...
!pip install --upgrade tornado==4.5.3
Looking in indexes: https://pypi.org/simple, https://pip.repos.neuron.amazonaws.com Requirement already satisfied: tornado==4.5.3 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (4.5.3)
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Restart your kernelBecause the notebook itself has some dependencies with the tornado library, we need to restart the kernel before proceeding.To do so, go to the top menu > Kernel > Restart Kernel.. > RestartThen proceed and execute the following cells.
!pip install pandas !pip install jsonlines !pip install gremlinpython !pip install networkx !pip install matplotlib import os import jsonlines import networkx as nx import matplotlib.pyplot as plt import pandas as pd #load stored variable from previous notebooks %store -r
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Loading the Gremlin libraries and connecting to our Neptune instance
from gremlin_python import statics from gremlin_python.process.anonymous_traversal import traversal from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.process.traversa...
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
IMPORTANT:- Note that the remote connection will time out after few minutes if unused so if you're encountering exceptions after having paused the notebook execution for a while, please re-run the above cell.- Make sure your Neptune DB is created for the sole purpose of this labs as we'll be cleaning it before starting...
#CAREFUL - the below line of code empties your graph. Again, make sure you're using a dedicated instance for this workshop g.V().drop().iterate()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
A note on GremlinGremlin is a functional, data-flow language that enables users to succinctly express complex traversals on (or queries of) their application's property graph. Every Gremlin traversal is composed of a sequence of (potentially nested) steps. A step performs an atomic operation on the data stream. Every ...
#Vertex representing a Video V_VIDEO = "video" #Vertex representing a "scene" e.g. SHOT, TECHNICAL_CUE V_VIDEO_SCENE = "video_scene" #Vertex representing a Video segment. we arbitrary split our video into 1min segments and attach metadata to the segments itselves V_VIDEO_SEGMENT = 'video_segment' #Edge between VIDE...
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
We start by adding our video to the GraphNote how I start with g, our traversal graph, then call the addV (V for Vertex) method and then attach properties to the new vertex. I end the line with ".next()" which will return the newly created node (similar to how an iterator would work). all method are "chained" together...
sample_video_vertex = g.addV(V_VIDEO).property("name", video_name).property("filename", video_file) .property('description', 'description of the video').next()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] We're listing all the vertices in the graph with their metadata. At this stage, we only have one.Explanation: g.V() gets us all vertices in the graph, the .hasLabel() filters the vertices based on the vertex label(=type), the .valueMap() returns all properties for all vertices and the .toList() returns the full...
g.V().hasLabel(V_VIDEO).valueMap().toList()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] Below is a different way to precisely return a vertex based on its name. Explanation: g.V() gives us all the vertices, .has() allows us to filter based on the name of the vertex and .next() returns the first (and only) item from the iterator. note that we haven't used .valueMap() so what is returned is the ID o...
g.V().has('name', video_name).next()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Creating 1min segments vertices in Neptune As mentioned in the previous notebook, we are creating metadata segments that we'll use to store labels and other information related to those 1min video segments. This will give us a more fine grained view of the video's topics and metadata.
print(segment_size_ms) #get the video duration by looking at the end of the last segment. def get_video_duration_in_ms(segment_detection_output): return segment_detection_output['Segments'][-1]['EndTimestampMillis'] #create a new segment vertex and connect it to the video def add_segment_vertex(video_name, start, ...
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Note: remember, the SegmentDetectionOutput object contains the output of the Amazon Rekognition segment (=scene) detection job
duration = get_video_duration_in_ms(SegmentDetectionOutput) generate_segment_vertices(video_name, g, duration, segment_size_ms)
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] Let's retrieve the segments that are connected to the video vertex via an edge, ordered by StartTimestampMillis. In that case we limit the result set to 5 items.Explanation: g.V() get us all vertices, .has(V_VIDEO, 'name', video_name) filters on the video vertices with name=video_name, .out() gives us all verti...
list_of_segments = g.V().has(V_VIDEO, 'name', video_name).out().hasLabel(V_VIDEO_SEGMENT) \ .order().by('StartTimestampMillis', Order.asc).valueMap().limit(5).toList() list_of_segments
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Graph VisualisationThe networkx library alongside with matplotlib allows us to draw visually the graph.Let's draw our vertex video and the 1min segments we just created.
#Function printing the graph from a start vertex and a list of edges that will be traversed/displayed. def print_graph(start_vertex_label, start_vertex_name, list_edges, displayLabels=True, node_size=2000, node_limit=200): #getting the paths between vertices paths = g.V().has(start_vertex_label, 'name', start_...
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Add the scenes into our graphIn the below steps we're connecting the scenes to the video itself and not the segments as we want to be able to search and list the different types of scenes at the video level. However, note that we're not going to attach any specific metadata at the scene level, only at the segment leve...
def store_video_segment(original_video_name, json_segment_detection_output, orig_video_vertex): shot_counter = 0 tech_cue_counter = 0 for technicalCue in json_segment_detection_output['Segments']: #start frameStartValue = technicalCue['StartTimestampMillis'] / 1000 #end ...
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] We're retrieving the list of edges/branches created between the video and the scenes.Explanation: g.V() returns all vertices, .has(V_VIDEO, 'name', video_name) returns the V_VIDEO vertex with name=video_name, .out(E_HAS_SCENE) returns the list of vertices that are connected to the V_VIDEO vertex by a E_HAS_SCEN...
list_of_edges = g.V().has(V_VIDEO, 'name', video_name).out(E_HAS_SCENE).toList() print(f"the sample video vertex has now {len(list_of_edges)} edges connecting to the scenes vertices")
the sample video vertex has now 133 edges connecting to the scenes vertices
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] Let's search for the technical cues (black and fix screens) at the end of the video.Explanation: g.V() returns all vertices, .has(V_VIDEO, 'name', video_name) returns the V_VIDEO vertex with name=video_name, .out(E_HAS_SCENE) returns the list of vertices that are connected to the V_VIDEO vertex by a E_HAS_SCENE...
g.V().has(V_VIDEO, 'name', video_name).out(E_HAS_SCENE) \ .has('type', 'TECHNICAL_CUE') \ .order().by('EndTimestampMillis', Order.desc) \ .limit(5).valueMap().toList()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Let's print the graph for those newly created SCENE vertices
#please note that we limit the number of nodes being displayed print_graph(V_VIDEO, video_name, [E_HAS_SCENE], node_limit=15)
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop