id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
15,400 | import matplotlib pyplot as plt import numpy as np nextwe will be plotting the datapoints we have taken for this examplex np array([[ , ],[ , ],[ , ],[ , ],[ , ],[ , ],[ , ][ , ],[ , ],[ , ],]labels range( plt figure(figsize=( )plt subplots_adjust(bottom= plt scatter( [:, ], [:, ]label='true position'for labelxy in zip(labelsx[: ] [: ])plt annotate(label,xy=(xy)xytext=(- ),textcoords='offset points'ha='right'va='bottom'plt show(from the above diagramit is very easy to see that we have two clusters in out datapoints but in the real world datathere can be thousands of clusters nextwe will be plotting the dendrograms of our datapoints by using scipy libraryfrom scipy cluster hierarchy import dendrogramlinkage from matplotlib import pyplot as plt linked linkage( 'single'labellist range( plt figure(figsize=( ) |
15,401 | dendrogram(linkedorientation='top',labels=labellistdistance_sort='descending',show_leaf_counts=trueplt show(nowonce the big cluster is formedthe longest vertical distance is selected vertical line is then drawn through it as shown in the following diagram as the horizontal line crosses the blue line at two pointsthe number of clusters would be two nextwe need to import the class for clustering and call its fit_predict method to predict the cluster we are importing agglomerativeclustering class of sklearn cluster library |
15,402 | from sklearn cluster import agglomerativeclustering cluster agglomerativeclustering(n_clusters= affinity='euclidean'linkage='ward'cluster fit_predict(xnextplot the cluster with the help of following codeplt scatter( [:, ], [:, ] =cluster labels_cmap='rainbow'the above diagram shows the two clusters from our datapoints example as we understood the concept of dendrograms from the simple example discussed abovelet us move to another example in which we are creating clusters of the data point in pima indian diabetes dataset by using hierarchical clusteringimport matplotlib pyplot as plt import pandas as pd %matplotlib inline import numpy as np from pandas import read_csv path " :\pima-indians-diabetes csvheadernames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=headernamesarray data values array[:, : |
15,403 | array[:, data shape ( data head(preg plas pres skin test mass pedi age class patient_data data iloc[: : values import scipy cluster hierarchy as shc plt figure(figsize=( )plt title("patient dendograms"dend shc dendrogram(shc linkage(datamethod='ward') |
15,404 | from sklearn cluster import agglomerativeclustering cluster agglomerativeclustering(n_clusters= affinity='euclidean'linkage='ward'cluster fit_predict(patient_dataplt figure(figsize=( )plt scatter(patient_data[:, ]patient_data[:, ] =cluster labels_cmap='rainbow' |
15,405 | machine learning algorithms knn algorithm |
15,406 | knn algorithm finding nearest neighbors introduction -nearest neighbors (knnalgorithm is type of supervised ml algorithm which can be used for both classification as well as regression predictive problems howeverit is mainly used for classification predictive problems in industry the following two properties would define knn welllazy learning algorithmknn is lazy learning algorithm because it does not have specialized training phase and uses all the data for training while classification non-parametric learning algorithmknn is also non-parametric learning algorithm because it doesn' assume anything about the underlying data working of knn algorithm -nearest neighbors (knnalgorithm uses 'feature similarityto predict the values of new datapoints which further means that the new data point will be assigned value based on how closely it matches the points in the training set we can understand its working with the help of following stepsstep for implementing any algorithmwe need dataset so during the first step of knnwe must load the training as well as test data step nextwe need to choose the value of the nearest data points can be any integer step for each point in the test data do the following calculate the distance between test data and each row of training data with the help of any of the method namelyeuclideanmanhattan or hamming distance the most commonly used method to calculate distance is euclidean nowbased on the distance valuesort them in ascending order nextit will choose the top rows from the sorted array nowit will assign class to the test point based on most frequent class of these rows step end example the following is an example to understand the concept of and working of knn algorithmsuppose we have dataset which can be plotted as follows |
15,407 | nowwe need to classify new data point with black dot (at point , into blue or red class we are assuming it would find three nearest data points it is shown in the next diagramwe can see in the above diagram the three nearest neighbors of the data point with black dot among those threetwo of them lies in red class hence the black dot will also be assigned in red class implementation in python as we know -nearest neighbors (knnalgorithm can be used for both classification as well as regression the following are the recipes in python to use knn as classifier as well as regressor |
15,408 | knn as classifier firststart with importing necessary python packagesimport numpy as np import matplotlib pyplot as plt import pandas as pd nextdownload the iris dataset from its weblink as followspath "nextwe need to assign column names to the dataset as followsheadernames ['sepal-length''sepal-width''petal-length''petal-width''class'nowwe need to read dataset to pandas dataframe as followsdataset pd read_csv(pathnames=headernamesdataset head( sepal-length sepal-width petal-length 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 following code will split the dataset into training data and of testing datafrom sklearn model_selection import train_test_split x_trainx_testy_trainy_test train_test_split(xytest_size= nextdata scaling will be done as followsfrom sklearn preprocessing import standardscaler scaler standardscaler(scaler fit(x_trainx_train scaler transform(x_train |
15,409 | x_test scaler transform(x_testnexttrain the model with the help of kneighborsclassifier class of sklearn as followsfrom sklearn neighbors import kneighborsclassifier classifier kneighborsclassifier(n_neighbors= classifier fit(x_trainy_trainat last we need to make prediction it can be done with the help of following scripty_pred classifier predict(x_testnextprint the results as followsfrom sklearn metrics import classification_reportconfusion_matrixaccuracy_score result confusion_matrix(y_testy_predprint("confusion matrix:"print(resultresult classification_report(y_testy_predprint("classification report:",print (result result accuracy_score(y_test,y_predprint("accuracy:",result output confusion matrix[[ ]classification reportprecision recall -score support iris-setosa iris-versicolor iris-virginica micro avg macro avg weighted avg |
15,410 | accuracy knn as regressor firststart with importing necessary python packagesimport numpy as np import pandas as pd nextdownload the iris dataset from its weblink as followspath "nextwe need to assign column names to the dataset as followsheadernames ['sepal-length''sepal-width''petal-length''petal-width''class'nowwe need to read dataset to pandas dataframe as followsdata pd read_csv(urlnames=headernamesarray data values array[:,: array[:, data shape output:( nextimport kneighborsregressor from sklearn to fit the modelfrom sklearn neighbors import kneighborsregressor knnr kneighborsregressor(n_neighbors= knnr fit(xyat lastwe can find the mse as followsprint ("the mse is:",format(np power( -knnr predict( ), mean())output the mse is |
15,411 | pros and cons of knn pros it is very simple algorithm to understand and interpret it is very useful for nonlinear data because there is no assumption about data in this algorithm it is versatile algorithm as we can use it for classification as well as regression it has relatively high accuracy but there are much better supervised learning models than knn cons it is computationally bit expensive algorithm because it stores all the training data high memory storage required as compared to other supervised learning algorithms prediction is slow in case of big it is very sensitive to the scale of data as well as irrelevant features applications of knn the following are some of the areas in which knn can be applied successfullybanking system knn can be used in banking system to predict weather an individual is fit for loan approvaldoes that individual have the characteristics similar to the defaulters onecalculating credit ratings knn algorithms can be used to find an individual' credit rating by comparing with the persons having similar traits politics with the help of knn algorithmswe can classify potential voter into various classes like "will vote""will not vote""will vote to party 'congress'"will vote to party 'bjpother areas in which knn algorithm can be used are speech recognitionhandwriting detectionimage recognition and video recognition |
15,412 | machine learning algorithms -machine performance metrics there are various metrics which we can use to evaluate the performance of ml algorithmsclassification as well as regression algorithms we must carefully choose the metrics for evaluating ml performance becausehow the performance of ml algorithms is measured and compared will be dependent entirely on the metric you choose how you weight the importance of various characteristics in the result will be influenced completely by the metric you choose performance metrics for classification problems we have discussed classification and its algorithms in the previous herewe are going to discuss various performance metrics that can be used to evaluate predictions for classification problems confusion matrix it is the easiest way to measure the performance of classification problem where the output can be of two or more type of classes confusion matrix is nothing but table with two dimensions viz "actualand "predictedand furthermoreboth the dimensions have "true positives (tp)""true negatives (tn)""false positives (fp)""false negatives (fn)as shown belowactual true positives (tpfalse positives (fp false negatives (fntrue negatives (tnpredicted explanation of the terms associated with confusion matrix are as followstrue positives (tp)it is the case when both actual class predicted class of data point is true negatives (tn)it is the case when both actual class predicted class of data point is false positives (fp)it is the case when actual class of data point is predicted class of data point is |
15,413 | false negatives (fn)it is the case when actual class of data point is predicted class of data point is we can use confusion_matrix function of sklearn metrics to compute confusion matrix of our classification model classification accuracy it is most common performance metric for classification algorithms it may be defined as the number of correct predictions made as ratio of all predictions made we can easily calculate it by confusion matrix with the help of following formulaaccuracy tp tn tp fp fn tn we can use accuracy_score function of sklearn metrics to compute accuracy of our classification model classification report this report consists of the scores of precisionsrecallf and support they are explained as followsprecision precisionused in document retrievalsmay be defined as the number of correct documents returned by our ml model we can easily calculate it by confusion matrix with the help of following formulaprecision tp tp fp recall or sensitivity recall may be defined as the number of positives returned by our ml model we can easily calculate it by confusion matrix with the help of following formularecall tp tp fn 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 |
15,414 | support support may be defined as the number of samples of the true response that lies in each class of target values score this score will give us the harmonic mean of precision and recall mathematicallyf score is the weighted average of the precision and recall the best value of would be and worst would be we can calculate score with the help of following formulaf (precision recall(precision recallf score is having equal relative contribution of precision and recall we can use classification_report function of sklearn metrics to get the classification report of our classification model auc (area under roc curveauc (area under curve)-roc (receiver operating characteristicis performance metricbased on varying threshold valuesfor classification problems as name suggestsroc is probability curve and auc measure the separability in simple wordsauc-roc metric will tell us about the capability of model in distinguishing the classes higher the aucbetter the model mathematicallyit can be created by plotting tpr (true positive ratei sensitivity or recall vs fpr (false positive ratei -specificityat various threshold values following is the graph showing rocauc having tpr at -axis and fpr at -axistpr roc aoc fpr we can use roc_auc_score function of sklearn metrics to compute auc-roc logloss (logarithmic lossit is also called logistic regression loss or cross-entropy loss it basically defined on probability estimates and measures the performance of classification model where the input is probability value between and it can be understood more clearly by differentiating it with accuracy as we know that accuracy is the count of predictions (predicted value actual valuein our model whereas log loss is the amount of uncertainty of our prediction based on how much it varies from the actual label with the |
15,415 | help of log loss valuewe can have more accurate view of the performance of our model we can use log_loss function of sklearn metrics to compute log loss example the following is simple recipe in python which will give us an insight about how we can use the above explained performance metrics on binary classification modelfrom sklearn metrics import confusion_matrix from sklearn metrics import accuracy_score from sklearn metrics import classification_report from sklearn metrics import roc_auc_score from sklearn metrics import log_loss x_actual [ y_predic [ results confusion_matrix(x_actualy_predicprint ('confusion matrix :'print(resultsprint ('accuracy score is',accuracy_score(x_actualy_predic)print ('classification report 'print (classification_report(x_actualy_predic)print('auc-roc:',roc_auc_score(x_actualy_predic)print('logloss value is',log_loss(x_actualy_predic)output confusion matrix [[ [ ]accuracy score is classification report precision recall -score support micro avg macro avg weighted avg auc-roc logloss value is |
15,416 | performance metrics for regression problems we have discussed regression and its algorithms in previous herewe are going to discuss various performance metrics that can be used to evaluate predictions for regression problems mean absolute error (maeit is the simplest error metric used in regression problems it is basically the sum of average of the absolute difference between the predicted and actual values in simple wordswith maewe can get an idea of how wrong the predictions were mae does not indicate the direction of the model no indication about underperformance or overperformance of the model the following is the formula to calculate maemae | yn herey=actual output values and predicted output values we can use mean_absolute_error function of sklearn metrics to compute mae mean square error (msemse is like the maebut the only difference is that the it squares the difference of actual and predicted output values before summing them all instead of using the absolute value the difference can be noticed in the following equationmse ( yn herey=actual output values and predicted output values we can use mean_squared_error function of sklearn metrics to compute mse squared ( squared metric is generally used for explanatory purpose and provides an indication of the goodness or fit of set of predicted output values to the actual output values the following formula will help us understanding it = ) ( - = ) ( - = in the above equationnumerator is mse and the denominator is the variance in values we can use _score function of sklearn metrics to compute squared value |
15,417 | example the following is simple recipe in python which will give us an insight about how we can use the above explained performance metrics on regression modelfrom sklearn metrics import _score from sklearn metrics import mean_absolute_error from sklearn metrics import mean_squared_error x_actual [ - y_predic [ - print (' squared =', _score(x_actualy_predic)print ('mae =',mean_absolute_error(x_actualy_predic)print ('mse =',mean_squared_error(x_actualy_predic)output squared mae mse |
15,418 | machine learning with pipelines -machine automatic workflows introduction in order to execute and produce results successfullya machine learning model must automate some standard workflows the process of automate these standard workflows can be done with the help of scikit-learn pipelines from data scientist' perspectivepipeline is generalizedbut very important concept it basically allows data flow from its raw format to some useful information the working of pipelines can be understood with the help of following diagramdata ingestion data preparation ml model training model evaluation deployment ml model re-training the blocks of ml pipelines are as followsdata ingestionas the name suggestsit is the process of importing the data for use in ml project the data can be extracted in real time or batches from single or multiple systems it is one of the most challenging steps because the quality of data can affect the whole ml model data preparationafter importing the datawe need to prepare data to be used for our ml model data preprocessing is one of the most important technique of data preparation ml model trainingnext step is to train our ml model we have various ml algorithms like supervisedunsupervisedreinforcement to extract the features from dataand make predictions model evaluationnextwe need to evaluate the ml model in case of automl pipelineml model can be evaluated with the help of various statistical methods and business rules ml model retrainingin case of automl pipelineit is not necessary that the first model is best one the first model is considered as baseline model and we can train it repeatably to increase model' accuracy |
15,419 | deploymentat lastwe need to deploy the model this step involves applying and migrating the model to business operations for their use challenges accompanying ml pipelines in order to create ml pipelinesdata scientists face many challenges these challenges fall into the following three categoriesquality of data the success of any ml model depends heavily on the quality of data if the data we are providing to ml model is not accuratereliable and robustthen we are going to end with wrong or misleading output data reliability another challenge associated with ml pipelines is the reliability of data we are providing to the ml model as we knowthere can be various sources from which data scientist can acquire data but to get the best resultsit must be assured that the data sources are reliable and trusted data accessibility to get the best results out of ml pipelinesthe data itself must be accessible which requires consolidationcleansing and curation of data as result of data accessibility propertymetadata will be updated with new tags modelling ml pipeline and data preparation data leakagehappening from training dataset to testing datasetis an important issue for data scientist to deal with while preparing data for ml model generallyat the time of data preparationdata scientist uses techniques like standardization or normalization on entire dataset before learning but these techniques cannot help us from the leakage of data because the training dataset would have been influenced by the scale of the data in the testing dataset by using ml pipelineswe can prevent this data leakage because pipelines ensure that data preparation like standardization is constrained to each fold of our cross-validation procedure example the following is an example in python that demonstrate data preparation and model evaluation workflow for this purposewe are using pima indian diabetes dataset from sklearn firstwe will be creating pipeline that standardized the data then linear discriminative analysis model will be created and at last the pipeline will be evaluated using -fold cross validation firstimport the required packages as followsfrom pandas import read_csv from sklearn model_selection import kfold from sklearn model_selection import cross_val_score |
15,420 | from sklearn preprocessing import standardscaler from sklearn pipeline import pipeline from sklearn discriminant_analysis import lineardiscriminantanalysis nowwe need to load the pima diabetes dataset as did in previous examplespath " :\pima-indians-diabetes csvheadernames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=headernamesarray data values nextwe will create pipeline with the help of the following codeestimators [estimators append(('standardize'standardscaler())estimators append(('lda'lineardiscriminantanalysis())model pipeline(estimatorsat lastwe are going to evaluate this pipeline and output its accuracy as followskfold kfold(n_splits= random_state= results cross_val_score(modelxycv=kfoldprint(results mean()output the above output is the summary of accuracy of the setup on the dataset modelling ml pipeline and feature extraction data leakage can also happen at feature extraction step of ml model that is why feature extraction procedures should also be restricted to stop data leakage in our training dataset as in the case of data preparationby using ml pipelineswe can prevent this data leakage also featureuniona tool provided by ml pipelines can be used for this purpose example the following is an example in python that demonstrates feature extraction and model evaluation workflow for this purposewe are using pima indian diabetes dataset from sklearn first features will be extracted with pca (principal component analysisthen features will be extracted with statistical analysis after feature extractionresult of multiple feature selection and extraction procedures will be combined by using |
15,421 | featureunion tool at lasta logistic regression model will be createdand the pipeline will be evaluated using -fold cross validation firstimport the required packages as followsfrom pandas import read_csv from sklearn model_selection import kfold from sklearn model_selection import cross_val_score from sklearn pipeline import pipeline from sklearn pipeline import featureunion from sklearn linear_model import logisticregression from sklearn decomposition import pca from sklearn feature_selection import selectkbest nowwe need to load the pima diabetes dataset as did in previous examplespath " :\pima-indians-diabetes csvheadernames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=headernamesarray data values nextfeature union will be created as followsfeatures [features append(('pca'pca(n_components= ))features append(('select_best'selectkbest( = ))feature_union featureunion(featuresnextpipeline will be creating with the help of following script linesestimators [estimators append(('feature_union'feature_union)estimators append(('logistic'logisticregression())model pipeline(estimatorsat lastwe are going to evaluate this pipeline and output its accuracy as followskfold kfold(n_splits= random_state= results cross_val_score(modelxycv=kfoldprint(results mean() |
15,422 | output the above output is the summary of accuracy of the setup on the dataset |
15,423 | machine learning improving performance of ml models performance improvement with ensembles ensembles can give us boost in the machine learning result by combining several models basicallyensemble models consist of several individually trained supervised learning models and their results are merged in various ways to achieve better predictive performance compared to single model ensemble methods can be divided into following two groupssequential ensemble methods as the name impliesin these kind of ensemble methodsthe base learners are generated sequentially the motivation of such methods is to exploit the dependency among base learners parallel ensemble methods as the name impliesin these kind of ensemble methodsthe base learners are generated in parallel the motivation of such methods is to exploit the independence among base learners ensemble learning methods the following are the most popular ensemble learning methods the methods for combining the predictions from different modelsbagging the term bagging is also known as bootstrap aggregation in bagging methodsensemble model tries to improve prediction accuracy and decrease model variance by combining predictions of individual models trained over randomly generated training samples the final prediction of ensemble model will be given by calculating the average of all predictions from the individual estimators one of the best examples of bagging methods are random forests boosting in boosting methodthe main principle of building ensemble model is to build it incrementally by training each base model estimator sequentially as the name suggestsit basically combine several week base learnerstrained sequentially over multiple iterations of training datato build powerful ensemble during the training of week base learnershigher weights are assigned to those learners which were misclassified earlier the example of boosting method is adaboost |
15,424 | voting in this ensemble learning modelmultiple models of different types are built and some simple statisticslike calculating mean or median etc are used to combine the predictions this prediction will serve as the additional input for training to make the final prediction bagging ensemble algorithms the following are three bagging ensemble algorithmsbagged decision treeas we know that bagging ensemble methods work well with the algorithms that have high variance andin this concernthe best one is decision tree algorithm in the following python recipewe are going to build bagged decision tree ensemble model by using baggingclassifier function of sklearn with decisiontreeclasifier ( classification regression trees algorithmon pima indians diabetes dataset firstimport the required packages as followsfrom pandas import read_csv from sklearn model_selection import kfold from sklearn model_selection import cross_val_score from sklearn ensemble import baggingclassifier from sklearn tree import decisiontreeclassifier nowwe need to load the pima diabetes dataset as we did in the previous examplespath " :\pima-indians-diabetes csvheadernames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=headernamesarray data values array[:, : array[:, nextgive the input for -fold cross validation as followsseed kfold kfold(n_splits= random_state=seedcart decisiontreeclassifier(we need to provide the number of trees we are going to build here we are building treesnum_trees |
15,425 | nextbuild the model with the help of following scriptmodel baggingclassifier(base_estimator=cartn_estimators=num_treesrandom_state=seedcalculate and print the result as followsresults cross_val_score(modelxycv=kfoldprint(results mean()output the output above shows that we got around accuracy of our bagged decision tree classifier model random forest it is an extension of bagged decision trees for individual classifiersthe samples of training dataset are taken with replacementbut the trees are constructed in such way that reduces the correlation between them alsoa random subset of features is considered to choose each split point rather than greedily choosing the best split point in construction of each tree in the following python recipewe are going to build bagged random forest ensemble model by using randomforestclassifier class of sklearn on pima indians diabetes dataset firstimport the required packages as followsfrom pandas import read_csv from sklearn model_selection import kfold from sklearn model_selection import cross_val_score from sklearn ensemble import randomforestclassifier nowwe need to load the pima diabetes dataset as did in previous examplespath " :\pima-indians-diabetes csvheadernames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=headernamesarray data values array[:, : array[:, nextgive the input for -fold cross validation as followsseed |
15,426 | kfold kfold(n_splits= random_state=seedwe need to provide the number of trees we are going to build here we are building trees with split points chosen from featuresnum_trees max_features nextbuild the model with the help of following scriptmodel randomforestclassifier(n_estimators=num_treesmax_features=max_featurescalculate and print the result as followsresults cross_val_score(modelxycv=kfoldprint(results mean()output the output above shows that we got around accuracy of our bagged random forest classifier model extra trees it is another extension of bagged decision tree ensemble method in this methodthe random trees are constructed from the samples of the training dataset in the following python recipewe are going to build extra tree ensemble model by using extratreesclassifier class of sklearn on pima indians diabetes dataset firstimport the required packages as followsfrom pandas import read_csv from sklearn model_selection import kfold from sklearn model_selection import cross_val_score from sklearn ensemble import extratreesclassifier nowwe need to load the pima diabetes dataset as did in previous examplespath " :\pima-indians-diabetes csvheadernames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=headernamesarray data values array[:, : |
15,427 | array[:, nextgive the input for -fold cross validation as followsseed kfold kfold(n_splits= random_state=seedwe need to provide the number of trees we are going to build here we are building trees with split points chosen from featuresnum_trees max_features nextbuild the model with the help of following scriptmodel extratreesclassifier(n_estimators=num_treesmax_features=max_featurescalculate and print the result as followsresults cross_val_score(modelxycv=kfoldprint(results mean()output the output above shows that we got around accuracy of our bagged extra trees classifier model boosting ensemble algorithms the followings are the two most common boosting ensemble algorithmsadaboost it is one the most successful boosting ensemble algorithm the main key of this algorithm is in the way they give weights to the instances in dataset due to this the algorithm needs to pay less attention to the instances while constructing subsequent models in the following python recipewe are going to build ada boost ensemble model for classification by using adaboostclassifier class of sklearn on pima indians diabetes dataset firstimport the required packages as followsfrom pandas import read_csv from sklearn model_selection import kfold from sklearn model_selection import cross_val_score from sklearn ensemble import adaboostclassifier |
15,428 | nowwe need to load the pima diabetes dataset as did in previous examplespath " :\pima-indians-diabetes csvheadernames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=headernamesarray data values array[:, : array[:, nextgive the input for -fold cross validation as followsseed kfold kfold(n_splits= random_state=seedwe need to provide the number of trees we are going to build here we are building trees with split points chosen from featuresnum_trees nextbuild the model with the help of following scriptmodel adaboostclassifier(n_estimators=num_treesrandom_state=seedcalculate and print the result as followsresults cross_val_score(modelxycv=kfoldprint(results mean()output the output above shows that we got around accuracy of our adaboost classifier ensemble model stochastic gradient boosting it is also called gradient boosting machines in the following python recipewe are going to build stochastic gradient boostingensemble model for classification by using gradientboostingclassifier class of sklearn on pima indians diabetes dataset firstimport the required packages as followsfrom pandas import read_csv from sklearn model_selection import kfold from sklearn model_selection import cross_val_score |
15,429 | from sklearn ensemble import gradientboostingclassifier nowwe need to load the pima diabetes dataset as did in previous examplespath " :\pima-indians-diabetes csvheadernames ['preg''plas''pres''skin''test''mass''pedi''age''class'data read_csv(pathnames=headernamesarray data values array[:, : array[:, nextgive the input for -fold cross validation as followsseed kfold kfold(n_splits= random_state=seedwe need to provide the number of trees we are going to build here we are building trees with split points chosen from featuresnum_trees nextbuild the model with the help of following scriptmodel gradientboostingclassifier(n_estimators=num_treesrandom_state=seedcalculate and print the result as followsresults cross_val_score(modelxycv=kfoldprint(results mean()output the output above shows that we got around accuracy of our gradient boosting classifier ensemble model voting ensemble algorithms as discussedvoting first creates two or more standalone models from training dataset and then voting classifier will wrap the model along with taking the average of the predictions of sub-model whenever needed new data in the following python recipewe are going to build voting ensemble model for classification by using votingclassifier class of sklearn on pima indians diabetes dataset we are combining the predictions of logistic regressiondecision tree classifier and svm together for classification problem as follows |
15,430 | backpropagation gradient descent variants gradient-based optimization techniques practical implementation with pytorch summary automatic differentiation in deep learning numerical differentiation symbolic differentiation automatic differentiation fundamentals implementing automatic differentiation summary training deep leaning models performance metrics classification metrics regression metrics data procurement splitting data for trainingvalidationand testing establishing the achievable limit on the error rate establishing the baseline with standard choices building an automatedend-to-end pipeline orchestration for visibility analysis of overfitting and underfitting hyperparameter tuning model capacity regularizing the model early stopping norm penalties |
15,431 | dropout practical implementation in pytorch interpreting the business outcomes for deep learning summary convolutional neural networks convolution operation pooling operation convolution-detector-pooling building block stride padding batch normalization filter filter depth number of filters summarizing key learnings from cnns implementing basic cnn using pytorch implementing larger cnn in pytorch cnn thumb rules summary recurrent neural networks introduction to rnns training rnns bidirectional rnns vanishing and exploding gradients gradient clipping vi |
15,432 | long short-term memory practical implementation summary recent advances in deep learning going beyond classification in computer vision object detection image segmentation pose estimation generative computer vision natural language processing with deep learning transformer models bidirectional encoder representations from transformers groknet additional noteworthy research concluding thoughts index vii |
15,433 | nikhil ketkar currently leads the machine learning platform team at flipkartindia' largest ecommerce company he received his phd from washington state university following thathe conducted postdoctoral research at university of north carolina at charlottewhich was followed by brief stint in high-frequency trading at transmarket in chicago more recentlyhe led the data mining team at guavusa startup doing big data analytics in the telecom domainand indixa startup doing data science in the ecommerce domain his research interests include machine learning and graph theory jojo moolayil is an artificial intelligence professional and published author of three books on machine learningdeep learningand iot he is currently working with amazon web services as research scientist in their vancouverbc office in his current role with awsjojo works on researching and developing large-scale solutions for combating fraud and enriching the customer' payment experience in the cloud he is also actively involved as technical reviewer and ai consultant with leading publishers and has reviewed over dozen books on machine learningdeep learningand business analytics ix |
15,434 | you can reach jojo atx |
15,435 | judy raj is google certified professional cloud architect she has great experience with the three leading cloud platforms-amazon web servicesazureand google cloud platform--and has co-authored book on google cloud platform with packt publications she has also worked with wide range of technologies in machine learningdata scienceblockchainsiotroboticsand mobile and web app development she is currently technical content engineer in loonycorn judy holds degree in computer science and engineering from cochin university of science and technology driven engineer fascinated with technologyshe is passionate codera machine language enthusiastand blockchain aficionado manohar swamynathan is data science practitioner and an avid programmerwith more than years of experience in various data science-related areasincluding data warehousingbusiness intelligence (bi)analytical tool developmentad-hoc analysispredictive modelingdata science product developmentconsultingformulating strategyand executing analytics programs xi |
15,436 | his career has covered the life cycle of data across multiple domainssuch as us mortgage bankingretail/ecommerceinsuranceand industrial iot manohar has bachelor' degree with specialization in physicsmathematicscomputersand master' degree in project management he is currently living in bengaluruthe silicon valley of india xii |
15,437 | would like to thank my colleagues at flipkart and indixand the technical reviewersfor their feedback and comments will also like to thank charu mudholkar for proofreading the book in its final stages --nikhil ketkar would like to thank my beloved wifedivyafor her constant support --jojo moolayil xiii |
15,438 | this book has been drafted with unique approach the second edition focuses on the practicality of the topics within deep learning that help the reader to embrace modern tools with the right mathematical foundations the first edition focused on introducing meaningful foundation for the subjectwhile limiting the depth of the practical implementations while we explored breadth of technical frameworks for deep learning (theanotensorflowkerasand pytorch)we limited the depth of the implementation details the idea was to distill the mathematical foundations while focusing briefly on the practical tools used for implementation lot has changed over the past three years the deep learning fraternity is now stronger than everand the frameworks have evolved in size and adoption theano is now deprecated (ceased development)tensorflow saw huge adoption in the industry and academiaand keras became more popular among beginners and deep learning enthusiasts howeverpytorch has emerged recently as widely popular choice for academia as well as industry the growing number of research publications that recently have used pytorch over tensorflow is testament to its growth within deep learning on the same notewe felt the need to revise the book with focus on engaging readers with hands-on exercises to aid more meaningful understanding of the subject in this bookwe have struck the perfect balancewith mathematical foundations as well as hands-on exercisesto embrace practical implementation exclusively on pytorch each exercise is supplemented with the required explanations of pytorch' functionalities and required abstractions for programming complexities xv |
15,439 | part serves as brief introduction to machine learningdeep learningand pytorch we explore the evolution of the fieldfrom early rule-based systems to the present-day sophisticated algorithmsin an accelerated fashion part ii explores the essential deep learning building blocks introduces simple feed-forward neural network incrementally and logicallywe uncover the various building blocks that constitute neural network and which can be reused in building any other network though foundational focuses on building baby neural network with the required framework that helps to construct and train networks of all kinds and complexities in we explore the core idea that enabled the possibility of training large networks through backpropagation using automatic differentiation and chain rule we explore pytorch' autograd module with small example to understand how the solution works programmatically in we look at orchestrating all the building blocks discussed through so faralong with the performance metrics of deep learning models and the artifacts required to enable an improved means for training-- regularizationhyperparameter tuningoverfittingunderfittingand model capacity finallywe leverage all this content to develop deep neural network for real-life dataset using pytorch in this exercisewe also explore additional pytorch constructs that help in the orchestration of various deep learning building blocks part iii covers three important topics within deep learning explores convolutional neural networks and introduces the field of computer vision we explore the core topics within convolutional neural networksincluding how they learn and how they are distinguished from other networks we also leverage few hands-on exercises--using small mnist dataset as well as the popular cats and dogs dataset--to study the practical implementation of convolutional neural network in we study recurrent neural networks and enter the field of natural language processing similar to we incrementally build an intuition xvi |
15,440 | around the fundamentals and later explore practical exercises with real-life datasets concludes the book by looking at some of the recent trends within deep learning this is only cursory introduction and does not include any implementation details the objective is to highlight some advances in the research and the possible next steps for advanced topics overallwe have put in great efforts to write structuredconciseexercise-rich book that balances the coverage between the mathematical foundations and the practical implementation xvii |
15,441 | introduction to machine learning and deep learning the subject of deep learning has gained immense popularity recentlyandin the processhas given rise to several terminologies that make distinguishing them fairly complex one might find the task of neatly separating each field overwhelmingwith the sheer volume of overlap between the topics this introduces the subject of deep learning by discussing its historical context and how the field evolved into its present-day form laterwe will introduce machine learning by covering the foundational topics in brief to start with deep learningwe will leverage the constructs gained from machine learning using basic python begins the practical implementation using pytorch defining deep learning deep learning is subfield within machine learning that deals with the algorithms that closely resemble an over-simplified version of the human brain that solves vast category of modern-day machine intelligence many common examples can be found within the smartphone' app (cnikhil ketkarjojo moolayil ketkar and moolayildeep learning with python |
15,442 | introduction to machine learning and deep learning ecosystem (ios and android)face detection on the cameraauto-correct and predictive text on keyboardsai-enhanced beautification appssmart assistants like siri/alexa/google assistantface-id (face unlock on iphones)video suggestions on youtubefriend suggestions on facebookcat filters on snapchat are all products that were made the state-of-theart only for deep learning essentiallydeep learning is ubiquitous in the today' digital life truth be toldit can be complicated to define deep learning without navigating some historical context brief history the journey of artificial intelligence (aito its present day can be broadly divided into four partsviz rule-based systemsknowledge-based systemsmachineand deep learning although the granular transitions in the journey can be mapped into several important milestoneswe will cover more simplistic overview the entire evolution is encompassed into the larger idea of "artificial intelligence let' take step-by-step approach to tackle this broad term figure - the ai landscape |
15,443 | introduction to machine learning and deep learning the journey of deep learning starts with the field of artificial intelligencethe rightful parent of the fieldand has rich history going back to the the field of artificial intelligence can be defined in simple terms as the ability of machines to think and learn in more layman wordswe would define it as the process of aiding machines with intelligence in some form so that they can execute task better than before the above figure - showcases simplified landscape of ai with the various aforementioned fields showcased subset we will explore each of these subsets in more detail in the section below ule-based systems the intelligence we induce into machine may not necessarily be sophisticated process or abilitysomething as simple as set of rules can be defined as intelligence the first-generation ai products were simply rule-based systemswherein comprehensive set of rules were guided to the machine to map the exhaustive possibilities machine that executes task based on defined rules would result in more appealing outcome than rigid machine (one without intelligencea more layman example for the modern-day equivalent would be an atm that dispenses cash once authenticatedusers enter the amount they want and the machinebased on the existing combination of notes in-storedispenses the correct amount with the least number of bills the logic (intelligencefor the machine to solve the problem is explicitly coded (designedthe designer of the machine carefully thought through the comprehensive list of possibilities and designed system that can solve the task programmatically with finite time and resources most of the early day' success in artificial intelligence was fairly simple such tasks can be easily described formallylike the game of checkers or chess this notion of being able to easily describe the task formally is at the heart of what can or cannot be done easily by computer program for instanceconsider the game of chess the |
15,444 | introduction to machine learning and deep learning formal description of the game of chess would be the representation of the boarda description of how each of the pieces movesthe starting configurationand description of the configuration wherein the game terminates with these notions formalizedit is relatively easy to model chess-playing ai program as searchandgiven sufficient computational resourcesit' possible to produce relatively good chess-playing ai the first era of ai focused on such tasks with fair amount of success at the heart of the methodology were symbolic representation of the domain and the manipulation of the symbols based on given rules (with increasingly sophisticated algorithms for searching the solution space to arrive at solutionit must be noted that the formal definitions of such rules were done manually howeversuch early ai systems were fairly general-purpose task/problem solvers in the sense that any problem that could be described formally could be solved with the generic approach the key limitation of such systems is that the game of chess is relatively easy problem for ai simply because the problem set is relatively simple and can be easily formalized this is not the case with many of the problems human beings solve on day-to-day basis (natural intelligencefor instanceconsider diagnosing disease or transcribing human speech to text these taskswhich human beings can do but which are hard to describe formallypresented as challenge in the early days of ai knowledge-based systems the challenge of addressing natural intelligence to solve day-to-day problems evolved the landscape of ai into an approach akin to humanbeings-- by leveraging large amount of knowledge about the taskproblem domain given this observationsubsequent ai systems relied on large knowledge bases that captured the knowledge about the problemtask domain note that the term used here is knowledgenot information or data by knowledgewe simply mean data/information that programalgorithm can reason about an example could be graph representation |
15,445 | introduction to machine learning and deep learning of map with edges labeled with distances and about of traffic (which is being constantly updated)allowing program to reason about the shortest path between points such knowledge-based systemswherein the knowledge was compiled by experts and represented in way that allowed algorithms/programs to reason about itrepresented the second generation of ai at the heart of such approaches were increasingly sophisticated approaches for representing and reasoning about knowledge to solve tasks/problems that required such knowledge examples of such sophistication include the use of first-order logic to encode knowledge and probabilistic representations to capture and reason where uncertainty is inherent to the domain one of the key challenges that such systems facedand addressed to some extentwas the uncertainty inherent in many domains human beings are relatively good at reasoning in environments with unknowns and uncertainty one key observation here is that even the knowledge we hold about domain is not black or white but grey lot of progress was made in this era on representing and reasoning about unknowns and uncertainty there were some limited successes in tasks like diagnosing disease that relied on leveraging and reasoning using knowledge base in the presence of unknowns and uncertainty the key limitation of such systems was the need to hand-compile the knowledge about the domain from experts collectingcompilingand maintaining such knowledge bases rendered such systems impractical in certain domainsit was extremely hard to even collect and compile such knowledge--for exampletranscribing speech to text or translating documents from one language to another while human beings can easily learn to do such tasksit' extremely challenging to hand-compile and encode the knowledge related to the tasks--for instancethe knowledge of the english language and grammaraccentsand subject matter to address these challengesmachine learning is the way forward |
15,446 | introduction to machine learning and deep learning machine learning in formal termswe define machine learning as the field within ai where intelligence is added without explicit programming human beings acquire knowledge for any task through learning given this observationthe focus of subsequent work in ai shifted over decade or two to algorithms that improved their performance based on data provided to them the focus of this subfield was to develop algorithms that acquired relevant knowledge for task/problem domain given data it is important to note that this knowledge acquisition relied on labeled data and suitable representation of labeled data as defined by human being considerfor examplethe problem of diagnosing disease for such taska human expert would collect lot of cases where patient had and did not have the disease in question thenthe human expert would identify number of features that would aid in making the prediction-for examplethe age and gender of the patientand the results from number of diagnostic testssuch as blood pressureblood sugaretc the human expert would compile all this data and represent it in suitable form--for exampleby scaling/normalizing the dataetc once this data were prepareda machine learning algorithm could learn how to infer whether the patient has the disease or not by generalizing from the labeled data note that the labeled data consisted of patients that both have and do not have the disease soin essencethe underlying machine language algorithm is essentially doing the job of finding mathematical function that can produce the right outcome (disease or no diseasegiven the inputs (features like agegenderdata from diagnostic testsand so forthfinding the simplest mathematical function that predicts the outputs with the required level of accuracy is at the heart of the field of machine learning for examplequestions related to the number of examples required to learn task or the time complexity of an algorithm are specific areas for which the field of ml has provided answers with theoretical justification the field has matured to point wheregiven enough data |
15,447 | introduction to machine learning and deep learning compute resourcesand human resources to engineer featuresa large class of problems are solvable the key limitation of mainstream machine language algorithms is that applying them to new problem domain requires massive amount of feature engineering for instanceconsider the problem of recognizing objects in images using traditional machine language techniquessuch problem would require massive feature-engineering effort wherein experts identify and generate features that would be used by the machine language algorithm in sensetrue intelligence is in the identification of featuresthe machine language algorithm is simply learning how to combine these features to arrive at the correct answer this identification of features or the representation of data that domain experts do before machine language algorithms are applied is both conceptual and practical bottleneck in ai it' conceptual bottleneck because if features are being identified by domain experts and the machine language algorithm is simply learning to combine and draw conclusions from thisis this really aiit' practical bottleneck because the process of building models via traditional machine language is bottlenecked by the amount of feature engineering required there are limits to how much human effort can be thrown at the problem deep learning the major bottleneck in machine learning systems was solved with deep learning herewe essentially took the intelligence one step furtherwhere the machine develops relevant features for the task in an automated way instead of hand-crafting human beings learn concepts starting from raw data for instancea child shown with few examples of particular animal (saycatswill soon learn to identify the animal the learning process does not involve parent identifying cat' featuressuch as its whiskersfuror tail human learning goes from raw data to conclusion without the explicit step where features are identified and provided to the learner in sensehuman beings learn the appropriate representation |
15,448 | introduction to machine learning and deep learning of data from the data itself furthermorethey organize concepts as hierarchy where complicated concepts are expressed using primitive concepts the field of deep learning has its primary focus on learning appropriate representations of data such that these could be used to conclude the word "deepin "deep learningrefers to the idea of learning the hierarchy of concepts directly from raw data more technically appropriate term for deep learning would be representation learningand more practical term for the same would be automated feature engineering advances in related fields it is important to note the advances in other fields like compute powerstorage costetc that have played key role in the recent interest and success of deep learning consider the followingfor example the ability to collectstore and process large amounts of data has greatly advanced over the last decade (for instancethe apache hadoop ecosystemthe ability to generate supervised training data (data with labels--for examplepictures annotated with the objects in the picturehas improved lot with the availability of crowd-sourcing services (like amazon mechanical turkthe massive improvements in computational horsepower brought about by graphical processing units (gpusenabled parallel computing to new heights the advances in both the theory and software implementation of automatic differentiation (such as pytorch or theanoaccelerated the speed of development and research for deep learning |
15,449 | introduction to machine learning and deep learning although these advancements are peripheral to deep learningthey have played big role in enabling advances in deep learning rerequisites the key prerequisites for reading this book include working knowledge of python and some coursework in linear algebracalculusand probability readers should refer to the following in case they need to cover these prerequisites dive into pythonby mark pilgrim apress publications ( introduction to linear algebra (fifth edition)by gilbert strang wellesley-cambridge press calculusby gilbert strang wellesley-cambridge press all of statistics (section - )by larry wasserman springer ( the approach ahead this book focuses on the key concepts of deep learning and its practical implementation using pytorch in order to use pytorchyou should possess basic understanding of python programming introduces pytorchand the subsequent discuss additional important constructs within pytorch before delving into deep learningwe need to discuss the basic constructs of machine learning in the remainder of this we will explore the baby steps of machine learning with dummy example to implement the constructswe will use python and again implement the same using pytorch |
15,450 | introduction to machine learning and deep learning installing the required libraries you need to install number of libraries in order to run the source code for the examples in this book we recommend installing the anaconda python distribution (simplifies the process of installing the required packages (using either conda or pipthe list of packages you need include numpymatplotlibscikit-learnand pytorch pytorch is not installed as part of the anaconda distribution you should install pytorchtorchtextand torchvisionalong with the anaconda environment note that python (and aboveis recommended for the exercises in this book we highly recommend creating new python environment after installing the anaconda distribution create new environment with python (use terminal in linuxmac or the command prompt in windows)and then install the additional necessary packagesas followsconda create - testenvironment python= conda activate testenvironment pip install pytorch torchvision torchtext for additional help with pytorchplease refer to the get started guide at the concept of machine learning as human beingswe are intuitively aware of the concept of learning it simply means to get better at task over time the task could be physicalsuch as learning to drive caror intellectualsuch as learning new language the subject of machine learning focuses on the development of algorithms that can learn as humans learnthat isthey get better at task |
15,451 | introduction to machine learning and deep learning over period over time and with experience--thus inducing intelligence without explicit programming the first question to ask is why we would be interested in the development of algorithms that improve their performance over timewith experience after allmany algorithms are developed and implemented to solve real-world problems that don' improve over timethey simply are developed by humansimplemented in softwareand get the job done from banking to ecommerce and from navigation systems in our cars to landing spacecraft on the moonalgorithms are everywhereanda majority of them do not improve over time these algorithms simply perform the task they are intended to performwith some maintenance required from time to time why do we need machine learningthe answer to this question is that for certain tasks it is easier to develop an algorithm that learns/improves its performance with experience than to develop an algorithm manually although this might seem unintuitive to the reader at this pointwe will build intuition for this during this machine learning can be broadly classified as supervised learningwhere training data with labels is provided for the model to learnand unsupervised learningwhere the training data lacks labels we also have semi-supervised learning and reinforcement learningbut for nowwe would limit our scope to supervised machine learning supervised learning can again be classified into two areasclassificationfor discrete outcomesand regressionfor continuous outcomes binary classification in order to further discuss the matter at handwe need to be precise about some of the terms we have been intuitively usingsuch as tasklearningexperienceand improvement we will start with the task of binary classification |
15,452 | introduction to machine learning and deep learning consider an abstract problem domain where we have data of the form , , xn ,yn where rn and + we do not have access to all such data but only subset using sour task is to generate computational procedure that implements the function such that we can use to make predictions over unseen data (xiyis that are correctf(xiyi let' denote as the set of unseen data--that is(xiyis and (xiyiu we measure performance over this task as the error over unseen data du xi yi xi yi we now have precise definition of the taskwhich is to categorize data into one of two categories ( + based on some seen data by generating we measure performance (and improvement in performanceusing the error efduover unseen data the size of the seen data |sis the conceptual equivalent of experience in this contextwe want to develop algorithms that generate such functions (which are commonly referred to as modelin generalthe field of machine learning studies the development of such algorithms that produce models that make predictions over unseen data for suchandother formal tasks (we introduce multiple such tasks later in the note that the is commonly referred to as the input/input variable and is referred to as the output/output variable as with any other discipline in computer sciencethe computational characteristics of such algorithms are an important facethoweverin addition to thatwe also would like to have model that achieves lower error efduwith as small |sas possible let' now relate this abstract but precise definition to real-world problem so that our abstractions are grounded suppose that an ecommerce website wants to customize its landing page for registered |
15,453 | introduction to machine learning and deep learning users to show the products they might be interested in buying the website has historical data on users and would like to implement this as feature to increase sales let' now see how this real-world problem maps on to the abstract problem of binary classification we described earlier the first thing that one might notice is that given particular user and particular productone would want to predict whether the user will buy the product since this is the value to be predictedit maps on to + where we will let the value of denote the prediction that the user will buy the product and the value of denote the prediction that the user will not buy the product note that there is no particular reason for picking these valueswe could have swapped this (let denote the does not buy case and denote the buy case)and there would be no difference we just use + to denote the two classes of interest to categorize data nextlet' assume that we can represent the attributes of the product and the users buying and browsing history as rn this step is referred to as feature engineering in machine learning and we will cover it later in the for nowit suffices to say that we are able to generate such mapping thuswe have historical data of what the users browsed and boughtattributes of productand whether the user bought the product or not mapped on to {( )( )(xnyn)nowbased on this datawe would like to generate function or model ywhich we can use to determine which products particular user will buyand use this to populate the landing page for users we can measure how well the model is doing on unseen data by populating the landing page for usersseeing whether they buy the products or notand evaluating the error efduregression this section introduces another taskregression herewe have data of the form {( )( )(xnyn)}where rn and rand our task is to generate computational procedure that implements the function |
15,454 | introduction to machine learning and deep learning note that instead of the prediction being binary class label + like in binary classificationwe have real valued prediction we measure performance over this task as the root-mean-square error (rmseover unseen data yi xi du note that the rmse is simply taking the difference between the predicted and actual valuesquaring it so as to account for both positive and negative differencestaking the mean so as to aggregate over all the unseen dataandfinallytaking the square root so as to counterbalance the square operation real-world problem that corresponds to the abstract task of regression is to predict the credit score for an individual based on their financial historywhich can be used by credit card company to extend the line of credit generalization let' now cover what is the single most important intuition in machine leaningwhich is that we want to develop/generate models that have good performance over unseen data in order to do thatfirst will we introduce toy data set for regression task laterwe will develop three different models using the same dataset with varying levels of complexity and study how the results differ to understand intuitively the concept of generalization |
15,455 | introduction to machine learning and deep learning in listing - we generate the toy dataset by generating values equidistantly between - and as the input variable (xwe generate the output variable (ybased on where , is noise (random variationfrom normal distributionwith being the mean and being the standard deviation the code for this is presented in listing - and the data is plotted in figure - in order to simulate seen and unseen datawe use the first data points as seen data and treat the rest as unseen data that iswe build the model using only the first data points and use the rest for evaluating the model listing - generalization vs rote learning #import packages import matplotlib pyplot as plt import numpy as np #generate toy dataset np linspace(- , , signal noise numpy random normal( signal noise plt plot(signal,' ')plt plot( ,' 'plt plot(noise' 'plt xlabel(" "plt ylabel(" "plt legend(["without noise""with noise""noise"]loc plt show(#extract training from the toy dataset x_train [ : y_train [ : print("shape of x_train:",x_train shapeprint("shape of y_train:",y_train shape |
15,456 | introduction to machine learning and deep learning output[shape of x_train( ,shape of y_train( ,figure - toy dataset nextwe use very simple algorithm to generate modelcommonly referred to as least squares given data set of the form {( )( )(xnyn)}where rn and rthe least squares model takes the form bxwhere is vector such that is minimized herex is matrix wherein each row is an (thusx rm with being the number of examples--in our case the value of can be derived using the closed form (xtx)- xty we are glossing over lot of important details of the least squares methodbut those are secondary to the current discussion the more pertinent detail is how we transform the input variable to suitable form in our first modelwe will transform to be vector of values [ that isif it will be transformed to [ after this transformationwe can generate least squares model using the formula described previously what is happening under the hood is that we are approximating the given data with second order polynomial (degree equationand the least squares algorithm is simply curve fitting or generating the coefficients for each of [ |
15,457 | introduction to machine learning and deep learning we can evaluate the model on the unseen data using the rmse metric we can also compute the rmse metric on the training data figure - plots the actual and predicted valuesand listing - shows the source code for generating the model listing - function to build model with parameterized number of co-efficients #create function to build regression model with parameterized degree of independent coefficients def create_model(x_train,degree)degree+= x_train np column_stack([np power(x_train,ifor in range( ,degree)]model np dot(np dot(np linalg inv(np dot(x_train transpose(),x_train)),x_train transpose()),y_trainplt plot( , ,' 'plt xlabel(" "plt ylabel(" "predicted np dot(model[np power( ,ifor in range( ,degree)]plt plot(xpredicted,' 'plt legend(["actual""predicted"]loc plt title("model with degree = "train_rmse np sqrt(np sum(np dot( [ : predicted[ : ]y_train predicted[ : ]))test_rmse np sqrt(np sum(np dot( [ :predicted[ :] [ :predicted[ :]))print("train rmse(degree "+str(degree)+"):"round(train_ rmse , )print("test rmse (degree "+str(degree)+"):"round(test_ rmse , )plt show( |
15,458 | introduction to machine learning and deep learning #create model with degree using the function create_model(x_train, output[train rmse(degree ) test rmse (degree ) figure - actual and predicted values for model with degree similarlylisting - and figure - repeat the exercise for model with degree = listing - creating model with degree= #create model with degree= create_model(x_train, output[train rmse (degree test rmse (degree |
15,459 | introduction to machine learning and deep learning figure - actual and predicted values for model with degree nextas shown in listing - we generate another model with the least squares algorithmbut we will transform to [ that iswe are approximating the given data with polynomial with degree listing - model with degree= #create model with degree= create_model(x_train, output[train rmse(degree ) test rmse (degree ) |
15,460 | introduction to machine learning and deep learning figure - actual and predicted values for model with degree the actual and predicted values are plotted in figure - figure - and figure - the source-code (functionfor creating the model is available in listing - we now have all the details in place to discuss the core concept of generalization the key question to ask is which is the better model--the one with degree the one with degree or the one with degree let' start by making few observations about the three models the model with degree performs poorly on both the seen as well as unseen data as compared to all other two models the model with degree performs better on seen data as compared to model with degree the model with degree performs better then model with degree on unseen data table - should help to clarify the interpretation of the models table - comparing the performance of the three models |
15,461 | introduction to machine learning and deep learning we now consider the important concept of model capacitywhich corresponds to the degree of the polynomial in this example the data we generated was using second order polynomial (degree with some noise thenwe tried to approximate the data using three models (of degrees and respectivelythe higher the degreethe more expressive is the model--that isit can accommodate more variation this ability to accommodate variation corresponds to the notion of model capacity that iswe say that the model with degree has higher capacity than the model with degree whichin turnhas higher capacity than the model with degree isn' having higher capacity always good thingit turns out that it is notwhen we consider that all real-world datasets contain some noise and higher capacity model will end up in just fitting the noise in addition to the signal in the data this is why we observe that the model with degree does better on the unseen data as compared to the model with degree in this examplewe knew how the data was generated (with second order polynomial (degree with some noise)hencethis observation is quite trivial howeverin the real worldwe don' know the underlying mechanism by which the data is generated this leads us to the fundamental challenge in machine learningdoes the model truly generalizeand the only true test for that is the performance over unseen data in sensethe concept of capacity corresponds to the simplicity or parsimony of the model model with high capacity can approximate more complex data this is how many how many free variablescoefficients the model has in our examplethe model with degree does not have capacity sufficient to approximate the data this is commonly referred to as underfitting correspondinglythe model with degree has extra capacity and overfits the data as thought experimentconsider what would happen if we had model with degree given that we had data points as training datawe would have an -degree polynomial that would perfectly approximate the data this is the ultimate pathological case where in there is no learning at all the model has coefficients and can simply |
15,462 | introduction to machine learning and deep learning memorize the data this is referred to as rote learningthe logical extreme of overfitting this is why the capacity of the model needs to be tuned with respect to the amount of training data we have if the dataset is smallwe are better off training models with lower capacity egularization building on the ideas of model capacitygeneralizationoverfittingand underfittingthis section discusses regularization the key idea here is to penalize the complexity of the model regularized version of least squares takes the form bxwhere is vector such that is minimized and is user-defined parameter that controls the complexity hereby introducing the term we are penalizing complex models to see why this is the caseconsider fitting least squares model using polynomial of degree but the values in the vector have eight zeros and two non-zeros as against thisconsider the case where all values in the vector are non-zeros for all practical purposesthe former model is model with degree and has lower value of the term enables us to balance accuracy over the training data with the complexity of the model lower values of imply simpler model tuning the value of lwe can improve model performance over unseen data by balancing overfitting and underfitting listing - demonstrates how the model performance on unseen data changes while keeping the model coefficients constant but increasing values listing - regularization import matplotlib pyplot as plt import numpy as np #setting seed for reproducibility np random seed( |
15,463 | introduction to machine learning and deep learning #create random data np linspace(- , , signal noise np random normal( signal noise x_train [ : y_train [ : train_rmse [test_rmse [degree #define range of values for lambda lambda_reg_values np linspace( , , for lambda_reg in lambda_reg_values#for each value of lambdacompute build model and compute performance for lambda_reg in lambda_reg_valuesx_train np column_stack([np power(x_train,ifor in range( ,degree)]model np dot(np dot(np linalg inv(np dot(x_train transpose(),x_trainlambda_reg np identity(degree))x_train transpose()),y_trainpredicted np dot(model[np power( ,ifor in range( ,degree)]train_rmse append(np sqrt(np sum(np dot( [ : predicted[ : ]y_train predicted[ : ])))test_rmse append(np sqrt(np sum(np dot( [ :predicted[ :] [ :predicted[ :])))#plot the performance over train and test dataset plt plot(lambda_reg_valuestrain_rmseplt plot(lambda_reg_valuestest_rmse |
15,464 | introduction to machine learning and deep learning plt xlabel( "$\lambda$"plt ylabel("rmse"plt legend(["train""test"]loc plt show(we can compute the value of using the closed form (xtx li)- xty we illustrate keeping the degree fixed at value of and varying the value of in listing - the training rmse (seen dataand test rmse (unseen datais plotted in figure - figure - regularization we see that the test rmse reduces gradually to the minimum and then gradually increases as the model capacity increasesresulting in overfitting ummary this covered brief history of deep learning and introduced the foundations of machine learningincluding examples of supervised learning (classification and regressionthe key points for this |
15,465 | introduction to machine learning and deep learning are the concepts of generalizing over unseen examplesoverfitting and underfitting the training datathe capacity of the modeland the notion of regularization readers are encouraged to try out the examples in the source code listings in the next we will explore pytorch as foundational framework to develop deep learning models |
15,466 | introduction to pytorch the recent years have witnessed major releases of frameworks and tools to democratize deep learning to the masses todaywe have plethora of options at our disposal this aims to provide an overview of pytorch we will be using pytorch extensively throughout the book for implementing deep learning examples note that this is not comprehensive guide for pytorchso you should consult the additional materials suggested in the for deeper understanding of the framework basic overview will be offered and the necessary additions to the topic will be provided in the course of the examples implemented later in the book with no further adolet' get started by reviewing some of the broader questions you may have when considering pytorch hy do we need deep learning frameworkdeveloping deep neural network and preparing it to solve today' problems is quite herculean task there are too many pieces to connect and orchestrate in systematic flow to achieve the objectives we desire (cnikhil ketkarjojo moolayil ketkar and moolayildeep learning with python |
15,467 | introduction to pytorch with deep learning to enable easieracceleratedand quality solutions for experiments in research and productsenterprises require large amount of abstraction that can do the heavy lifting for ground tasks this would help researchers and developers focus on the tasks that matterrather than investing the bulk of their time on basic operations deep learning frameworks and platforms provide fair abstraction on the ground complex tasks with simple functions that can be used as tools for solving larger problems by researchers and developers few popular choices are keraspytorchtensorflowmxnetcaffemicrosoft' cntketc what is pytorchpytorch is an open source machine learning and deep learning library developed by facebookinc it is python-basedas its name suggestsand aims to provide faster alternative/replacement to numpy (used in this examplesby providing seamless use of gpus and platform for deep learning that provides maximum flexibility and speed why pytorchrecommending pytorch is easy it provides an extremely easy to useextenddevelopand debug framework because it is pythonicit is easy for the software engineering community to embrace it is equally easy for researchers and developers to get tasks done pytorch also makes it easy for deep learning models to be productionized it is equipped with highperformance +runtime that developers can leverage for production environments while avoiding inference via python for most users who are familiar with python' numpy packagepytorch will be even easier to transition to overallpytorch provides an excellent framework and platform for researchers and developers to work on cutting-edge deep |
15,468 | introduction to pytorch learning problems while focusing on the tasks that matter and be able to easily debugexperimentand deploy for the aforementioned reasonspytorch has seen wider adoption in enterprises if you follow the media around deep learningyou might have read articles that mention new large organization adopting pytorch yann lecuna profound researcher in deep learningprofessor at nyuand chief scientist at facebook (at the time this writingtweeted the following in nov "over of neurips' papers that mention using deep learning framework mention pytorch pytorch is dominant in deep learning research (ml/cv/nlp conferencesby wide margin with enough reasons to justify pytorch as worthy choice for deep learninglet' get started it all starts with tensor in generala task in deep learning would revolve around processing an imagetextor tabular data (cross-sectional as well as time-seriesto generate an outcome that is numberlabelmore textanother imageor combination of these simple examples include classifying an image as dog or catpredicting the next word in sentencegenerating captions for an imageor transforming an image with new style (saythe prisma app on ios/androideach of these tasks would need the underlying data to be stored in specific structure processing and developing these solutions will have several intermediate stageswhich will also need specific structure (for examplethe weights of neural networka common structure that could be universally used for storingrepresentingand transforming is tensor |
15,469 | introduction to pytorch tensor is nothing but multi-dimensional array of objects of the same type (usually floating-point numbersalthough bit of an oversimplificationit' fair to say that at lower level of abstractionall computation in pytorch is tensors and operations over tensors thusin order for you to be fluent with pytorchit is essential that you develop an intuitive understanding of tensors and the operations over them it must also be noted that this introduction to tensors and their operations is by no means completeyou should refer to the pytorch documentation for specific use cases howeverit' also essential to point out that this covers all the conceptual aspects of tensors and their operations you should try out the examples in this section in python terminal (jupyter notebook is recommended the best way to internalize this material is to read about the concepttype out the source codeand see it execute figure - - dimensional tensor tensor is generalized way of representing scalarvectorand matrices tensor can be defined as an -dimensional matrix -dimensional tensor ( single numberis called scalar (figure - ) -dimensional tensor is called vectora -dimensional tensor is called matrix -dimensional tensor is also called cubeetc the dimension of matrix is also called the rank of tensor |
15,470 | introduction to pytorch pytorch is very rich library that provides numerous functions that enable building blocks for deep learning this looks briefly at some of the functionalities pytorch provides for creating tensors and performing data munging operationslinear algebraand mathematical operations to beginlet' explore the multitude of ways to construct tensors the most basic way is to construct tensor using lists in python the following exercise will demonstrate an array of tensor operations that are commonly used in building deep learning applications to help you engage the flow betterthe codes and output have been maintained the notebook style (interactive flowinput output next input next output and so onc reating tensors in listing - we have constructed -dimensional tensor using nested lists we store this tensor as variable and then look at its shape listing - creating -dimensional tensor in [ ]import torch torch tensor([[ ],[ ]]out[ ]tensor([[ ][ ]]the shape indicates the dimensions of the tensor and the total number of dimensions that would be used to infer the rank of the tensor in listing - dimension [ , would be inferred as rank listing - explores the shape of tensor |
15,471 | introduction to pytorch listing - the shape of tensor in [ ] torch tensor([[ ],[ ]]in [ ] shape out[ ]torch size([ ]in [ ] out[ ]tensor([[ ][ ]]we can try out more examples with different shapes listing - explores tensors with different shapes listing - the shape of tensor (continuedin [ ] torch tensor([[ ],[ ],[ ]]in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]also note that we can have tensors of arbitrary dimensionsnot just two (as in the previous exampleslisting - shows the creation of tensors with three dimensions |
15,472 | introduction to pytorch listing - creating tensors with arbitrary dimensions in [ ] torch tensor([[[ ],[ ]],[[ ],[ ]]]in [ ] shape out[ ]torch size([ ]in [ ] out[ ]tensor([[[ ][ ]][[ ][ ]]]just as we can build tensors with python listswe can build tensors with numpy arrays this functionality can come in most handy when interfacing numpy code with pytorch listing - demonstrates creating tensors using numpy listing - creating tensors with numpy in [ ] torch tensor(numpy array([[ ],[ ]])in [ ] out[ ]tensor([[ ][ ]]dtype=torch float in [ ] shape out[ ]torch size([ ]we can also create tensor from an existing numpy -dimensional array using the from_numpy function listing - demonstrates the creation of tensors using pytorch' built-in function from_numpy to create tensors from numpy |
15,473 | introduction to pytorch listing - creating tensors from numpy import numpy as np np array([ ]tensor_a torch from_numpy(atensor_a output[tensor([ ]as we mentioned in the introductiontensors are multi-dimensional arrays of the same type we can specify the type when we construct tensor in the following exampleswe initialize the tensor with -bit floating point numbers -bit floating-point numbersand -bit floating point numbers pytorch defines total of eight types (consult the pytorch documentation for more details listing - demonstrates constructing tensors with few of the popular datatypes available in pytorch listing - defining tensor datatypes in [ ] torch tensor([[ ],[ ]]dtype=torch float in [ ] out[ ]tensor([[ ][ ]]in [ ] torch tensor([[ ],[ ]]dtype=torch float in [ ] out[ ]tensor([[ ][ ]]dtype=torch float |
15,474 | introduction to pytorch in [ ] torch tensor([[ ],[ ]]dtype=torch float in [ ] out[ ]tensor([[ ][ ]]dtype=torch float table - shows the different datatypes and their pytorch equivalents table - datatypes and their pytorch equivalents data type pytorch equivalent -bit floating point torch float or torch float -bit floating point torch float or torch double -bit floating point torch float or torch half -bit integer (unsignedtorch uint -bit integer (signedtorch int -bit integer (signedtorch int or torch short -bit integer (signedtorch int or torch int -bit integer (signedtorch int or torch long boolean torch bool let' now look at other ways in which tensors can be constructed common requirement is to construct tensor filled with random values listing - demonstrates the creation of tensor with defined shape having random values |
15,475 | introduction to pytorch listing - creating tensor with random values in [ ] torch rand( , , in [ ] out[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ] shape out[ ]torch size([ ]another common requirement is to construct tensor of zeros listing - demonstrates the creation of tensor with defined shape having all zeros listing - creating tensor having all zeros in [ ]zeros torch zeros( , , in [ ]zeros out[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ]zeros shape out[ ]torch size([ ]similarlywe can construct tensor of ones listing - demonstrates the creation of tensor with defined shape having all ones |
15,476 | introduction to pytorch listing - creating tensor having all ones in [ ]ones torch ones( , , in [ ]ones out[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ]ones shape out[ ]torch size([ ]another common requirement is the construction of identity matrices (tensorslisting - demonstrates the creation of an identity matrix tensor ( all diagonal elements as listing - creating an identity matix tensor in [ torch eye( in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]we can also construct tensor of an arbitrary shape filled with an arbitrary value listing - demonstrates the creation of tensor with an arbitrary value |
15,477 | introduction to pytorch listing - creating tensor filled with an arbitrary value in [ ] torch full(( , ) in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ] common use case is also to build tensors with linearly spaced floating-point numbers listing - demonstrates the creation of tensor with linearly spaced floating-point numbers listing - creating tensor with linearly spaced floating-point numbers in [ ]lin torch linspace( steps= in [ ]lin out[ ]tensor( ]similarlylisting - shows building tensor with logarithmically spaced floating-point numbers listing - creating tensor with logarithmically spaced floating-point numbers in [ ]log torch logspace(- steps= in [ ]log out[ ]tensor([ - - + + ] |
15,478 | introduction to pytorch sometimes we need to create tensors with dimensions similar to existing tensors the example in listing - illustrates this listing - creating tensor with dimensions similar to another tensor in [ ] torch tensor([[ ],[ ]]in [ ] torch zeros_like(ain [ ] out[ ]tensor([[ ][ ]]in [ ] torch ones_like(ain [ ] out[ ]tensor([[ ][ ]]so farwe have considered only floating-point numbers pytorch tensorshoweverare not limited to floating-point numbers here are few examples of constructing tensors with integers and longs as side notenotice that the dtype functions can be used to find the type of the objects the tensor comprises listing - demonstrates creating tensor with integer datatypes listing - creating tensor with integer datatypes in [ ] torch tensor([[ , ],[ , ]]in [ ] out[ ]tensor([[ ][ ]] |
15,479 | introduction to pytorch in [ ] dtype out[ ]torch int in [ ] torch tensor([[ , ],[ , ]]dtype=torch intin [ ] out[ ]tensor([[ ][ ]]dtype=torch int similarlylisting - shows the construction of tensor with range of integers listing - creating tensor with range of integers in [ ] torch arange( , step= in [ ] out[ ]tensor([ ]similarlywe can construct random permutation of integers in listing - we create tensor with random permutation of integers listing - creating tensor with random permutation of integers in [ ] torch randperm( in [ ] out[ ]tensor([ ] |
15,480 | introduction to pytorch tensor munging operations having looked at tensors and tensor construction operationslet' now dive deeper into operations with tensors we will start by looking at accessing individual elements of tensor the following example should be familiaras it is identical to the list indexing operator in python listing demonstrates accessing individual members of tensor listing - accessing individual members of tensor in [ ] torch tensor([[ , ],[ , ]]in [ ] out[ ]tensor([[ ][ ]]in [ ] [ ][ out[ ]tensor( in [ ] [ ][ out[ ]tensor( in [ ] [ ][ out[ ]tensor( in [ ] [ ][ out[ ]tensor( in [ ] shape out[ ]torch size([ ]to extract the data in tensor containing only single valuethe item method should be used listing - demonstrates accessing single value from tensor |
15,481 | introduction to pytorch listing - accessing single value from tensor in [ ] torch tensor([[[ ]]]in [ ] out[ ]tensor([[[ ]]]in [ ] shape out[ ]torch size([ ]in [ ] item(out[ ] the view method provides an easy way to reshape tensor essentiallythe values in tensor are allocated in contiguous blocks of memory the pytorch tensor is essentially just view over this continuous block multiple indexes can refer to the same storage and represent the tensor in different shapes listing - demonstrates simple example of reshaping tensor listing - reshaping tensor in [ ] torch zeros( in [ ] out[ ]tensor([ ]in [ ] shape out[ ]torch size([ ]in [ ] view( , in [ ] out[ ]tensor([[ ][ ]] |
15,482 | introduction to pytorch in [ ] shape out[ ]torch size([ ]it is important to note how (the order in which the elements are placedthe view method reshapes the tensor listing - demonstrates verifying the size of tensor after reshaping with the 'viewmethod listing - verifying the size of tensor after reshaping with view in [ ] torch arange( , in [ ] out[ ]tensor([ ]in [ ] shape out[ ]torch size([ ]in [ ] view( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]the cat operation allows you to concatenate list of tensors along given dimension note that the cat operation takes two parametersthe list of tensors to concatenate and the dimension along which to perform this operation listing - explores the concatenation of two tensors |
15,483 | introduction to pytorch listing - concatenating two tensors in [ ] torch zeros( , in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch cat([ , , ], in [ ] out[ ]tensor([[ ][ ][ ][ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch cat([ , , ], in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ] |
15,484 | introduction to pytorch the stack operation allows you to construct tensor by stacking list of tensors along dimension the resultant tensor will have its dimension increased by one listing - shows how the stacking operation operates along each dimension note that the stack operation takes two parametersthe list of tensors and the stacking dimension the range of dimension is equal to the range of the tensors to be stacked listing - stacking tensors in [ ] torch zeros( , in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch stack([ , , ] in [ ] out[ ]tensor([[[ ][ ]][[ ][ ]][[ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ] torch stack([ , , ] |
15,485 | introduction to pytorch in [ ] out[ ]tensor([[[ ][ ][ ]][[ ][ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ] torch stack([ , , ] in [ ] out[ ]tensor([[[ ]][[ ]]]in [ ] shape out[ ]torch size([ ]the chunk operation chops up tensor into the given number of parts along given direction note that the first parameter is the tensorthe second parameter is the number of partsand the third parameter is the direction along which to partition listing - demonstrates chunking tensors listing - chunking tensors in [ ] torch zeros( in [ ] out[ ] |
15,486 | introduction to pytorch tensor([[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch chunk( in [ ] out[ ](tensor([[ ][ ]])tensor([[ ][ ]])tensor([[ ][ ]])tensor([[ ][ ]])tensor([[ ][ ]])note that when the length of the tensor along the dimension on which partitioning is being performed is not multiple of the part sizethe last part has fewer elements than the part size listing - illustrates additional examples of chunking/chopping of tensors |
15,487 | introduction to pytorch listing - chunking tensors (continuedin [ ] torch chunk( in [ ] out[ ](tensor([[ ][ ][ ][ ]])tensor([[ ][ ][ ][ ]])tensor([[ ][ ]])just as the chunk method enables you to split tensor into the given number of partsthe split method does the same operation but given the size of the part note the difference basicallythe chunk method takes the number of partswhereas the split method takes the size of the part listing - illustrates splitting tensors listing - splitting tensors in [ ] torch zeros( , in [ ] out[ ]tensor([[ ][ ][ ][ ][ ] |
15,488 | introduction to pytorch [ ][ ][ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch split( , , in [ ] out[ ](tensor([[ ],[ ]])tensor([[ ],[ ]])tensor([[ ],[ ]])tensor([[ ],[ ]])tensor([[ ],[ ]])the index_select method allows you to extract parts of tensor along given dimension note that the method takes three argumentsthe tensor to operate onthe dimension along which to extract dataand the tensor containing the indices in listing - we construct tensorand then extract data along each of the two dimensions listing - extracting parts of tensors using index_select in [ ] torch floattensor([[ , ],[ ][ ]]in [ ] out[ ]tensor([[ ][ ][ ]] |
15,489 | introduction to pytorch in [ ] shape out[ ]torch size([ ]in [ ]index torch longtensor([ ]in [ ] torch index_select( indexin [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch index_select( indexin [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]the masked_select methodillustrated in listing - allows you to select elements given boolean mask listing - selecting elements from tensor using masked_ select in [ ] torch floattensor([[ , ],[ ][ ]]in [ ] out[ ]tensor([[ ] |
15,490 | introduction to pytorch [ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ]mask torch bytetensor([[ ],[ ],[ ]]in [ ]mask out[ ]tensor([[ ][ ][ ]]dtype=torch uint in [ ]mask shape out[ ]torch size([ ]in [ ] torch masked_select(amaskin [ ] out[ ]tensor([ ]in [ ] shape out[ ]torch size([ ]the squeeze method removes all dimensions with value of oneas illustrated in listing - listing - reshaping tensor with the squeeze method in [ ] torch zeros( , , in [ ] out[ ]tensor([[[ ][ ]] |
15,491 | introduction to pytorch [[ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ] squeeze(in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]similarlythe unsqueeze method adds new dimension with value of oneas illustrated in listing - note how the extra dimension could be added at three different positions listing - reshaping tensor with the unsqueeze method in [ ] torch zeros( , in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch unsqueeze( in [ ] out[ ] |
15,492 | introduction to pytorch tensor([[[ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ] torch unsqueeze( in [ ] out[ ]tensor([[[ ]][[ ]]]in [ ] shape out[ ]torch size([ ]in [ ] torch unsqueeze( in [ ] out[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ] shape out[ ]torch size([ ]the unbind function breaks up given tensor into separate tensors along given dimension listing - illustrates extracting parts of tensor using unbind tensor is broken along the first and second dimension note that the resultant tensors are returned as tuple |
15,493 | introduction to pytorch listing - extracting parts of tensor using unbind in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ]torch unbind( out[ ](tensor([ ])tensor([ ])tensor([ ])in [ ]torch unbind( out[ ](tensor([ ])tensor([ ])tensor([ ])listing - illustrates creating tensor from an existing tensor using the where method listing - constructing tensor from an existing tensor using the where method in [ ] torch zeros( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch ones( , |
15,494 | introduction to pytorch in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch where( abin [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]the any and all methodsillustrated in listing - enable you to check whether given condition is true in any or all casesrespectively |
15,495 | introduction to pytorch listing - conducting logical operations on tensors using the any and all methods in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ]torch any( out[ ]tensor( dtype=torch uint in [ ]torch any( out[ ]tensor( dtype=torch uint in [ ]torch all( out[ ]tensor( dtype=torch uint in [ ]torch all( out[ ]tensor( dtype=torch uint the view method allows you to reshape tensors listing - illustrates reshaping tensors note that using - as the size along some dimension implies that this is to be inferred based on the other sizes listing - reshaping tensors in [ ] torch arange( , in [ ] out[ ]tensor([ ]in [ ] view( , |
15,496 | introduction to pytorch in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] view( ,- in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]the flatten method can be used to collapse the dimensions of given tensor starting with particular dimension listing - demonstrates collapsing the dimensions of tensor using flatten listing - collapsing the dimensions of tensor using the flatten method in [ ] out[ ]tensor([[[[ ][ ]][[ ][ ]]] |
15,497 | introduction to pytorch [[[ ][ ]][[ ][ ]]]]in [ ] shape out[ ]torch size([ ]in [ ] torch flatten(ain [ ] out[ ]tensor([ ]in [ ] shape out[ ]torch size([ ]in [ ] torch flatten(astart_dim= in [ ] out[ ]tensor([ ]in [ ] shape out[ ]torch size([ ]in [ ] torch flatten(astart_dim= in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ] |
15,498 | introduction to pytorch in [ ] torch flatten(astart_dim= in [ ] out[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ] torch flatten(astart_dim= in [ ] out[ ]tensor([[[[ ][ ]][[ ][ ]]][[[ ][ ]][[ ][ ]]]]in [ ] shape out[ ]torch size([ ]the gather method allows us to extract values from tensor along given dimension at given positions listing - illustrates extracting values from tensor using gather |
15,499 | introduction to pytorch listing - extracting values from tensor using the gather method in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch longtensor([[ , , , ]]in [ ] out[ ]tensor([[ ]]in [ ] shape out[ ]torch size([ ]in [ ] gather( ,bin [ ] out[ ]tensor([[ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch longtensor([[ ],[ ],[ ],[ ]]in [ ] out[ ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.