id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
15,300 | output ( [ ]load csv with pandas another approach to load csv data file is by pandas and pandas read_csv()function this is the very flexible function that returns pandas dataframe which can be used immediately for plotting the following is an example of loading csv data file with the help of itexample herewe will be im... |
15,301 | script- the following is the python script for loading csv data filealong with providing the headers names toousing pandas on pima indians diabetes datasetfrom pandas import read_csv path " :\pima-indians-diabetes csvheadernames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=headernamesp... |
15,302 | machine learning with python understanding data with statistics introduction while working with machine learning projectsusually we ignore two most important parts called mathematics and data it is becausewe know that ml is data driven approach and our ml model will produce only as good or as bad results as the data we... |
15,303 | |
15,304 | we can observe from the above output that first column gives the row number which can be very useful for referencing specific observation checking dimensions of data it is always good practice to know how much datain terms of rows and columnswe are having for our ml project the reasons behind aresuppose if we have too ... |
15,305 | the help of dtypes property we can categorize each attributes data type it can be understood with the help of following python scriptexample from pandas import read_csv path " :\iris csvdata read_csv(pathprint(data dtypesoutput sepal_length float sepal_width float petal_length float petal_width float dtypeobject from t... |
15,306 | set_option('display width' set_option('precision' print(data shapeprint(data describe()output ( preg plas pres skin test mass pedi age class count mean std min max from the above outputwe can observe the statistical summary of the data of pima indian diabetes dataset along with shape of data reviewing class distributio... |
15,307 | dtypeint from the above outputit can be clearly seen that the number of observations with class are almost double than number of observations with class reviewing correlation between attributes the relationship between two variables is called correlation in statisticsthe most common method for calculating correlation i... |
15,308 | pedi - age - - class the matrix in above output gives the correlation between all the pairs of the attribute in dataset reviewing skew of attribute distribution skewness may be defined as the distribution that is assumed to be gaussian but appears distorted or shifted in one direction or anotheror either to the left or... |
15,309 | |
15,310 | machine learning with python understanding data with visualization introduction in the previous we have discussed the importance of data for machine learning algorithms along with some python recipes to understand the data with statistics there is another way called visualizationto understand the data with the help of ... |
15,311 | from the shape of the binwe can easily observe the distribution weather it is gaussianskewed or exponential histograms also help us to see possible outliers example the code shown below is an example of python script creating the histogram of the attributes of pima indian diabetes dataset herewe will be using hist(func... |
15,312 | the above output shows that it created the histogram for each attribute in the dataset from thiswe can observe that perhaps agepedi and test attribute may have exponential distribution while mass and plas have gaussian distribution density plots another quick and easy technique for getting each attributes distribution ... |
15,313 | from the above outputthe difference between density plots and histograms can be easily understood box and whisker plots box and whisker plotsalso called boxplots in shortis another useful technique to review the distribution of each attribute' distribution the following are the characteristics of this techniqueit is un... |
15,314 | output from the above plot of attribute' distributionit can be observed that agetest and skin appear skewed towards smaller values multivariate plotsinteraction among multiple variables another type of visualization is multi-variable or "multivariatevisualization with the help of multivariate visualizationwe can unders... |
15,315 | from matplotlib import pyplot from pandas import read_csv import numpy path " :\pima-indians-diabetes csvnames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=namescorrelations data corr(fig pyplot figure(ax fig add_subplot( cax ax matshow(correlationsvmin=- vmax= fig colorbar(caxticks nu... |
15,316 | from the above output of correlation matrixwe can see that it is symmetrical the bottom left is same as the top right it is also observed that each variable is positively correlated with each other scatter matrix plot scatter plots shows how much one variable is affected by another or the relationship between them with... |
15,317 | output |
15,318 | machine learning with python preparing data introduction machine learning algorithms are completely dependent on data because it is the most crucial aspect that makes model training possible on the other handif we won' be able to make sense out of that databefore feeding it to ml algorithmsa machine will be useless in ... |
15,319 | names ['preg''plas''pres''skin''test''mass''pedi''age''class'dataframe read_csv(pathnames=namesarray dataframe values nowwe can use minmaxscaler class to rescale the data in the range of and data_scaler preprocessing minmaxscaler(feature_range=( , )data_rescaled data_scaler fit_transform(arraywe can also summarize the ... |
15,320 | types of normalization in machine learningthere are two types of normalization preprocessing techniques as followsl normalization it may be defined as the normalization technique that modifies the dataset values in way that in each row the sum of the absolute values will always be up to it is also called least absolute... |
15,321 | normalization it may be defined as the normalization technique that modifies the dataset values in way that in each row the sum of the squares will always be up to it is also called least squares example in this examplewe use normalization technique to normalize the data of pima indians diabetes dataset which we used e... |
15,322 | for exampleif we choose threshold value then the dataset value above it will become and below this will become that is why we can call it binarizing the data or thresholding the data this technique is useful when we have probabilities in our dataset and want to convert them into crisp values we can binarize the data wi... |
15,323 | standardization another useful data preprocessing technique which is basically used to transform the data attributes with gaussian distribution it differs the mean and sd (standard deviationto standard gaussian distribution with mean of and sd of this technique is useful in ml algorithms like linear regressionlogistic ... |
15,324 | [- - - ]data labeling we discussed the importance of good fata for ml algorithms as well as some techniques to pre-process the data before sending it to ml algorithms one more aspect in this regard is data labeling it is also very important to send the data to ml algorithms having proper labeling for examplein case of ... |
15,325 | print("\nencoded values ="encoded_valuesprint("\ndecoded labels ="list(decoded_list)output labels ['green''red''black'encoded values [ encoded values [ decoded labels ['white''black''yellow''green' |
15,326 | machine learning with python -machine datalearning feature selection in the previous we have seen in detail how to preprocess and prepare data for machine learning in this let us understand in detail data feature selection and various aspects involved in it importance of data feature selection the performance of machin... |
15,327 | from sklearn feature_selection import chi path ' :\pima-indians-diabetes csvnames ['preg''plas''pres''skin''test''mass''pedi''age''class'dataframe read_csv(pathnames=namesarray dataframe values nextwe will separate array into input and output componentsx array[:, : array[:, the following lines of code will select the b... |
15,328 | recursive feature elimination as the name suggestsrfe (recursive feature eliminationfeature selection technique removes the attributes recursively and builds the model with remaining attributes we can implement rfe feature selection technique with the help of rfe class of scikit-learn python library example in this exa... |
15,329 | principal component analysis (pcapcagenerally called data reduction techniqueis very useful feature selection technique as it uses linear algebra to transform the dataset into compressed form we can implement pca feature selection technique with the help of pca class of scikit-learn python library we can select number ... |
15,330 | we can observe from the above output that principal components bear little resemblance to the source data feature importance as the name suggestsfeature importance technique is used to choose the importance features it basically uses trained supervised classifier to select features we can implement this feature selecti... |
15,331 | machine learning algorithms classification |
15,332 | classification introduction introduction to classification classification may be defined as the process of predicting class or category from observed values or given data points the categorized output can have the form such as "blackor "whiteor "spamor "no spammathematicallyclassification is the task of approximating m... |
15,333 | import sklearn step importing dataset after importing necessary packagewe need dataset to build classification prediction model we can import it from sklearn dataset or can use other one as per our requirement we are going to use sklearn' breast cancer wisconsin diagnostic database we can import it with the help of fol... |
15,334 | the output of the above command is the names of the features for label benign cancermean texture we can print the features for these labels with the help of following commandprint(features[ ]this will give the following output[ + + + + - - - - - - + - + + - - - - - - + + + + - - - - - - we can print the features for th... |
15,335 | step model evaluation after dividing the data into training and testing we need to build the model we will be using naive bayes algorithm for this purpose the following commands will import the gaussiannb modulefrom sklearn naive_bayes import gaussiannb nowinitialize the model as followsgnb gaussiannb(nextwith the help... |
15,336 | classification evaluation metrics the job is not done even if you have finished implementation of your machine learning application or model we must have to find out how effective our model isthere can be different evaluation metricsbut we must choose it carefully because the choice of metrics influences how the perfor... |
15,337 | from sklearn metrics import confusion_matrix output [ ]accuracy it may be defined as the number of correct predictions made by our ml model we can easily calculate it by confusion matrix with the help of following formulaaccuracy tp tn tp fp fn tn for above built binary classifiertp tn + and tp+fp+fn+tn + + + = henceac... |
15,338 | for above built binary classifiertp and tp+fn + henceprecision / specificity specificityin contrast to recallmay be defined as the number of negatives returned by our ml model we can easily calculate it by confusion matrix with the help of following formulaspecificity tn tn fp for the above built binary classifiertn an... |
15,339 | classification algorithms logistic regression introduction to logistic regression logistic regression is supervised learning classification algorithm used to predict the probability of target variable the nature of target or dependent variable is dichotomouswhich means there would be only two possible classes in simple... |
15,340 | in case of binary logistic regressionthe target variables must be binary always and the desired outcome is represented by the factor level there should not be any multi-collinearity in the modelwhich means independent variables must be independent of each other we must include meaningful variables in our model we shoul... |
15,341 | nowafter defining the loss function our prime goal is to minimize the loss function it can be done with the help of fitting the weights which means by increasing or decreasing the weights with the help of derivatives of the loss function each weightwe would be able to know what parameters should have high weight and wh... |
15,342 | nextwe will define sigmoid functionloss function and gradient descend as followsclass logisticregressiondef __init__(selflr= num_iter= fit_intercept=trueverbose=false)self lr lr self num_iter num_iter self fit_intercept fit_intercept self verbose verbose def __add_intercept(selfx)intercept np ones(( shape[ ] )return np... |
15,343 | nowinitialize the weights as followsself theta np zeros( shape[ ]for in range(self num_iter) np dot(xself thetah self __sigmoid(zgradient np dot( ( ) size self theta -self lr gradient np dot(xself thetah self __sigmoid(zloss self __loss(hyif(self verbose ==true and = )print( 'loss{loss\ 'with the help of the following ... |
15,344 | xx xx np meshgrid(np linspace( _minx _max)np linspace( _minx _max)grid np c_[xx ravel()xx ravel()probs model predict_prob(gridreshape(xx shapeplt contour(xx xx probs[ ]linewidths= colors='red')multinomial logistic regression model another useful form of logistic regression is multinomial logistic regression in which th... |
15,345 | from sklearn model_selection import train_test_split nextwe need to load digit datasetdigits datasets load_digits(nowdefine the feature matrix(xand response vector( )as followsx digits data digits target with the help of next line of codewe can split and into training and testing setsx_trainx_testy_trainy_test train_te... |
15,346 | classification algorithms supportmachine vector machine (svmintroduction to svm support vector machines (svmsare powerful yet flexible supervised machine learning algorithms which are used both for classification and regression but generallythey are used in classification problems in ssvms were first introduced but lat... |
15,347 | the main goal of svm is to divide the datasets into classes to find maximum marginal hyperplane (mmhand it can be done in the following two stepsfirstsvm will generate hyperplanes iteratively that segregates the classes in best way thenit will choose the hyperplane that separates the classes correctly implementing svm ... |
15,348 | plt plot([ ][ ]' 'color='black'markeredgewidth= markersize= for mb in [( )( )(- )]plt plot(xfitm xfit '- 'plt xlim(- )the output is as followswe can see from the above output that there are three different separators that perfectly discriminate the above samples as discussedthe main goal of svm is to divide the dataset... |
15,349 | from the above image in outputwe can easily observe the "marginswithin the discriminative classifiers svm will choose the line that maximizes the margin nextwe will use scikit-learn' support vector classifier to train an svm model on this data herewe are using linear kernel to fit svm as followsfrom sklearn svm import ... |
15,350 | yx np meshgrid(yxxy np vstack([ ravel() ravel()] model decision_function(xyreshape( shapenextwe need to plot decision boundaries and margins as followsax contour(xypcolors=' 'levels=[- ]alpha= linestyles=['--''-''--']nowsimilarly plot the support vectors as followsif plot_supportax scatter(model support_vectors_[: ]mod... |
15,351 | we can observe from the above output that an svm classifier fit to the data with margins dashed lines and support vectorsthe pivotal elements of this fittouching the dashed line these support vector points are stored in the support_vectors_ attribute of the classifier as followsmodel support_vectors_ the output is as f... |
15,352 | heregamma ranges from to we need to manually specify it in the learning algorithm good default value of gamma is as we implemented svm for linearly separable datawe can implement it in python for the data that is not linearly separable it can be done by using kernels example the following is an example for creating an ... |
15,353 | plt contourf(xxyyzcmap=plt cm tab alpha= plt scatter( [: ] [: ] =ycmap=plt cm set plt xlabel('sepal length'plt ylabel('sepal width'plt xlim(xx min()xx max()plt title('support vector classifier with linear kernel'output text( 'support vector classifier with linear kernel'for creating svm classifier with rbf kernelwe can... |
15,354 | output text( 'support vector classifier with rbf kernel'we put the value of gamma to 'autobut you can provide its value between to also pros and cons of svm classifiers pros of svm classifiers svm classifiers offers great accuracy and work well with high dimensional space svm classifiers basically use subset of trainin... |
15,355 | classification algorithms machine decision tree introduction to decision tree in generaldecision tree analysis is predictive modelling tool that can be applied across many areas decision trees can be constructed by an algorithmic approach that can split the dataset in different ways based on different conditions decisi... |
15,356 | implementing decision tree algorithm gini index it is the name of the cost function that is used to evaluate the binary splits in the dataset and works with the categorial target variable "successor "failurehigher the value of gini indexhigher the homogeneity perfect gini index value is and worst is (for class problemg... |
15,357 | reached at maximum depth once tree got maximum number of terminal nodes minimum node recordsit may be defined as the minimum number of training patterns that given node is responsible for we must stop adding terminal nodes once tree reached at these minimum node records or below this minimum terminal node is used to ma... |
15,358 | nextdownload the iris dataset from its weblink as followscol_names ['pregnant''glucose''bp''skin''insulin''bmi''pedigree''age''label'pima pd read_csv( " :\pima-indians-diabetes csv"header=nonenames=col_namespima head( pregnant glucose bp skin insulin bmi pedigree age label nowsplit the dataset into features and target ... |
15,359 | result accuracy_score(y_test,y_predprint("accuracy:",result output confusion matrix[[ ]classification reportprecision recall -score support micro avg macro avg weighted avg accuracy visualizing decision tree the above decision tree can be visualized with the help of following codefrom sklearn tree import export_graphvi... |
15,360 | |
15,361 | classification algorithmsmachine naive bayes introduction to naive bayes algorithm naive bayes algorithms is classification technique based on applying bayestheorem with strong assumption that all the predictors are independent to each other in simple wordsthe assumption is that the presence of feature in class is inde... |
15,362 | example depending on our data setwe can choose any of the naive bayes model explained above herewe are implementing gaussian naive bayes model in pythonwe will start with required imports as followsimport numpy as np import matplotlib pyplot as plt import seaborn as snssns set(nowby using make_blobs(function of scikit ... |
15,363 | output array([[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]]pros cons pros the followings are some pros of using naive bayes classifiersnaive bayes classification is easy to implement and fast it will converge faster than discriminative models like logistic regression it requires less training data it is highly scalable in natureor t... |
15,364 | applications of naive bayes classification the following are some common applications of naive bayes classificationreal-time predictiondue to its ease of implementation and fast computationit can be used to do prediction in real-time multi-class predictionnaive bayes classification algorithm can be used to predict post... |
15,365 | classification algorithms -machine random forest introduction random forest is supervised learning algorithm which is used for both classification as well as regression but howeverit is mainly used for classification problems as we know that forest is made up of trees and more trees means more robust forest similarlyra... |
15,366 | the following diagram will illustrate its workingtraining sample training sample training sample training sample training sample training sample training set test set voting prediction implementation in python firststart with importing necessary python packagesimport numpy as np import matplotlib pyplot as plt import p... |
15,367 | sepallength sepalwidth petallength petal-width class iris-setosa iris-setosa iris-setosa iris-setosa iris-setosa data preprocessing will be done with the help of following script linesx dataset iloc[::- values dataset iloc[: values nextwe will divide the data into train and test split the following code will split the ... |
15,368 | output confusion matrix[[ ]classification reportprecision recall -score support iris-setosa iris-versicolor iris-virginica micro avg macro avg weighted avg accuracy pros and cons of random forest pros the following are the advantages of random forest algorithmit overcomes the problem of overfitting by averaging or comb... |
15,369 | complexity is the main disadvantage of random forest algorithms construction of random forests are much harder and time-consuming than decision trees more computational resources are required to implement random forest algorithm it is less intuitive in case when we have large collection of decision trees the prediction... |
15,370 | machine learning algorithms regression |
15,371 | regression algorithmsmachine overview introduction to regression regression is another important and broadly used statistical and machine learning tool the key objective of regression-based tasks is to predict output labels or responses which are continues numeric valuesfor the given input data the output will be based... |
15,372 | types of regression models regression models simple multiple (univariate features(multiple featuresregression models are of following two typessimple regression modelthis is the most basic regression model in which predictions are formed from singleunivariate feature of the data multiple regression modelas name implies... |
15,373 | input_data np loadtxt(inputdelimiter=','xy input_data[::- ]input_data[:- step organizing data into training testing sets as we need to test our model on unseen data hencewe will divide our dataset into two partsa training set and test set the following command will perform ittraining_samples int( len( )testing_samples ... |
15,374 | output in the above outputwe can see the regression line between the data points step performance computationwe can also compute the performance of our regression model with the help of various performance metrics as followsprint("regressor model performance:"print("mean absolute error(mae="round(sm mean_absolute_error... |
15,375 | types of ml regression algorithms the most useful and popular ml regression algorithm is linear regression algorithm which further divided into two types namelysimple linear regression algorithm multiple linear regression algorithm we will discuss about it and implement it in python in the next applications the applica... |
15,376 | regression algorithms linear regression introduction to linear regression linear regression may be defined as the statistical model that analyzes the linear relationship between dependent variable with given set of independent variables linear relationship between variables means that when the value of one or more inde... |
15,377 | negative linear relationship linear relationship will be called positive if independent increases and dependent variable decreases it can be understood with the help of following graphnegative linear relationship types of linear regression linear regression is of the following two typessimple linear regression multiple... |
15,378 | nextdefine function which will calculate the important values for slrdef coef_estimation(xy)the following script line will give number of observations nn np size(xthe mean of and vector can be calculated as followsm_xm_y np mean( )np mean(ywe can find cross-deviation and deviation about as followsss_xy np sum( *xn*m_y*... |
15,379 | def main() np array([ ] np array([ ] coef_estimation(xyprint("estimated coefficients:\nb_ {\nb_ {}format( [ ] [ ])plot_regression_line(xybif __name__ ="__main__"main(output estimated coefficientsb_ b_ example in the following python implementation examplewe are using diabetes dataset from scikit-learn firstwe will star... |
15,380 | nextwe will load the diabetes dataset and create its objectdiabetes datasets load_diabetes(as we are implementing slrwe will be using only one feature as followsx diabetes data[:np newaxis nextwe need to split the data into training and testing sets as followsx_train [:- x_test [- :nextwe need to split the target into ... |
15,381 | output coefficients[ mean squared error variance score multiple linear regression (mlrit is the extension of simple linear regression that predicts response using two or more features mathematically we can explain it as followsconsider dataset having observationsp features independent variables and as one response depe... |
15,382 | python implementation in this examplewe will be using boston housing dataset from scikit learnfirstwe will start with importing necessary packages as follows%matplotlib inline import matplotlib pyplot as plt import numpy as np from sklearn import datasetslinear_modelmetrics nextload the dataset as followsboston dataset... |
15,383 | color "blue" label 'test data'plt hlines( xmin xmax linewidth plt legend(loc 'upper right'plt title("residual errors"plt show(output coefficients[- - - - - + + - - + - - - - - + - - - variance score assumptions the following are some assumptions about dataset that is made by linear regression modelmulti-collinearitylin... |
15,384 | auto-correlationanother assumption linear regression model assumes is that there is very little or no auto-correlation in the data basicallyauto-correlation occurs when there is dependency between residual errors relationship between variableslinear regression model assumes that the relationship between response and fe... |
15,385 | machine learning algorithms clustering |
15,386 | clustering algorithmsmachine overview introduction to clustering clustering methods are one of the most useful unsupervised ml methods these methods are used to find similarity as well as the relationship patterns among data samples and then cluster those samples into groups having similarity based on features clusteri... |
15,387 | in these methodsthe clusters are formed by portioning the objects into clusters number of clusters will be equal to the number of partitions ex -meansclustering large applications based upon randomized search (claransgrid in these methodsthe clusters are formed as grid like structure the advantage of these methods is t... |
15,388 | davis-bouldin index db index is another good metric to perform the analysis of clustering algorithms with the help of db indexwe can understand the following points about clustering modelweather the clusters are well-spaced from each other or nothow much dense the clusters arewe can calculate db index with the help of ... |
15,389 | hierarchical clustering it is another unsupervised learning algorithm that is used to group together the unlabeled data points having similar characteristics we will be discussing all these algorithms in detail in the upcoming applications of clustering we can find clustering useful in the following areasdata summariza... |
15,390 | clustering algorithms -means algorithm introduction to -means algorithm -means clustering algorithm computes the centroids and iterates until we it finds optimal centroid it assumes that the number of clusters are already known it is also called flat clustering algorithm the number of clusters identified from data by a... |
15,391 | due to the iterative nature of -means and random initialization of centroidskmeans may stick in local optimum and may not converge to global optimum that is why it is recommended to use different initializations of centroids implementation in python the following two examples of implementing -means clustering algorithm... |
15,392 | nextmake an object of kmeans along with providing number of clusterstrain the model and do the prediction as followskmeans kmeans(n_clusters= kmeans fit(xy_kmeans kmeans predict(xnowwith the help of following code we can plot and visualize the cluster' centers picked by -means python estimatorplt scatter( [: ] [: ] =y_... |
15,393 | example let us move to another example in which we are going to apply -means clustering on simple digits dataset -means will try to identify similar digits without using the original label information firstwe will start by importing the necessary packages%matplotlib inline import matplotlib pyplot as plt import seaborn... |
15,394 | output as outputwe will get following image showing clusters centers learned by -means the following lines of code will match the learned cluster labels with the true labels found in themfrom scipy stats import mode labels np zeros_like(clustersfor in range( )mask (clusters =ilabels[maskmode(digits target[mask])[ nextw... |
15,395 | the following are some disadvantages of -means clustering algorithmsit is bit difficult to predict the number of clusters the value of output is strongly impacted by initial inputs like number of clusters (value of korder of data will have strong impact on the final output it is very sensitive to rescaling if we will r... |
15,396 | clustering algorithms mean shift algorithm introduction to mean-shift algorithm as discussed earlierit is another powerful clustering algorithm used in unsupervised learning unlike -means clusteringit does not make any assumptionshence it is nonparametric algorithm mean-shift algorithm basically assigns the datapoints ... |
15,397 | plt scatter( [:, ], [:, ]plt show(ms meanshift(ms fit(xlabels ms labels_ cluster_centers ms cluster_centers_ print(cluster_centersn_clusters_ len(np unique(labels)print("estimated clusters:"n_clusters_colors *[' ',' ',' ',' ',' ',' ',' 'for in range(len( ))plt plot( [ ][ ] [ ][ ]colors[labels[ ]]markersize plt scatter(... |
15,398 | advantages and disadvantages advantages the following are some advantages of mean-shift clustering algorithmit does not need to make any model assumption as like in -means or gaussian mixture it can also model the complex clusters which have nonconvex shape it only needs one parameter named bandwidth which automaticall... |
15,399 | clustering algorithms hierarchical clustering introduction to hierarchical clustering hierarchical clustering is another unsupervised learning algorithm that is used to group together the unlabeled data points having similar characteristics hierarchical clustering algorithms falls into following two categoriesagglomera... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.