id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
15,700 | recurrent neural networks figure - long short-term memory network practical implementation this section describes practical implementation of an rnn and lstm with pytorch we will divide the exercise into two parts firstwe will use just the vanilla rnn network with no additional processing (from the universe of nlpand train the network over sentiment classification dataset we would expect this vanilla network to perform poorly secondwe will make significant improvements to the network we will leverage lstm layers instead of rnn layers and make the network bidirectional with dropout regularization such network will perform much better on our dataset we will the torchtext packagewhich consists of data processing utilities and popular datasets for nlp we will leverage the dataset hosted on kaggle at |
15,701 | recurrent neural networks we recommend leveraging kaggle notebook for the exercise (with the internet option turned on and the gpu accelerator enabledlet' get started by importing the essential packages (listing - listing - importing the packages for the rnn import numpy as np linear algebra import pandas as pd data processingcsv file / ( pd read_csvimport torch from torch import nn,optim import torchtext from torchtext import data #check if we have gpu enabled if torch cuda is_available()device "cudaelsedevice "cpuprint("device =",deviceinput_data_path "/kaggle/input/imdb-dataset-sentimentanalysis-in-csv-format/firstlet' explore the dataset at high-level using pandas the objective here is to just have glimpse of the dataset for the remainder of the exercisewe will use torchtext-based wrapper for handling training and validation datasets within the realm of nlp listing - reads the data for our use case into memory |
15,702 | recurrent neural networks listing - reading data into memory #read the csv dataset using pandas df pd read_csv("/input/imdb-dataset-sentiment-analysis-incsv-format/train csv"print("df shape :\ ",df shapeprint("df label ",df label value_counts()df head(output[df shape ( df label namelabeldtypeint we have only two columns in the dataset"text,which contains the actual commentand "label,which contains the values (negativeand (positivethe distribution between positive and negative is fairly even nextwe will use the torchtext dataset wrappers that will help us to create an iterator-based dataset that streamlines the data processing tasks we need as illustrated in listing - we begin by defining the raw datatypes required to define our train and validation dataset |
15,703 | recurrent neural networks listing - defining the tokenizerfieldsand dataset for training and validation #define custom tokenizer my_tokenizer lambda :str(xsplit(#define fields for our input dataset text data field(sequential=truelowertrue,tokenize my_tokenizer,use_vocab=truelabel data field(sequential false,use_vocab false#define inut fields as list of tuples of fields trainval_fields [("text",text),("label",label)#contruct dataset train_dataval_data data tabulardataset splits(path input_data_pathtrain "train csv"validation "valid csv"format "csv"skip_header truefields trainval_fields#build vocabulary max_vocab_size text build_vocab(train_datamax_size max_vocab_size#define iterators for train and validation train_iterator data bucketiterator(train_datadevice device batch_size sort_key lambda :len( text,sort_within_batch false ,repeat false |
15,704 | recurrent neural networks val_iterator data bucketiterator(val_datadevice devicebatch_size sort_key lambda :len( textsort_within_batch false repeat falseprint(text vocab freqs most_common()[: ]output[[('the' )(' ' )('and' )('of' )('to' ('is' )('in' )(' ' )('this' )('that' )in listing - we processed couple of things that are necessary for our network for nlp use caseswe would need to tokenize and then numericalize the data as part of the text processing before using the data for the network training as you might have already guessedneural networks process only numeric data both of the aforementioned operations are neatly handled by pytorch internally we can provide an existing tokenizer--for examplespacy (an open source advanced nlp library)--and pytorch does the rest in this examplewe use custom simple one nextwe define the necessary fields (raw datafor our dataset the field class models common text-processing datatypes that can be represented by tensors alsoit holds vocab object that defines the vectors hosting the numerical representations of all words that would occur in the field our dataset has two columns"textand "label,the former being the plain english comments and the latter being numeric label ( / thuswe define text and label as two individual fields that represent our columns we add the parameter to define the tokenizing function that would be necessary on this fielda boolean flag to convert the text to lowercaseand boolean flag to indicate that the data within this field is sequential for the label fieldwe do not have sequential datahencewe set it to false |
15,705 | recurrent neural networks nextwe define our data fields list that would be required while creating the dataset this list represents each column within the dataset if we plan to not use particular column within this datasetwe would need to assign "noneto the column name when defining the list of columns we assign this list to the trainval_fields variable we then create tabulardataset object with the streamlined list of operations necessary on the data columns note that the splits(function does not actually split an existing dataset it should be used only when we already have individually separated datasets in the path nextwe need to build the vocabulary ( numericized representation of the unique words that appear in our field textthis step is very important and has several means of execution we can use pretrained word embedding to create vocabulary or we can custom-train one using pretrained one is simpleso we will use this in our next example we set the maximum number of vocabularies to , the function will also create two additional wordstaking the total to , --one for all the unknown tokens (for examplenew wordsand the other for padding (used to make sentences of equal lengthfinallywe create the iterator objects the sort_within_batch parameter sorts the data within each mini-batch in decreasing order according to the sort_key this is necessary when we want to use pack_ padded_sequence with the padded sequence data and convert the padded sequence tensor to packedsequence object we will not leverage this feature in our first exercisebut we will use it in the next exercisewhere we improve our model essentiallypytorch adds padding to the sequences such that all sequences are of equal length the process is made efficient by sorting the data in the decreasing order of the keyand ensures that the network does not learn the pads the last line prints the most frequent words in the vocab and returns the index associated with each word in the vector (embeddingwith the data ready to be processedwe will construct our rnn classas shown in listing - |
15,706 | recurrent neural networks listing - defining the rnn class class rnnmodel(nn module)def __init__(self,embedding_dim,input_dim,hidden_dimoutput_dim)super(__init__(self embedding nn embedding(input_dim,embedding_dimself rnn nn rnn(embedding_dim,hidden_dimself fc nn linear(hidden_dim,output_dimdef forward(self,text)embed self embedding(textoutputhidden self rnn(embedout self fc(hidden squeeze( )return(out#define model input_dim len(text vocabembedding_dim hidden_dim output_dim #create model instance model rnnmodel(embedding_diminput_dim,hidden_dimoutput_dima significant portion of this code is very comparable to our experiments in and the new additions here are the embedding layer and the rnn layer the rnn layer returns the output as well as the hidden layer computation (unlike the other layers we've explored so farthe input dimension is the length of our vocab list the embedding dimension is value that we decide would best represent word numerically we use herebut it could be or higher |
15,707 | recurrent neural networks higher number will not always be valuableand it increases computation load significantly alsowe select dimensions for our hidden layer and (since the outcome is binarydimension for our output layer nextin listing - we define two functions that will wrap the training step and evaluation step for given epoch laterwe orchestrate the training step and evaluation step for each epoch through another function listing - defining the training and evaluation step #define training step def train(modeldata_iterator,optimizer,loss_function)epoch_loss,epoch_acc,epoch_denom , , model train(#explicitly set model to train mode for ibatch in enumerate(data_iterator)optimizer zero_grad(predictions model(batch textloss loss_function(predictions reshape(- , )batch label float(reshape(- , )acc accuracy(predictions reshape(- , )batch label reshape(- , )loss backward(optimizer step(epoch_loss +loss item(epoch_acc +acc item(epoch_denom +len(batchreturn epoch_loss/epoch_denom,epoch_accepoch_denom #define evaluation step def evaluate(modeldata_iterator,loss_function)epoch_loss,epoch_acc,epoch_denom , , |
15,708 | recurrent neural networks model eval(#explcitly set model to eval mode for ibatch in enumerate(data_iterator)with torch no_grad()predictions model(batch textloss loss_function(predictions reshape(- , )batch label float(reshape(- , )acc accuracy(predictions reshape(- , )batch label reshape(- , )epoch_loss +loss item(epoch_acc +acc item(epoch_denom +len(batchreturn epoch_loss/epoch_denomepoch_accepoch_denom herethe contents are similar to the previous experiments we create the necessary boilerplate code for our training loop note that we need helper function within the evaluate function that would compute accuracy (binary outcomesin our casethis part is not mandatebut it helps to view intermediate results in accuracy after each epoch listing - defines the function and the necessary bits for our network listing - defining the accuracy functionloss functionand optimizerand instantiating the model #compute binary accuracy def accuracy(predsy)rounded_preds torch round(torch sigmoid(preds)#count the number of correctly predicted outcomes correct (rounded_preds =yfloat(acc correct sum(return acc |
15,709 | recurrent neural networks #define optimizerloss function optimizer torch optim adam(model parameters()lr= - criterion nn bcewithlogitsloss(#transfer components to gpuif available model model to(devicecriterion criterion to(devicefinallyin listing - we train the model instantiated above with the define loss functions and optimizer in loop for five epochs we define here for illustration purposes onlyfor practical examples we recommend increasing the number of epochs based on the size of data and complexity of the network listing - training the model for five epochs n_epochs for epoch in range(n_epochs)#train and evaluate train_losstrain_acc,train_num train(modeltrain_ iteratoroptimizercriterionvalid_lossvalid_acc,val_num evaluate(modelval_ iterator,criterionprint("epoch-",epochprint( '\ttrain loss{train_loss ftrain predicted correct {train_acctrain denom{train_numpercaccuracy{train_acc/train_num}'print( '\tvalid loss{valid_loss fvalid predicted correct{valid_accval denom{val_num}percaccuracy{train_acc/train_num}' |
15,710 | recurrent neural networks output[epoch - train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy epoch - train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy epoch - train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy epoch - train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy epoch - train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy we can see that model barely improved in performance although five epochs are actually too fewwe should have seen small changes the overall accuracy hasn' really added any value from the model the performance is poor to improve our resultswe will take more holistic approach in our second experiment |
15,711 | recurrent neural networks in our second experimentwe will leverage tokenizer from spacy (rather than using our custom tokenizerand pretrained word embedding (instead of training one from scratch)and add bidirectional lstm layers (instead of unidirectional rnn layerswe will also add dropout to reduce overfitting we actually need to start freshrather than continuing with the same code base (though the changes are minimalas usualwe begin by importing the required packagesas shown in listing - listing - importing the required packages import numpy as np linear algebra import pandas as pd data processingcsv file / ( pd read_csvimport torch,torchtext from torch import nnoptim from torch optim import adam from torchtext import data if torch cuda is_available()device "cudaelsedevice "cpuprint("device =",deviceinput_data_path /input/imdb-dataset-sentiment-analysis-incsv-format/#define fields for our input dataset text data field(sequential=truelowertrue,tokenize 'spacy'include_lengths truelabel data field(sequential false,use_vocab false |
15,712 | recurrent neural networks #define list of tuples of fields trainval_fields [("text",text),("label",label)#contruct dataset train_dataval_data data tabulardataset splits(path input_data_pathtrain "train csv"validation "valid csv"format "csv"skip_header truefields trainval_fields#build vocab using pretrained max_vocab_size text build_vocab(train_datamax_size max_vocab_ sizevectors 'fasttext simple 'batch_size train_iteratorval_iterator data bucketiterator splits(train_dataval_data)batch_size batch_sizesort_key lambda :len( text)sort_within_batch truedevice devicewe will focus only on the changes in the preceding code snippet while defining our data fieldswe used the tokenizer from spacy using the string spacy for the tokenize parameter sufficespytorch manages the necessary heavy lifting in the backend we also added the include_length parameter as true this is necessaryas we would add padding and sort the samples within batch later to leverage thiswe now need to pass the length of the sample along with the text to the forward function in our rnn model' class definition |
15,713 | recurrent neural networks while building the vocabularywe use vectors 'fasttext simple dto tell pytorch to download the pretrained fasttext vector and create an embedding vector for the words in our text field (if you are using kaggle kernelthe internet option should be turned on in the notebook environment settingsthis pretrained vector has dimensions we need to note this change while creating the network instance this step might actually take whiledepending on your internet speeds finallywe also enabled sorting and defined the sort key pytorch downloads the defined pretrained vectors (usually mn or moreand creates subset for our use case based on the , tokens let' now define our improved sequence modelas demonstrated in listing - listing - defining the (improvedrnn class class improvedrnn(nn module)def __init__(selfvocab_sizeembedding_dimhidden_dimoutput_dimn_layersbidirectionaldropoutpad_idx)super(__init__(self embedding nn embedding(vocab_sizeembedding_dimpadding_idx pad_idxself lstm nn lstm(embedding_dimhidden_dimnum_layers=n_layersbidirectional=bidirectionaldropout=dropoutself fc nn linear(hidden_dim output_dimself dropout nn dropout(dropout |
15,714 | recurrent neural networks def forward(selftexttext_lengths)embedded self dropout(self embedding(text)#pack sequence packed_embedded nn utils rnn pack_padded_ sequence(embeddedtext_lengthspacked_output(hiddencellself lstm(packed_ embedded#unpack sequence outputoutput_lengths nn utils rnn pad_packed_ sequence(packed_outputhidden self dropout(torch cat((hidden[- ,:,:]hidden[- ,:,:])dim )return self fc(hiddennotice that we have made quite few additions here we now have an lstm layer instead of the vanilla rnn when the bidirectional flag is set to trueit enables us to capture the forward as well backward context the dimensions of the linear layer would be now twice the original layeras we have both forward and backward network functioning in tandem we initially added include_lengths=true while defining our original fieldthereforeour forward function will now take one extra parameter this information is necessary while packing and unpacking the data after receiving from the embedding output and before passing it to the linear layer the hidden layer now concatenates the output from the forward as well as the backward network before passing it to the next layer listing - defines the model properties and copies the pretrained weights |
15,715 | recurrent neural networks listing - defining the model properties and copying the pretrained weights #define model input parameters input_dim len(text vocabembedding_dim hidden_dim output_dim n_layers bidirectional true dropout #create model instance model improvedrnn(input_dimembedding_dimhidden_dimoutput_dimn_layersbidirectionaldropoutpad_idx#copy pretrained vector weights model embedding weight data copy_(pretrained_embeddings#initialize the embedding with for pad as well as unknown tokens unk_idx text vocab stoi[text unk_tokenmodel embedding weight data[unk_idxtorch zeros(embedding_dimpad_idx text vocab stoi[text pad_tokenmodel embedding weight data[pad_idxtorch zeros(embedding_dimprint(model embedding weight data |
15,716 | recurrent neural networks output [torch size([ ]nextwe define the train and evaluate functionssimilar to our previous exercise the only difference is that we need to handle text_lengths as an additional parameter in the model we will also define the accuracy function required to compute the binary accuracy and define the model' loss functionoptimizer and load the model and the loss function on the gpuif available these steps are identical to our previous exercise in listing - we train our improved model definition listing - training the improved model #define train step def train(modeliteratoroptimizercriterion)epoch_loss,epoch_acc,epoch_denom , , model train(for batch in iteratoroptimizer zero_grad(texttext_lengths batch text predictions model(texttext_lengthssqueeze( loss criterion(predictions reshape(- , )batch label float(reshape(- , )acc accuracy(predictionsbatch labelloss backward(optimizer step(epoch_loss +loss item(epoch_acc +acc item(epoch_denom +len(batchreturn epoch_loss/epoch_denomepoch_accepoch_denom |
15,717 | recurrent neural networks #define evaluate step def evaluate(modeliteratorcriterion)epoch_loss,epoch_acc,epoch_denom , , model eval(with torch no_grad()for batch in iteratortexttext_lengths batch text predictions model(texttext_lengthssqueeze( loss criterion(predictionsbatch label float()acc accuracy(predictionsbatch labelepoch_loss +loss item(epoch_acc +acc item(epoch_denom +len(batchreturn epoch_loss/epoch_denomepoch_accepoch_denom #define optimizerloss funciton and load to gpu optimizer optim adam(model parameters()criterion nn bcewithlogitsloss(model model to(devicecriterion criterion to(device#similar to previous exercisewe deifne our accuracy function def accuracy(predsy)rounded_preds torch round(torch sigmoid(preds)correct (rounded_preds =yfloat(acc correct sum(return acc |
15,718 | recurrent neural networks #finally lets train our model for epochs n_epochs for epoch in range(n_epochs)train_losstrain_acc,train_num train(modeltrain_ iteratoroptimizercriterionvalid_lossvalid_acc,val_num evaluate(modelval_ iteratorcriterionprint("epoch-",epochprint( '\ttrain loss{train_loss ftrain predicted correct {train_acctrain denom{train_numpercaccuracy{train_acc/train_num}'print( '\tvalid loss{valid_loss fvalid predicted correct{valid_accval denom{val_num}percaccuracy{train_acc/train_num}'output[train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy epoch train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy |
15,719 | recurrent neural networks epoch train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy epoch train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy epoch train loss train predicted correct train denom percaccuracy valid loss valid predicted correct val denom percaccuracy as you can seethe performance has improved lot we trained the network for only five epochsyet the results are impressive readers are recommended to experiment by making changes to the network experiments could include changing the pretrained vectors (probably glove instead of fasttext)processing more nlp-related actions on the input dataadding more aggressive dropoutsadding more epochsetc this concludes our second exercisein which we tried to improve the performance of our sequence model we used the vanilla rnn networkslstm networksand bidirectional networks we also leveraged pretrained embeddings for numericized representations of words (this is highly recommended for almost all nlp-related tasks there also exists gated recurrent units (grus)which are very similar to lstms but which are slightly on the faster end of computationas they have fewer operations when it comes to performancehowevermost researchers have found both lstms and grus to be very similar in nlp experimentsit is very |
15,720 | recurrent neural networks common to iterate using lstms and grusand take the best you can read more about this research at discussing the details of grus is beyond the scope of this readers are encouraged to explore this topic further on their own ummary in this we covered the basics of recurrent neural networks (rnnsthe key takeaway points from this are the notion of the hidden statetraining rnns via unrolling (backpropagation through time)the problem of vanishing and exploding gradientsand long short-term memory (lstmnetworks it is important to internalize how rnns contain internal/hidden state that allow them to make predictions on sequence of inputs--an ability that goes beyond conventional neural networks |
15,721 | recent advances in deep learning so farthis book has discussed important topics in the realm of deep learningfeed-forward networksconvolutional neural networksand recurrent neural networks we described their practical aspectsincluding implementationtrainingvalidationand tuning models for improvement with pytorch although we covered lot of ground on the foundational aspectsthere are still vast areas that remain untouched the field of deep learning recently has witnessed huge spike in researchcontributorsand adoption in the industry for cutting-edge solutions the sheer velocity of updates and changes (both incremental and groundbreakingis colossal even since you have been reading this bookthere might have been several groundbreaking research papers published that tailor the next course in the field of deep learning in this concluding we introduce some additional topics relevant to deep learning that should help you study the topic in more meaningful way this serves only as brief introduction and does not dive into any implementation details you are recommended to explore additional resources related to these topics to strengthen the area that interests your academicpersonaland industry career let' get started (cnikhil ketkarjojo moolayil ketkar and moolayildeep learning with python |
15,722 | recent advances in deep learning oing beyond classification in computer vision in we studied computer vision problems within deep learning that are solved using convolutional neural networks this idea was novel and groundbreaking focused on only one key area-classification we studied the classic example of mnist handwritten digits wherein we classified given image as digits between - [ classesin another exercisewe looked at binary classification between cats and dogs although the ability to classify an image into meaningful label using computational techniques is indeed valuablegoing step further opens up several use cases that are of profound value to modern-day use cases this section explores few possibilities that open by extending the ideas within convolutional neural networks further bject detection object detectiona technology related to computer visionattempts to distinguish one or more objects within an image or video for examplein the classification exercise of cats vs dogsobject detection would go one step further and predict rectangular bounding box that best captures the object of interest in more sophisticated use caseobject detection could be used to detect several objects within an image/video figure - shows sophisticated object detection algorithm in action there are bounding boxes against each identified object to distinguish them from one another |
15,723 | recent advances in deep learning figure - object detection in computer vision image source the bounding boxes against each person (multiple people are identifiedare outcomes from object detection real-life use cases for object detection include identifying cars from cctv video streamthereby tracking traffic on important routesusing face-detection on smartphone so that the auto-focus can precisely focus on important objects for improved picturesand so forth image segmentation the next logical step in computer visionafter object detectionis image segmentation image segmentation is type of labeling where given image is partitioned into segments ( group of pixelsthat more precisely define the object the difference between image segmentation and object detection is the more precise definition of the object identified in |
15,724 | recent advances in deep learning the image under image segmentation that isinstead of rectangular bounding boxas in object detectionwe would have the actual pixel outline of the object (see figure - figure - image segmentation in computer vision image source instead of the bounding boxwe now have more granular outlines capturing the actual object practical applications of image segmentation include traffic surveillancemedical imagingportrait mode in smartphone cameras (digital mimicking of the bokeh effect--identifying the person to blur the backgroundmodern day smartphones implement semantic image segmentation-identifying objects within the image and further processing them based on the type of object identified for examplea face would be processed for beauty (smoothing blemishes/shadow/etc ) sky would be less focused with the addition of blur effectnature would be color-processed to have vibrant feeland so on |
15,725 | recent advances in deep learning to learn more about semantic image segmentationvisit developer apple com/videos/play/wwdc / ose estimation pose estimation is computer vision technique that predicts and tracks the location of person or object essentiallypose estimation predicts the body part or joint positions of person from an image or video using at combination of the pose and the orientation of given person/object more sophisticated version of pose estimation--and more difficult computer vision problem to solve--is multi-person pose estimation (see figure - figure - multi-person pose estimation image source github com/facebookresearch/detectron |
15,726 | recent advances in deep learning the practical applications of pose estimation are similar to image segmentation and object detectionalthough the applications for pose estimation are more meaningful and targeted--for exampletracking the activity of personsuch as runningcyclingetc activity tracking enables security surveillance to be taken to the next level another important application of pose estimation is related to the field of motion cinema and augmented reality translating motion capture from human into -dimensional graphical characterwhere the movements are precisely captured and translated (called vfxor vfx)is used often in motion cinema to learn more about pose estimationvisit tag/facial-pose-estimationgenerative computer vision beyond classificationobject detectionimage segmentationand pose estimationwe also have another hot field within computer vision-generative adversarial networks (gansgenerative models in computer vision first learn the distribution of the training set and then generate some new samples with small variation these new images are synthetically generated by the model using random noise and previously learned model weights in supervised setting figure - shows an example of image samples generated by gan models |
15,727 | recent advances in deep learning figure - gan-generated sample images the majority of the images look fairly realistic and identifiable--for examplehorseshipcaretc training gans has been difficult problem and often requires large computing resources producing larger size images increases the complexity even further nonethelesshowevergans have been one of the biggest developments in computer vision in recent times the acm turing aware laureate yann lecun described them as "the most interesting idea in the last years in machine learningthe practical applications of gans are limitless the easiest application would be product that renders images based on textual descriptions for exampletyping "design an image with busy street during day time with more people than cars on roadwould result in an image showing these things the reverse is also true-- inputting an image and receiving text-based natural language description about the image the technology company baidu designed prototype device that aids |
15,728 | recent advances in deep learning the blind with camera that describes surroundings in natural language to learn more about the prototypevisit watch? =xe rcj jy several emerging ecommerce enterprises are leveraging gans to design graphic tees for exampleprismaa popular photo-editing appand faceappa controversial yet intuitive app that can turn your existing photos into your older or younger selftook the internet by storm in deepfake videos are now (or soon will bea major problem on the internet deepfakes could produce almost realistic videos of celebrities speaking your input content with realistic speech and gestures atural language processing with deep learning discussed recurrent neural networks (rnnsand long shortterm memory (lstmnetworkswhich can be used to solve modern natural language processing (nlpproblems sequence models have also been very effective in speech recognition and related tasks within natural language processing recent years have seen phenomenal improvement with voice digital assistantssuch as apple' siri and amazon' alexa these assistants can now understand more languages and speech with regional influences and various accentsand respond with very realistic voice they also understand and distinguish your voice from someone else' voicealthough issues with accuracy still existof course in the early daysthese improvements were through lstm and gated recurrent units (grus)another variant similar to lstm lstm and gru models still have limitations they are computationally very expensive and process inputs sequentially the long-term dependencies problem still existsthough it is far better than with vanilla rnn |
15,729 | recent advances in deep learning transformer models in late google published its findings about the transformer networka groundbreaking deep learning model for nlp the paper "attention is all you need(shift in the research community for language models for whilernns were the best choice to process sequential data howeverthe sequential processing and comparatively poor performance on long-term dependencies brought various challenges to large nlp tasks the transformer network plays vital role in outperforming in such use cases transformer networks can train in parallelreducing the compute time by huge margin they are based on self-attention mechanism and dispense the recurrence and convolutions entirely (thusa faster computethe transformer model achieves bilingual evaluation understudy (bleuscore on the wmt english to-german translation taskimproving over the existing best resultsincluding ensemblesby more than two bleu idirectional encoder representations from transformers in year after publishing transformer networksresearchers at google ai language open sourced new technique for nlp called bidirectional encoder representations from transformers (bertbert relies on transformerbut with some variations vanilla transformer consists of an encoder and decoder architecturethe encoder reads the text inputwhile the decoder produces the prediction berthoweverleverages only the encoder part because bert' goal is to generate language representation modelthis is ideal one of unique differentiators of bert is its semi-supervised setting in this settingthe process first focuses on pretraining (unsupervised)where large |
15,730 | recent advances in deep learning corpus of text data (largely available over the internetis used for training language representation models nextthe model is trained and fine-tuned in supervised fashion for the specific use case of interest an example would the sentiment classification use case we explored in you can find more details about bert at com/ / /open-sourcing-bert-state-of-art-pre html bert uses two strategies for trainingmasked language modeling and next sentence prediction for masked language modelingwhile feeding word sequences into bertroughly of the words in each sequence are replaced with [masktoken the model then attempts to predict the original value of the masked words based on the context provided by the othernon-maskedwords in the sequence allennlp has released fun tool that uses bert in the backend (see simple demothe model predicted the word in [maskas car with probability figure - allennlp demo |
15,731 | recent advances in deep learning groknet the computer vision topics we have explored so far are all related to single-task learning that iswe specifically design network with one loss function and desired outcome--classifying an image into distinct categories modern problems in the digital age have more complex requirements that need more holistic approach consider an ecommerce marketplace when user uploads picture to list product for salethey might not add detailed and comprehensive description about the product in most casesthe uploader would add one-line description and broad category for the product (which might not be exactly trueto understand the problem betterconsider sample product listing for chair"nice sturdy chair for salejust year old and condition like new this user-drafted description lacks lot of information that might be ideal for buyer to make more informed decision informative attributes that would have been ideal for the buyer (as well as the marketplacewould include the color of the chairthe chair' make and modelthe year of manufactureetc from an engineering point of viewranking such product listing against user-based search query for the feed would be difficult taskas it might not match most of the relevant information fields solution to this problem would be augmenting additional information through several individual computer vision tasks--for exampleone task to classify the image into broad category (furnituretools/vehicles/books/etc )and then another model to classify with more specificity within vertical (make and model year)and so on there might also arise need to cater individual models for each vertical of products--for exampleapparelsfurniturebooksetc considering the wide range of possibilitieswe might often face the challenge of building and maintaining hundreds of distinct models considering the facebook marketplace as problemthe company released grokneta singleunified model with full coverage across all products with unified modelthe company has been able to reduce |
15,732 | recent advances in deep learning maintenance and computational cost and improve coverage by removing the need for separate model for each vertical application groknet leverages multi-task learning approach to train single computer vision trunk the model was trained over distinct datasets across several commerce verticalsusing categorical loss functions and embedding losses the final model predicts the following for given imageobject category"bar stool,"scarf,"area rug,etc home attributesobject colormaterialdecor styleetc fashion attributesstylecolormaterialsleeve lengthetc vehicle attributesmakemodelexternal colordecadeetc search queriestext phrases likely used by users to find the product on marketplace search image embeddinga -bit hash used to recognize exact productsfind and rank similar productsand improve search quality with such rich prediction for given imagea marketplace feed for given user' search results can be tailored and customized with highly relevant results the image embedding predicted can be further used to present similar product listings so that user can make more informed decision moreoverthis entire augmentation task is performed by single model rather than collection of models for more information about groknetvisit research/publications/groknet-unified-computer-vision-modeltrunk-and-embeddings-for-commerce |
15,733 | recent advances in deep learning additional noteworthy research this section describes few research publications relevant to the field of deep learning that are really exciting for folks to explore independently as next steps to advance in the field discussing any details for the research is beyond the scope of this bookso readers are encouraged to explore the following research papers independently jukeboxa generative model for music jukebox is neural network that generates musicincluding rudimentary singingas raw audio in variety of genres and artist styles openai released the model' weights and codealong with tool to explore the generated samples papercode image gpt generate coherent image completions transformer-based model trained on language can generate coherent text the same model trained on pixel sequences can generate coherent image completions and samples papergenerative_pretraining_from_pixels_v pdf code universal music translation network deep learning based method for translating music across musical instruments and styles the technique is based on unsupervised training of |
15,734 | recent advances in deep learning multi-domain wavenet autoencoderwith shared encoder and domain-independent latent space that is trained end-to-end on waveforms paper live face de-identification in video this method enables face de-identification in fully automatic setting for live videos at high frame rates using feed-forward encoder-decoder network architectureconditioned on the high-level representation of person' facial image paperc oncluding thoughts we would like you to thank youthe readerfor the time and interest you've taken to study the subject of deep learning by reading this book we sincerely appreciate your efforts invested in this book and hope that we have been able to deliver up to your expectations the subject of deep learning is so vast and dynamic that one would need to conduct continued research to keep up with the pace of the innovations our focus with this book has been to deliver healthy combination of abstract yet intuitive information on the subject (with minimal math operationsapologies if the equations were overwhelming)while blending the much-needed practical implementations with real-life datasets using the leading tool in industry and academia (pytorchwe would appreciate your thoughts and feedback |
15,735 | abs method activation functions hyperbolic tangent linear unit relu sigmoid activation softmax layer adaptive moment estimation (adam) addbmm function addmm function addmv function addr function allclose method area under the curve (auc) argmax method argmin method argsort function artificial intelligence (ai) autograd package automated feature engineering automatic differentiation composite functions computational graph - deep learning networks definition numerical pytorch symbolic backpropagation - backward(function baddbmm function batch gradient descent (bgd) batch normalization bidirectional encoder representations from transformers (bert) bilingual evaluation understudy (bleu) binary classification binary cross-entropy bmm function boolean flag ceil function chunk operation clamp function (cnikhil ketkarjojo moolayil ketkar and moolayildeep learning with python |
15,736 | mathematics important concepts statistics data mining artificial intelligence natural language processing deep learning important concepts machine learning methods supervised learning classification regression nsupervised learning lustering dimensionality reduction anomaly detection association rule-mining semi-supervised learning reinforcement learning batch learning online learning instance based learning model based learning the crisp-dm process model business understanding data understanding data preparation modeling evaluation deployment vi |
15,737 | building machine intelligence machine learning pipelines supervised machine learning pipeline unsupervised machine learning pipeline real-world case studypredicting student grant recommendations objective data retrieval data preparation modeling model evaluation model deployment prediction in action challenges in machine learning real-world applications of machine learning summary # the python machine learning ecosystem pythonan introduction strengths pitfalls setting up python environment why python for data science? introducing the python machine learning ecosystem jupyter notebooks numpy pandas scikit-learn neural networks and deep learning text analytics and natural language processing statsmodels summary vii |
15,738 | #part iithe machine learning pipeline # processingwranglingand visualizing data data collection sv json xml html and scraping sql ata description numeric text categorical ata wrangling nderstanding data filtering data typecasting transformations imputing missing values handling duplicates handling categorical data normalizing values string manipulations data summarization data visualization visualizing with pandas visualizing with matplotlib python visualization ecosystem summary viii |
15,739 | # feature engineering and selection featuresunderstand your data better data and datasets features models revisiting the machine learning pipeline feature extraction and engineering what is feature engineering? why feature engineering? how do you engineer features? feature engineering on numeric data raw measures binarization rounding interactions binning statistical transformations feature engineering on categorical data transforming nominal features transforming ordinal features encoding categorical features feature engineering on text data text pre-processing bag of words model bag of -grams model tf-idf model document similarity topic models word embeddings ix |
15,740 | feature engineering on temporal data date-based features time-based features feature engineering on image data image metadata features raw image and channel pixels grayscale image pixels binning image intensity distribution image aggregation statistics edge detection object detection localized feature extraction visual bag of words model automated feature engineering with deep learning feature scaling standardized scaling min-max scaling robust scaling feature selection threshold-based methods statistical methods recursive feature elimination model-based selection dimensionality reduction feature extraction with principal component analysis summary # buildingtuningand deploying models building models odel types learning model model building examples |
15,741 | odel evaluation evaluating classification models evaluating clustering models evaluating regression models odel tuning introduction to hyperparameters the bias-variance tradeoff cross validation hyperparameter tuning strategies odel interpretation nderstanding skater model interpretation in action odel deployment odel persistence custom development in-house model deployment model deployment as service ummary #part iiireal-world case studies # analyzing bike sharing trends the bike sharing dataset problem statement exploratory data analysis preprocessing distribution and trends outliers correlations xi |
15,742 | egression analysis types of regression assumptions evaluation criteria modeling linear regression decision tree based regression next steps summary # analyzing movie reviews sentiment problem statement setting up dependencies getting the data text pre-processing and normalization unsupervised lexicon-based models bing liu' lexicon mpqa subjectivity lexicon pattern lexicon afinn lexicon sentiwordnet lexicon vader lexicon classifying sentiment with supervised learning traditional supervised machine learning models newer supervised deep learning models advanced supervised deep learning models analyzing sentiment causation interpreting predictive models analyzing topic models ummary xii |
15,743 | # customer segmentation and effective cross selling online retail transactions dataset exploratory data analysis customer segmentation bjectives strategies clustering strategy cross selling market basket analysis with association rule-mining association rule-mining basics association rule-mining in action summary # analyzing wine types and quality problem statement setting up dependencies getting the data exploratory data analysis process and merge datasets understanding dataset features descriptive statistics inferential statistics univariate analysis multivariate analysis predictive modeling predicting wine types predicting wine quality summary xiii |
15,744 | # analyzing music trends and recommendations the million song dataset taste profile exploratory data analysis loading and trimming data enhancing the data visual analysis ecommendation engines types of recommendation engines utility of recommendation engines popularity-based recommendation engine item similarity based recommendation engine matrix factorization based recommendation engine note on recommendation engine libraries summary # forecasting stock and commodity prices time series data and analysis time series components smoothing techniques forecasting gold price problem statement dataset traditional approaches modeling stock price prediction problem statement dataset recurrent neural networkslstm upcoming techniquesprophet ummary xiv |
15,745 | # deep learning for computer vision convolutional neural networks image classification with cnns problem statement dataset cnn based deep learning classifier from scratch cnn based deep learning classifier with pretrained models artistic style transfer with cnns ackground preprocessing loss functions custom optimizer style transfer in action ummary index xv |
15,746 | dipanjan sarkar is data scientist at intelon mission to make the world more connected and productive he primarily works on data scienceanalyticsbusiness intelligenceapplication developmentand building large-scale intelligent systems he holds master of technology degree in information technology with specializations in data science and software engineering from the international institute of information technologybangalore he is also an avid supporter of self-learningespecially massive open online courses and also holds data science specialization from johns hopkins university on coursera dipanjan has been an analytics practitioner for several yearsspecializing in statisticalpredictiveand text analytics having passion for data science and educationhe is data science mentor at springboardhelping people up-skill on areas like data science and machine learning dipanjan has also authored several books on rpythonmachine learningand analyticsincluding text analytics with pythonapress besides thishe occasionally reviews technical books and acts as course beta tester for coursera dipanjan' interests include learning about new technologyfinancial marketsdisruptive start-upsdata scienceand more recentlyartificial intelligence and deep learning raghav bali is data scientist at intelenabling proactive and data-driven it initiatives he primarily works on data scienceanalyticsbusiness intelligenceand development of scalable machine learning-based solutions he has also worked in domains such as erp and finance with some of the leading organizations in the world raghav has master' degree (gold medalistin information technology from international institute of information technologybangalore raghav is technology enthusiast who loves reading and playing around with new gadgets and technologies he has also authored several books on rmachine learningand analytics he is shutterbugcapturing moments when he isn' busy solving problems xvii |
15,747 | tushar sharma has master' degree from international institute of information technologybangalore he works as data scientist with intel his work involves developing analytical solutions at scale using enormous volumes of infrastructure data in his previous rolehe worked in the financial domain developing scalable machine learning solutions for major financial organizations he is proficient in pythonrand big data frameworks like spark and hadoop apart from worktushar enjoys watching moviesplaying badmintonand is an avid reader he has also authored book on and social media analytics xviii |
15,748 | jojo moolayil is an artificial intelligence professional and published author of the booksmarter decisions the intersection of iot and decision science with over five years of industrial experience in machine learningdecision scienceand iothe has worked with industry leaders on high impact and critical projects across multiple verticals he is currently working with general electricthe pioneer and leader in data science for industrial iotand lives in bengaluru--the silicon valley of india he was born and raised in puneindia and graduated from university of pune with major in information technology engineering he started his career with mu sigma inc the world' largest pure play analytics provider and then fluturaan iot analytics startup he has also worked with the leaders of many fortune clients in his present role with general electriche focuses on solving and decision science problems for industrial iot use cases and developing data science products and platforms for industrial iot apart from authoring books on decision science and iotjojo has also been technical reviewer for various books on machine learning and business analytics with apress he is an active data science tutor and maintains blog at you can reach out to jojo ati would like to thank my familyfriendsand mentors for their kind support and constant motivation throughout my life --jojo john moolayil xix |
15,749 | this book would have definitely not been reality without the help and support from some excellent people and organizations that have helped us along this journey first and foremosta big thank you to all our readers for not only reading our books but also supporting us with valuable feedback and insights trulywe have learnt lot from all of you and still continue to do so we would like to acknowledge the entire team at apress for working tirelessly behind the scenes to create and publish quality content for everyone big shout-out goes to the entire python developer communityespecially to the developers of frameworks like numpyscipyscikit-learnspacynltkpandasstatsmodelskerasand tensorflow thanks also to organizations like anacondafor making the lives of data scientists easier and for fostering an amazing ecosystem around data science and machine learning that has been growing exponentially with time we also thank our friendscolleaguesteachersmanagersand well-wishers for supporting us with excellent challengesstrong motivationand good thoughts special mention goes to ram varra for not only being great mentor and guide to usbut also teaching us how to leverage data science as an effective tool from technical aspects as well as from the business and domain perspectives for adding real impact and value we would also like to express our gratitude to our managers and mentorsboth past and presentincluding nagendra venkateshsanjeev reddytamoghna ghosh and sailaja parthasarathy lot of the content in this book wouldn' have been possible without the help from several people and some excellent resources we would like to thank christopher olah for providing some excellent depictions and explanation for lstm models (depiction for lstm models in his blog (excellent pointers on feature engineering techniquesian london for his resources on the visual bag of words model (ian swansonand aaron kramerfor helping us cover lot of ground in model interpretation with skater (information pertaining to wine quality analysis (amazing content especially with regard to time series analysis and recommendation enginesamar lalwani for giving us some vital inputs around time series forecasting with deep learningharish narayanan for an excellent article on neural style transfer (not the leastfrancois chollet for creating keras and writing an excellent book on deep learning would also like to acknowledge and express my gratitude to my parentsdigbijoy and sampamy partner durba and my family and well-wishers for their constant lovesupportand encouragement that drive me to strive to achieve more special thanks to my fellow colleaguesfriendsand co-authors raghav and tushar for slogging many days and nights with me and making this experience worthwhilefinallyonce again would like to thank the entire team at apressespecially sanchita mandalcelestin johnmatthew moodieand our technical reviewerjojo moolayilfor being part of this wonderful journey --dipanjan sarkar xxi |
15,750 | am indebted to my familyteachersfriendscolleaguesand mentors who have inspired and encouraged me over the years would also like to take this opportunity to thank my co-authors and good friends dipanjan sarkar and tushar sharmayou guys are amazing special thanks to sanchita mandalcelestin johnmatthew moodieand apress for the opportunity and supportand last but not the leastthank you to jojo moolayil for the feedback and reviews --raghav bali would like to express my gratitude to my familyteachersand friends who have encouragedsupportedand taught me over the years special thanks to my classmatesfriendsand colleaguesdipanjan sarkar and raghav balifor co-authoring and making this journey wonderful through their valuable inputs and eye for detail would also like to thank matthew moodiesanchita mandalcelestin johnand apress for the opportunity and their support throughout the journey special thanks to the reviews and comments provided by jojo moolayil --tushar sharma xxii |
15,751 | the availability of affordable compute power enabled by moore' law has been enabling rapid advances in machine learning solutions and driving adoption across diverse segments of the industry the ability to learn complex models underlying the real-world processes from observed (trainingdata through systemiceasy-to-apply machine learning solution stacks has been of tremendous attraction to businesses to harness meaningful business value the appeal and opportunities of machine learning have resulted in the availability of many resources--bookstutorialsonline trainingand courses for solution developersanalystsengineersand scientists to learn the algorithms and implement platforms and methodologies it is not uncommon for someone just starting out to get overwhelmed by the abundance of the material in additionnot following structured workflow might not yield consistent and relevant results with machine learning solutions key requirements for building robust machine learning applications and getting consistentactionable results involve investing significant time and effort in understanding the objectives and key value of the projectestablishing robust data pipelinesanalyzing and visualizing dataand feature engineeringselectionand modeling the iterative nature of these projects involves several select apply validate tune cycles before coming up with suitable machine learning-based model final and important step is to integrate the solution (machine learning modelinto existing (or neworganization systems or business processes to sustain actionable and relevant results hencethe broad requirements of the ingredients for robust machine learning solution require development platform that is suited not just for interactive modeling of machine learningbut also excels in data ingestionprocessingvisualizationsystems integrationand strong ecosystem support for runtime deployment and maintenance python is an excellent choice of language because it fits the need of the hour with its multi-purpose capabilitiesease of implementation and integrationactive developer communityand ever-growing machine learning ecosystemleading to its adoption for machine learning growing rapidly the authors of this book have leveraged their hands-on experience with solving real-world problems using python and its machine learning ecosystem to help the readers gain the solid knowledge needed to apply essential conceptsmethodologiestoolsand techniques for solving their own real-world problems and use-cases practical machine learning with python aims to cater to readers with varying skill levels ranging from beginners to experts and enable them in structuring and building practical machine learning solutions --ram varrasenior principal engineerintel xxiii |
15,752 | data is the new oil and machine learning is powerful concept and framework for making the best out of it in this age of automation and intelligent systemsit is hardly surprise that machine learning and data science are some of the top buzz words the tremendous interest and renewed investments in the field of data science across industriesenterprisesand domains are clear indicators of its enormous potential intelligent systems and data-driven organizations are becoming reality and the advancements in tools and techniques is only helping it expand further with data being of paramount importancethere has never been higher demand for machine learning and data science practitioners than there is now indeedthe world is facing shortage of data scientists it' been coined "the sexiest job in the st centurywhich makes it all the more worthwhile to try to build some valuable expertise in this domain practical machine learning with python is problem solver' guide to building real-world intelligent systems it follows comprehensive three-tiered approach packed with conceptsmethodologieshands-on examplesand code this book helps its readers master the essential skills needed to recognize and solve complex problems with machine learning and deep learning by following data-driven mindset using real-world case studies that leverage the popular python machine learning ecosystemthis book is your perfect companion for learning the art and science of machine learning to become successful practitioner the conceptstechniquestoolsframeworksand methodologies used in this book will teach you how to thinkdesignbuildand execute machine learning systems and projects successfully this book will get you started on the ways to leverage the python machine learning ecosystem with its diverse set of frameworks and libraries the three-tiered approach of this book starts by focusing on building strong foundation around the basics of machine learning and relevant tools and frameworksthe next part emphasizes the core processes around building machine learning pipelinesand the final part leverages this knowledge on solving some real-world case studies from diverse domainsincluding retailtransportationmoviesmusiccomputer visionartand finance we also cover wide range of machine learning modelsincluding regressionclassificationforecastingrule-miningand clustering this book also touches on cutting edge methodologies and research from the field of deep learningincluding concepts like transfer learning and case studies relevant to computer visionincluding image classification and neural style transfer each consists of detailed concepts with complete hands-on examplescodeand detailed discussions the main intent of this book is to give wide range of readers--including it professionalsanalystsdevelopersdata scientistsengineersand graduate students-- structured approach to gaining essential skills pertaining to machine learning and enough knowledge about leveraging state-of-the-art machine learning techniques and frameworks so that they can start solving their own real-world problems this book is application-focusedso it' not replacement for gaining deep conceptual and theoretical knowledge about machine learning algorithmsmethodsand their internal implementations we strongly recommend you supplement the practical knowledge gained through this book with some standard books on data miningstatistical analysisand theoretical aspects of machine learning algorithms and methods to gain deeper insights into the world of machine learning xxv |
15,753 | understanding machine learning |
15,754 | machine learning basics the idea of making intelligentsentientand self-aware machines is not something that suddenly came into existence in the last few years in fact lot of lore from greek mythology talks about intelligent machines and inventions having self-awareness and intelligence of their own the origins and the evolution of the computer have been really revolutionary over period of several centuriesstarting from the basic abacus and its descendant the slide rule in the th century to the first general purpose computer designed by charles babbage in the in factonce computers started evolving with the invention of the analytical engine by babbage and the first computer programwhich was written by ada lovelace in people started wondering and contemplating that could there be time when computers or machines truly become intelligent and start thinking for themselves in factthe renowned computer scientistalan turingwas highly influential in the development of theoretical computer sciencealgorithmsand formal language and addressed concepts like artificial intelligence and machine learning as early as the this brief insight into the evolution of making machines learn is just to give you an idea of something that has been out there since centuries but has recently started gaining lot of attention and focus with faster computersbetter processingbetter computation powerand more storagewe have been living in what like to callthe "age of informationor the "age of dataday in and day outwe deal with managing big data and building intelligent systems by using concepts and methodologies from data scienceartificial intelligencedata miningand machine learning of coursemost of you must have heard many of the terms just mentioned and come across sayings like "data is the new oilthe main challenge that businesses and organizations have embarked on in the last decade is to use approaches to try to make sense of all the data that they have and use valuable information and insights from it in order to make better decisions indeed with great advancements in technologyincluding availability of cheap and massive computinghardware (including gpusand storagewe have seen thriving ecosystem built around domains like artificial intelligencemachine learningand most recently deep learning researchersdevelopersdata scientistsand engineers are working continuously round the clock to research and build toolsframeworksalgorithmstechniquesand methodologies to build intelligent models and systems that can predict eventsautomate tasksperform complex analysesdetect anomaliesself-heal failuresand even understand and respond to human inputs this follows structured approach to cover various conceptsmethodologiesand ideas associated with machine learning the core idea is to give you enough background on why we need machine learningthe fundamental building blocks of machine learningand what machine learning offers us presently this will enable you to learn about how best you can leverage machine learning to get the maximum from your data since this is book on practical machine learningwhile we will be focused on specific use casesproblemsand real-world case studies in subsequent it is extremely important to understand formal definitionsconceptsand foundations with regard to learning algorithmsdata managementmodel buildingevaluationand deployment hencewe cover all these aspectsincluding industry standards related to data mining and machine learning workflowsso that it gives you foundational framework that can be applied to approach and tackle any of the real-world problems we solve (cdipanjan sarkarraghav bali and tushar sharma sarkar et al practical machine learning with python |
15,755 | in subsequent besides thiswe also cover the different inter-disciplinary fields associated with machine learningwhich are in fact related fields all under the umbrella of artificial intelligence this book is more focused on applied or practical machine learninghence the major focus in most of the will be the application of machine learning techniques and algorithms to solve real-world problems hence some level of proficiency in basic mathematicsstatisticsand machine learning would be beneficial however since this book takes into account the varying levels of expertise for various readersthis foundational along with other in part and ii will get you up to speed on the key aspects of machine learning and building machine learning pipelines if you are already familiar with the basic concepts relevant to machine learning and its significanceyou can quickly skim through this and head over to "the python machine learning ecosystem,where we discuss the benefits of python for building machine learning systems and the major tools and frameworks typically used to solve machine learning problems this book heavily emphasizes learning by doing with lot of code snippetsexamplesand multiple case studies we leverage python and depict all our examples with relevant code files pyand jupyter notebooks ipynbfor more interactive experience we encourage you to refer to the github repository for this book at necessary code and datasets pertaining to each you can leverage this repository to try all the examples by yourself as you go through the book and adopt them in solving your own real-world problems bonus content relevant to machine learning and deep learning will also be shared in the futureso keep watching that spacethe need for machine learning human beings are perhaps the most advanced and intelligent lifeform on this planet at the moment we can thinkreasonbuildevaluateand solve complex problems the human brain is still something we ourselves haven' figured out completely and hence artificial intelligence is still something that' not surpassed human intelligence in several aspects thus you might get pressing question in mind as to why do we really need machine learningwhat is the need to go out of our way to spend time and effort to make machines learn and be intelligentthe answer can be summed up in simple sentence"to make data-driven decisions at scalewe will dive into details to explain this sentence in the following sections making data-driven decisions getting key information or insights from data is the key reason businesses and organizations invest heavily in good workforce as well as newer paradigms and domains like machine learning and artificial intelligence the idea of data-driven decisions is not new fields like operations researchstatisticsand management information systems have existed for decades and attempt to bring efficiency to any business or organization by using data and analytics to make data-driven decisions the art and science of leveraging your data to get actionable insights and make better decisions is known as making data-driven decisions of coursethis is easier said than done because rarely can we directly use raw data to make any insightful decisions another important aspect of this problem is that often we use the power of reasoning or intuition to try to make decisions based on what we have learned over period of time and on the job our brain is an extremely powerful device that helps us do so consider problems like understanding what your fellow colleagues or friends are speakingrecognizing people in imagesdeciding whether to approve or reject business transactionand so on while we can solve these problems almost involuntarycan you explain someone the process of how you solved each of these problemsmaybe to some extentbut after while |
15,756 | it would be like"heymy brain did most of the thinking for me!this is exactly why it is difficult to make machines learn to solve these problems like regular computational programs like computing loan interest or tax rebates solutions to problems that cannot be programmed inherently need different approach where we use the data itself to drive decisions instead of using programmable logicrulesor code to make these decisions we discuss this further in future sections efficiency and scale while getting insights and making decisions driven by data are of paramount importanceit also needs to be done with efficiency and at scale the key idea of using techniques from machine learning or artificial intelligence is to automate processes or tasks by learning specific patterns from the data we all want computers or machines to tell us when stock might rise or fallwhether an image is of computer or televisionwhether our product placement and offers are the bestdetermine shopping price trendsdetect failures or outages before they occurand the list just goes onwhile human intelligence and expertise is something that we definitely can' do withoutwe need to solve real-world problems at huge scale with efficiency real-world problem at scale consider the following real-world problem you are the manager of world-class infrastructure team for the dss company that provides data science services in the form of cloud based infrastructure and analytical platforms for other businesses and consumers being provider of services and infrastructureyou want your infrastructure to be top-notch and robust to failures and outages considering you are starting out of st louis in small officeyou have good grasp over monitoring all your network devices including routersswitchesfirewallsand load balancers regularly with your team of experienced employees soon you make breakthrough with providing cloud based deep learning services and gpus for development and earn huge profits howevernow you keep getting more and more customers the time has come for expanding your base to offices in san francisconew yorkand boston you have huge connected infrastructure now with hundreds of network devices in each buildinghow will you manage your infrastructure at scale nowdo you hire more manpower for each office or do you try to leverage machine learning to deal with tasks like outage predictionauto-recoveryand device monitoringthink about this for some time from both an engineer as well as manager' point of view traditional programming paradigm computerswhile being extremely sophisticated and complex devicesare just another version of our well known idiot boxthe television"how can that be?is very valid question at this point let' consider television or even one of the so-called smart tvswhich are available these days in theory as well as in practicethe tv will do whatever you program it to do it will show you the channels you want to seerecord the shows you want to view later onand play the applications you want to playthe computer has been doing the exact same thing but in different way traditional programming paradigms basically involve the user or programmer to write set of instructions or operations using code that makes the computer perform specific computations on data to give the desired results figure - depicts typical workflow for traditional programming paradigms |
15,757 | figure - traditional programming paradigm from figure - you can get the idea that the core inputs that are given to the computer are data and one or more programs that are basically code written with the help of programming languagesuch as high-level languages like javapythonor low-level like or even assembly programs enable computers to work on dataperform computationsand generate output task that can be performed really well with traditional programming paradigms is computing your annual tax nowlet' think about the real-world infrastructure problem we discussed in the previous section for dss company do you think traditional programming approach might be able to solve this problemwellit could to some extent we might be able to tap in to the device data and event streams and logs and access various device attributes like usage levelssignal strengthincoming and outgoing connectionsmemory and processor usage levelserror logs and eventsand so on we could then use the domain knowledge of our network and infrastructure experts in our teams and set up some event monitoring systems based on specific decisions and rules based on these data attributes this would give us what we could call as rule-based reactive analytical solution where we can monitor devicesobserve if any specific anomalies or outages occurand then take necessary action to quickly resolve any potential issues we might also have to hire some support and operations staff to continuously monitor and resolve issues as needed howeverthere is still pressing problem of trying to prevent as many outages or issues as possible before they actually take place can machine learning help us in some waywhy machine learningwe will now address the question that started this discussion of why we need machine learning considering what you have learned so farwhile the traditional programming paradigm is quite good and human intelligence and domain expertise is definitely an important factor in making data-driven decisionswe need machine learning to make faster and better decisions the machine learning paradigm tries to take into account data and expected outputs or results if any and uses the computer to build the programwhich is also known as model this program or model can then be used in the future to make necessary decisions and give expected outputs from new inputs figure - shows how the machine learning paradigm is similar yet different from traditional programming paradigms |
15,758 | figure - machine learning paradigm figure - reinforces the fact that in the machine learning paradigmthe machinein this context the computertries to use input data and expected outputs to try to learn inherent patterns in the data that would ultimately help in building model analogous to computer programwhich would help in making data-driven decisions in the future (predict or tell us the outputfor new input data points by using the learned knowledge from previous data points (its knowledge or experienceyou might start to see the benefit in this we would not need hand-coded rulescomplex flowchartscase and if-then conditionsand other criteria that are typically used to build any decision making system or decision support system the basic idea is to use machine learning to make insightful decisions this will be clearer once we discuss our real-world problem of managing infrastructure for dss company in the traditional programming approachwe talked about hiring new staffsetting up rule-based monitoring systemsand so on if we were to use machine learning paradigm shift herewe could go about solving the problem using the following steps leverage device data and logs and make sure we have enough historical data in some data store (databaselogsor flat filesdecide key data attributes that could be useful for building model this could be device usagelogsmemoryprocessorconnectionsline strengthlinksand so on observe and capture device attributes and their behavior over various time periods that would include normal device behavior and anomalous device behavior or outages these outcomes would be your outputs and device data would be your inputs feed these input and output pairs to any specific machine learning algorithm in your computer and build model that learns inherent device patterns and observes the corresponding output or outcome deploy this model such that for newer values of device attributes it can predict if specific device is behaving normally or it might cause potential outage thus once you are able to build machine learning modelyou can easily deploy it and build an intelligent system around it such that you can not only monitor devices reactively but you would be able to proactively identify potential problems and even fix them before any issues crop up imagine building self-heal or auto-heal systems coupled with round the clock device monitoring the possibilities are indeed endless and you will not have to keep on hiring new staff every time you expand your office or buy new infrastructure of coursethe workflow discussed earlier with the series of steps needed for building machine learning model is much more complex than how it has been portrayedbut again this is just to emphasize and make you think more conceptually rather than technically of how the paradigm has shifted in case |
15,759 | of machine learning processes and you need to change your thinking too from the traditional based approaches toward being more data-driven the beauty of machine learning is that it is never domain constrained and you can use techniques to solve problems spanning multiple domainsbusinessesand industries alsoas depicted in figure - you always do not need output data points to build modelsometimes input data is sufficient (or rather output data might not be presentfor techniques more suited toward unsupervised learning (which we will discuss in depth later on in this simple example is trying to determine customer shopping patterns by looking at the grocery items they typically buy together in store based on past transactional data in the next sectionwe take deeper dive toward understanding machine learning understanding machine learning by nowyou have seen how typical real-world problem suitable to solve using machine learning might look like besides thisyou have also got good grasp over the basics of traditional programming and machine learning paradigms in this sectionwe discuss machine learning in more detail to be more specificwe will look at machine learning from conceptual as well as domain-specific standpoint machine learning came into prominence perhaps in the when researchers and scientists started giving it more prominence as sub-field of artificial intelligence (aisuch that techniques borrow concepts from aiprobabilityand statisticswhich perform far better compared to using fixed rule-based models requiring lot of manual time and effort of courseas we have pointed out earliermachine learning didn' just come out of nowhere in the it is multi-disciplinary field that has gradually evolved over time and is still evolving as we speak brief mention of history of evolution would be really helpful to get an idea of the various concepts and techniques that have been involved in the development of machine learning and ai you could say that it started off in the late and the early when the first works of research were published which basically talked about the bayestheorem in fact thomas bayesmajor work"an essay towards solving problem in the doctrine of chances,was published in besides thisa lot of research and discovery was done during this time in the field of probability and mathematics this paved the way for more ground breaking research and inventions in the th centurywhich included markov chains by andrey markov in the early sproposition of learning system by alan turingand the invention of the very famous perceptron by frank rosenblatt in the many of you might know that neural networks had several highs and lows since the and they finally came back to prominence in the with the discovery of backpropagation (thanks to rumelharthintonand williams!and several other inventionsincluding hopfield networksneocognitionconvolutional and recurrent neural networksand -learning of courserapid strides of evolution started taking place in machine learning too since the with the discovery of random forestssupport vector machineslong short-term memory networks (lstms)and development and release of frameworks in both machine and deep learning including torchtheanotensorflowscikit-learnand so on we also saw the rise of intelligent systems including ibm watsondeepfaceand alphago indeed the journey has been quite roller coaster ride and there' still miles to go in this journey take moment and reflect on this evolutional journey and let' talk about the purpose of this journey why and when should we really make machines learnwhy make machines learnwe have discussed fair bit about why we need machine learning in previous section when we address the issue of trying to leverage data to make data-driven decisions at scale using learning algorithms without focusing too much on manual efforts and fixed rule-based systems in this sectionwe discuss in more detail why and when should we make machines learn there are several real-world tasks and problems that humansbusinessesand organizations try to solve day in and day out for our benefit there are several scenarios when it might be beneficial to make machines learn and some of them are mentioned as follows |
15,760 | lack of sufficient human expertise in domain ( simulating navigations in unknown territories or even spatial planetsscenarios and behavior can keep changing over time ( availability of infrastructure in an organizationnetwork connectivityand so onhumans have sufficient expertise in the domain but it is extremely difficult to formally explain or translate this expertise into computational tasks ( speech recognitiontranslationscene recognitioncognitive tasksand so onaddressing domain specific problems at scale with huge volumes of data with too many complex conditions and constraints the previously mentioned scenarios are just several examples where making machines learn would be more effective than investing timeeffortand money in trying to build sub-par intelligent systems that might be limited in scopecoverageperformanceand intelligence we as humans and domain experts already have enough knowledge about the world and our respective domainswhich can be objectivesubjectiveand sometimes even intuitive with the availability of large volumes of historical datawe can leverage the machine learning paradigm to make machines perform specific tasks by gaining enough experience by observing patterns in data over period of time and then use this experience in solving tasks in the future with minimal manual intervention the core idea remains to make machines solve tasks that can be easily defined intuitively and almost involuntarily but extremely hard to define formally formal definition we are now ready to define machine learning formally you may have come across multiple definitions of machine learning by now which includetechniques to make machines intelligentautomation on steroidsautomating the task of automation itselfthe sexiest job of the st centurymaking computers learn by themselves and countless otherswhile all of them are good quotes and true to certain extentsthe best way to define machine learning would be to start from the basics of machine learning as defined by renowned professor tom mitchell in the idea of machine learning is that there will be some learning algorithm that will help the machine learn from data professor mitchell defined it as follows " computer program is said to learn from experience with respect to some class of tasks and performance measure pif its performance at tasks in tas measured by pimproves with experience while this definition might seem daunting at firsti ask you go read through it couple of times slowly focusing on the three parameters--tpand --which are the main components of any learning algorithmas depicted in figure - |
15,761 | figure - defining the components of learning algorithm we can simplify the definition as follows machine learning is field that consists of learning algorithms thatimprove their performance at executing some task over time with experience while we discuss at length each of these entities in the following sectionswe will not spend time in formally or mathematically defining each of these entities since the scope of the book is more toward applied or practical machine learning if you consider our real-world problem from earlierone of the tasks could be predicting outages for our infrastructureexperience would be what our machine learning model would gain over time by observing patterns from various device data attributesand the performance of the model could be measured in various ways like how accurately the model predicts outages defining the taskt we had discussed briefly in the previous section about the tasktwhich can be defined in two-fold approach from problem standpointthe tasktis basically the real-world problem to be solved at handwhich could be anything from finding the best marketing or product mix to predicting infrastructure failures in the machine learning worldit is best if you can define the task as concretely as possible such that you talk about what the exact problem is which you are planning to solve and how you could define or formulate the problem into specific machine learning task machine learning based tasks are difficult to solve by conventional and traditional programming approaches tasktcan usually be defined as machine learning task based on the process or workflow that the system should follow to operate on data points or samples typically data sample or point will consist of multiple data attributes (also called features in machine learning lingojust like the various device parameters we mentioned in our problem for dss company earlier typical data point can be |
15,762 | denoted by vector (python listsuch that each element in the vector is for specific data feature or attribute we discuss more about features and data points in detail in future section as well as in "feature engineering and selectioncoming back to the typical tasks that could be classified as machine learning tasksthe following list describes some popular tasks classification or categorizationthis typically encompasses the list of problems or tasks where the machine has to take in data points or samples and assign specific class or category to each sample simple example would be classifying animal images into dogscatsand zebras regressionthese types of tasks usually involve performing prediction such that real numerical value is the output instead of class or category for an input data point the best way to understand regression task would be to take the case of real-world problem of predicting housing prices considering the plot areanumber of floorsbathroomsbedroomsand kitchen as input attributes for each data point anomaly detectionthese tasks involve the machine going over event logstransaction logsand other data points such that it can find anomalous or unusual patterns or events that are different from the normal behavior examples for this include trying to find denial of service attacks from logsindications of fraudand so on structured annotationthis usually involves performing some analysis on input data points and adding structured metadata as annotations to the original data that depict extra information and relationships among the data elements simple examples would be annotating text with their parts of speechnamed entitiesgrammarand sentiment annotations can also be done for images like assigning specific categories to image pixelsannotate specific areas of images based on their typelocationand so on translationautomated machine translation tasks are typically of the nature such that if you have input data samples belonging to specific languageyou translate it into output having another desired language natural language based translation is definitely huge area dealing with lot of text data clustering or groupingclusters or groups are usually formed from input data samples by making the machine learn or observe inherent latent patternsrelationships and similarities among the input data points themselves usually there is lack of pre-labeled or pre-annotated data for these tasks hence they form part of unsupervised machine learning (which we will discuss later onexamples would be grouping similar productsevents and entities transcriptionsthese tasks usually entail various representations of data that are usually continuous and unstructured and converting them into more structured and discrete data elements examples include speech to textoptical character recognitionimages to textand so on this should give you good idea of typical tasks that are often solved using machine learningbut this list is definitely not an exhaustive one as the limits of tasks are indeed endless and more are being discovered with extensive research over time |
15,763 | defining the experiencee at this pointyou know that any learning algorithm typically needs data to learn over time and perform specific taskwhich we named as the process of consuming dataset that consists of data samples or data points such that learning algorithm or model learns inherent patterns is defined as the experiencee which is gained by the learning algorithm any experience that the algorithm gains is from data samples or data points and this can be at any point of time you can feed it data samples in one go using historical data or even supply fresh data samples whenever they are acquired thusthe idea of model or algorithm gaining experience usually occurs as an iterative processalso known as training the model you could think of the model to be an entity just like human being which gains knowledge or experience through data points by observing and learning more and more about various attributesrelationships and patterns present in the data of coursethere are various forms and ways of learning and gaining experience including supervisedunsupervisedand reinforcement learning but we will discuss learning methods in future section for nowtake step back and remember the analogy we drew that when machine truly learnsit is based on data which is fed to it from time to time thus allowing it to gain experience and knowledge about the task to be solvedsuch that it can used this experienceeto predict or solve the same tasktin the future for previously unseen data points defining the performancep let' say we have machine learning algorithm that is supposed to perform tasktand is gaining experienceewith data points over period of time but how do we know if it' performing well or behaving the way it is supposed to behavethis is where the performancepof the model comes into the picture the performancepis usually quantitative measure or metric that' used to see how well the algorithm or model is performing the tasktwith experiencee while performance metrics are usually standard metrics that have been established after years of research and developmenteach metric is usually computed specific to the tasktwhich we are trying to solve at any given point of time typical performance measures include accuracyprecisionrecallf scoresensitivityspecificityerror ratemisclassification rateand many more performance measures are usually evaluated on training data samples (used by the algorithm to gain experienceeas well as data samples which it has not seen or learned from beforewhich are usually known as validation and test data samples the idea behind this is to generalize the algorithm so that it doesn' become too biased only on the training data points and performs well in the future on newer data points more on trainingvalidationand test data will be discussed when we talk about model building and validation while solving any machine learning problemmost of the timesthe choice of performance measurepis either accuracyf scoreprecisionand recall while this is true in most scenariosyou should always remember that sometimes it is difficult to choose performance measures that will accurately be able to give us an idea of how well the algorithm is performing based on the actual behavior or outcome which is expected from it simple example would be that sometimes we would want to penalize misclassification or false positives more than correct hits or predictions in such scenariowe might need to use modified cost function or priors such that we give scope to sacrifice hit rate or overall accuracy for more accurate predictions with lesser false positives real-world example would be an intelligent system that predicts if we should give loan to customer it' better to build the system in such way that it is more cautious against giving loan than denying one the simple reason is because one big mistake of giving loan to potential defaulter can lead to huge losses as compared to denying several smaller loans to potential customers to concludeyou need to take into account all parameters and attributes involved in tasktsuch that you can decide on the right performance measurespfor your system |
15,764 | multi-disciplinary field we have formally introduced and defined machine learning in the previous sectionwhich should give you good idea about the main components involved with any learning algorithm let' now shift our perspective to machine learning as domain and field you might already know that machine learning is mostly considered to be sub-field of artificial intelligence and even computer science from some perspectives machine learning has concepts that have been derived and borrowed from multiple fields over period of time since its inceptionmaking it true multi-disciplinary or inter-disciplinary field figure - should give you good idea with regard to the major fields that overlap with machine learning based on conceptsmethodologiesideasand techniques an important point to remember here is that this is definitely not an exhaustive list of domains or fields but pretty much depicts the major fields associated in tandem with machine learning figure - machine learninga true multi-disciplinary field the major domains or fields associated with machine learning include the followingas depicted in figure - we will discuss each of these fields in upcoming sections artificial intelligence natural language processing data mining mathematics statistics computer science deep learning data science |
15,765 | you could say that data science is like broad inter-disciplinary field spanning across all the other fields which are sub-fields inside it of course this is just simple generalization and doesn' strictly indicate that it is inclusive of all other other fields as supersetbut rather borrows important concepts and methodologies from them the basic idea of data science is once again processesmethodologiesand techniques to extract information from data and domain knowledge this is big part of what we discuss in an upcoming section when we talk about data science in further details coming back to machine learningideas of pattern recognition and basic data mining methodologies like knowledge discovery of databases (kddcame into existence when relational databases were very prominent these areas focus more on the ability and technique to mine for information from large datasetssuch that you can get patternsknowledgeand insights of interest of coursekdd is whole process by itself that includes data acquisitionstoragewarehousingprocessingand analysis machine learning borrows concepts that are more concerned with the analysis phasealthough you do need to go through the other steps to reach to the final stage data mining is again interdisciplinary or multi-disciplinary field and borrows concepts from computer sciencemathematicsand statistics the consequence of this is the fact that computational statistics form an important part of most machine learning algorithms and techniques artificial intelligence (aiis the superset consisting of machine learning as one of its specialized areas the basic idea of ai is the study and development of intelligence as exhibited by machines based on their perception of their environmentinput parameters and attributes and their response such that they can perform desired tasks based on expectations ai itself is truly massive field which is itself inter-disciplinary it draws on concepts from mathematicsstatisticscomputer sciencecognitive scienceslinguisticsneuroscienceand many more machine learning is more concerned with algorithms and techniques that can be used to understand databuild representationsand perform tasks such as predictions another major sub-field under ai related to machine learning is natural language processing (nlpwhich borrows concepts heavily from computational linguistics and computer science text analytics is prominent field today among analysts and data scientists to extractprocess and understand natural human language combine nlp with ai and machine learning and you get chatbotsmachine translatorsand virtual personal assistantswhich are indeed the future of innovation and technologycoming to deep learningit is subfield of machine learning itself which deals more with techniques related to representational learning such that it improves with more and more data by gaining more experience it follows layered and hierarchical approach such that it tries to represent the given input attributes and its current surroundingsusing nested layered hierarchy of concept representations such thateach complex layer is built from another layer of simpler concepts neural networks are something which is heavily utilized by deep learning and we will look into deep learning in bit more detail in future section and solve some real-world problems later on in this book computer science is pretty much the foundation for most of these domains dealing with studydevelopmentengineeringand programming of computers hence we won' be expanding too much on this but you should definitely remember the importance of computer science for machine learning to exist and be easily applied to solve real-world problems this should give you good idea about the broad landscape of the multi-disciplinary field of machine learning and how it is connected across multiple related and overlapping fields we will discuss some of these fields in more detail in upcoming sections and cover some basic concepts in each of these fields wherever necessary let' look at some core fundamentals of computer science in the following section computer science the field of computer science (cscan be defined as the study of the science of understanding computers this involves studyresearchdevelopmentengineeringand experimentation of areas dealing with understandingdesigningbuildingand using computers this also involves extensive design and development of algorithms and programs that can be used to make the computer perform computations and tasks as desired there are mainly two major areas or fields under computer scienceas follows |
15,766 | theoretical computer science applied or practical computer science the two major areas under computer science span across multiple fields and domains wherein each field forms part or sub-field of computer science the main essence of computer science includes formal languagesautomata and theory of computationalgorithmsdata structurescomputer design and architectureprogramming languagesand software engineering principles theoretical computer science theoretical computer science is the study of theory and logic that tries to explain the principles and processes behind computation this involves understanding the theory of computation which talks about how computation can be used efficiently to solve problems theory of computation includes the study of formal languagesautomataand understanding complexities involved in computations and algorithms information and coding theory is another major field under theoretical cs that has given us domains like signal processingcryptographyand data compression principles of programming languages and their analysis is another important aspect that talks about featuresdesignanalysisand implementations of various programming languages and how compilers and interpreters work in understanding these languages last but never the leastdata structures and algorithms are the two fundamental pillars of theoretical cs used extensively in computational programs and functions practical computer science practical computer science also known as applied computer science is more about toolsmethodologiesand processes that deal with applying concepts and principles from computer science in the real world to solve practical day-to-day problems this includes emerging sub-fields like artificial intelligencemachine learningcomputer visiondeep learningnatural language processingdata miningand robotics and they try to solve complex real-world problems based on multiple constraints and parameters and try to emulate tasks that require considerable human intelligence and experience besides thesewe also have wellestablished fieldsincluding computer architectureoperating systemsdigital logic and designdistributed computingcomputer networkssecuritydatabasesand software engineering important concepts these are several concepts from computer science that you should know and remember since they would be useful as foundational concepts to understand the other conceptsand examples better it' not an exhaustive list but should pretty much cover enough to get started algorithms an algorithm can be described as sequence of stepsoperationscomputationsor functions that can be executed to carry out specific task they are basically methods to describe and represent computer program formally through series of operationswhich are often described using plain natural languagemathematical symbolsand diagrams typically flowchartspseudocodeand natural language are used extensively to represent algorithms an algorithm can be as simple as adding two numbers and as complex as computing the inverse of matrix |
15,767 | programming languages programming language is language that has its own set of symbolswordstokensand operators having their own significance and meaning thus syntax and semantics combine to form formal language in itself this language can be used to write computer programswhich are basically real-world implementations of algorithms that can be used to specify specific instructions to the computer such that it carries our necessary computation and operations programming languages can be low level like and assembly or high level languages like java and python ode this is basically source code that forms the foundation of computer programs code is written using programming languages and consists of collection of computer statements and instructions to make the computer perform specific desired tasks code helps convert algorithms into programs using programming languages we will be using python to implement most of our real-world machine learning solutions data structures data structures are specialized structures that are used to manage data basically they are real-world implementations for abstract data type specifications that can be used to storeretrievemanageand operate on data efficiently there is whole suite of data structures like arraysliststuplesrecordsstructuresunionsclassesand many more we will be using python data structures like listsarraysdataframesand dictionaries extensively to operate on real-world datad ata science the field of data science is very diverseinter-disciplinary field which encompasses multiple fields that we depicted in figure - data science basically deals with principlesmethodologiesprocessestoolsand techniques to gather knowledge or information from data (structured as well as unstructureddata science is more of compilation of processestechniquesand methodologies to foster data-driven decision based culture in fact drew conway' "data science venn diagram,depicted in figure - shows the core components and essence of data sciencewhich in fact went viral and became insanely popular |
15,768 | figure - drew conway' data science venn diagram figure - is quite intuitive and easy to interpret basically there are three major components and data science sits at the intersection of them math and statistics knowledge is all about applying various computational and quantitative math and statistical based techniques to extract insights from data hacking skills basically indicate the capability of handlingprocessingmanipulating and wrangling data into easy to understand and analyzable formats substantive expertise is basically the actual real-world domain expertise which is extremely important when you are solving problem because you need to know about various factorsattributesconstraintsand knowledge related to the domain besides your expertise in data and algorithms thus drew rightly points out that machine learning is combination of expertise on data hacking skillsmathand statistical learning methods and for data scienceyou need some level of domain expertise and knowledge along with machine learning you can check out drew' personal insights in his article at science venn diagram besides thiswe also have brendan tierneywho talks about the true nature of data science being multi-disciplinary field with his own depictionas shown in figure - |
15,769 | figure - brendan tierney' depiction of data science as true multi-disciplinary field if you observe his depiction closelyyou will see lot of the domains mentioned here are what we just talked about in the previous sections and matches substantial part of figure - you can clearly see data science being the center of attention and drawing parts from all the other fields and machine learning as sub-field mathematics the field of mathematics deals with numberslogicand formal systems the best definition of mathematics was coined by aristotle as "the science of quantitythe scope of mathematics as scientific field is huge spanning across areas including algebratrigonometrycalculusgeometryand number theory just to name few major fields linear algebra and probability are two major sub-fields under mathematics that are used extensively in machine learning and we will be covering few important concepts from them in this section our major focus will always be on practical machine learningand applied mathematics is an important aspect for the same linear algebra deals with mathematical objects and structures like vectorsmatriceslinesplaneshyperplanesand vector spaces the theory of probability is mathematical field and framework used for studying and quantifying events of chance and uncertainty and deriving theorems and axioms from the same these laws and axioms help us in reasoningunderstandingand quantifying uncertainty and its effects in any real-world system or scenariowhich helps us in building our machine learning models by leveraging this framework |
15,770 | important concepts in this sectionwe discuss some key terms and concepts from applied mathematicsnamely linear algebra and probability theory these concepts are widely used across machine learning and form some of the foundational structures and principles across machine learning algorithmsmodelsand processes scalar scalar usually denotes single number as opposed to collection of numbers simple example might be or rwhere is the scalar element pointing to single number or real-valued single number vector vector is defined as structure that holds an array of numbers which are arranged in order this basically means the order or sequence of numbers in the collection is important vectors can be mathematically denoted as [ xn]which basically tells us that is one-dimensional vector having elements in the array each element can be referred to using an array index determining its position in the vector the following snippet shows us how we can represent simple vectors in python in [ ] [ out[ ][ in [ ]import numpy as np np array([ ]print(xprint(type( )[ thus you can see that python lists as well as numpy based arrays can be used to represent vectors each row in dataset can act as one-dimensional vector of attributeswhich can serve as inputs to learning algorithms matrix matrix is two-dimensional structure that basically holds numbers it' also often referred to as array each element can be referred to using row and column index as compared to single vector index in case em of vectors mathematicallyyou can depict matrix as em such that is matrix eem uu having three rows and three columns and each element is denoted by mrc such that denotes the row index and denotes the column index matrices can be easily represented as list of lists in python and we can leverage the numpy array structure as depicted in the following snippet in [ ] np array([[ ][ ][ ]] |
15,771 | in [ ]view matrix print( [[ [ [ ]in [ ]view dimensions print( shape( thus you can see how we can easily leverage numpy arrays to represent matrices you can think of dataset with rows and columns as matrix such that the data features or attributes are represented by columns and each row denotes data sample we will be using the same analogy later on in our analyses of courseyou can perform matrix operations like addsubtractproductsinversetransposedeterminantsand many more the following snippet shows some popular matrix operations in [ ]matrix transpose print('matrix transpose:\ ' transpose()'\ 'matrix determinant print ('matrix determinant:'np linalg det( )'\ 'matrix inverse m_inv np linalg inv(mprint ('matrix inverse:\ 'm_inv'\ 'identity matrix (result of matrix matrix_inverseiden_m np dot(mm_inviden_m np round(np abs(iden_m) print ('product of matrix and its inverse:\ 'iden_mmatrix transpose[[ [ [ ]matrix determinant- matrix inverse[[- - - - - ]product of matrix and its inverse[ ]this should give you good idea to get started with matrices and their basic operations more on this is covered in "the python machine learning ecosystem |
15,772 | tensor you can think of tensor as generic array tensors are basically arrays with variable number of axes an element in three-dimensional tensor can be denoted by tx, , where xyz denote the three axes for specifying element norm the norm is measure that is used to compute the size of vector often also defined as the measure of distance from the origin to the point denoted by the vector mathematicallythe pth norm of vector is denoted as follows xp ae op xi such that > and popular norms in machine learning include the norm used extensively in lasso regression models and the normalso known as the euclidean normused in ridge regression models eigen decomposition this is basically matrix decomposition process such that we decompose or break down matrix into set of eigen vectors and eigen values the eigen decomposition of matrix can be mathematically denoted by diag(lv- such that the matrix has total of linearly independent eigen vectors represented as { ( ) ( ) ( )and their corresponding eigen values can be represented as { lnthe matrix consists of one eigen vector per column of the matrix [ ( ) ( ) ( )and the vector consists of all the eigen values together [ lnan eigen vector of the matrix is defined as non-zero vector such that on multiplying the matrix by the eigen vectorthe result only changes the scale of the eigen vector itselfi the result is scalar multiplied by the eigen vector this scalar is known as the eigen value corresponding to the eigen vector mathematically this can be denoted by mv lv where is our matrixv is the eigen vector and is the corresponding eigen value the following python snippet depicts how to extract eigen values and eigen vectors from matrix in [ ]eigendecomposition np array([[ ][ ][ ]]eigen_valseigen_vecs np linalg eig(mprint('eigen values:'eigen_vals'\ 'print('eigen vectors:\ 'eigen_vecseigen values- eigen vectors[[- - - ] |
15,773 | singular value decomposition the process of singular value decompositionalso known as svdis another matrix decomposition or factorization process such that we are able to break down matrix to obtain singular vectors and singular values any real matrix will always be decomposed by svd even if eigen decomposition may not be applicable in some cases mathematicallysvd can be defined as follows considering matrix having dimensions such that denotes total rows and denotes total columnsthe svd of the matrix can be represented with the following equation ' ' sm' vnt' this gives us the following main components of the decomposition equation um is an unitary matrix where each column represents left singular vector sm is an matrix with positive numbers on the diagonalwhich can also be represented as vector of the singular values vtn is an unitary matrix where each row represents right singular vector in some representationsthe rows and columns might be interchanged but the end result should be the samei and are always orthogonal the following snippet shows simple svd decomposition in python in [ ]svd np array([[ ][ ][ ]]usvt np linalg svd(mprint('getting svd outputs:-\ 'print(' :\ ' '\ 'print(' :\ ' '\ 'print('vt:\ 'vt'\ 'getting svd outputs: [ - - - ] vt[ [- - [- ]svd as technique and the singular values in particular are very useful in summarization based algorithms and various other methods like dimensionality reduction |
15,774 | random variable used frequently in probability and uncertainty measurementa random variable is basically variable that can take on various values at random these variables can be of discrete or continuous type in general probability distribution probability distribution is distribution or arrangement that depicts the likelihood of random variable or variables to take on each of its probable states there are usually two main types of distributions based on the variable being discrete or continuous probability mass function probability mass functionalso known as pmfis probability distribution over discrete random variables popular examples include the poisson and binomial distributions probability density function probability density functionalso known as pdfis probability distribution over continuous random variables popular examples include the normaluniformand student' distributions marginal probability the marginal probability rule is used when we already have the probability distribution for set of random variables and we want to compute the probability distribution for subset of these random variables for discrete random variableswe can define marginal probability as follows ap for continuous random variableswe can define it using the integration operation as follows op dy conditional probability the conditional probability rule is used when we want to determine the probability that an event is going to take placesuch that another event has already taken place this is mathematically represented as follows ( yp , (ythis tells us the conditional probability of xgiven that has already taken place |
15,775 | bayes theorem this is another rule or theorem which is useful when we know the probability of an event of interest ( )the conditional probability for another event based on our event of interest ( aand we want to determine the conditional probability of our event of interest given the other event has taken place ( bthis can be defined mathematically using the following expression ( ) ap (bsuch that and are events and ap statistics the field of statistics can be defined as specialized branch of mathematics that consists of frameworks and methodologies to collectorganizeanalyzeinterpretand present data generally this falls more under applied mathematics and borrows concepts from linear algebradistributionsprobability theoryand inferential methodologies there are two major areas under statistics that are mentioned as follows descriptive statistics inferential statistics the core component of any statistical process is data hence typically data collection is done firstwhich could be in global termsoften called population or more restricted subset due to various constraints often knows as sample samples are usually collected manuallyfrom surveysexperimentsdata storesand observational studies from this datavarious analyses are carried out using statistical methods descriptive statistics is used to understand basic characteristics of the data using various aggregation and summarization measures to describe and understand the data better these could be standard measures like meanmedianmodeskewnesskurtosisstandard deviationvarianceand so on you can refer to any standard book on statistics to deep dive into these measures if you're interested the following snippet depicts how to compute some essential descriptive statistical measures in [ ]descriptive statistics import scipy as sp import numpy as np get data nums np random randint( , size=( , ))[ print('data'numsget descriptive stats print ('mean:'sp mean(nums)print ('median:'sp median(nums)print ('mode:'sp stats mode(nums)print ('standard deviation:'sp std(nums)print ('variance:'sp var(nums)print ('skew:'sp stats skew(nums)print ('kurtosis:'sp stats kurtosis(nums) |
15,776 | data mean median modemoderesult(mode=array([ ])count=array([ ])standard deviation variance skew- kurtosis- libraries and frameworks like pandasscipyand numpy in general help us compute descriptive statistics and summarize data easily in python we cover these frameworks as well as basic data analysis and visualization in and inferential statistics are used when we want to test hypothesisdraw inferencesand conclusions about various characteristics of our data sample or population frameworks and techniques like hypothesis testingcorrelationand regression analysisforecastingand predictions are typically used for any form of inferential statistics we look at this in much detail in subsequent when we cover predictive analytics as well as time series based forecasting data mining the field of data mining involves processesmethodologiestools and techniques to discover and extract patternsknowledgeinsights and valuable information from non-trivial datasets datasets are defined as non-trivial when they are substantially huge usually available from databases and data warehouses once againdata mining itself is multi-disciplinary fieldincorporating concepts and techniques from mathematicsstatisticscomputer sciencedatabasesmachine learning and data science the term is misnomer in general since the "miningrefers to the mining of actual insights or information from the data and not data itselfin the whole process of kdd or knowledge discovery in databasesdata mining is the step where all the analysis takes place in generalboth kdd as well as data mining are closely linked with machine learning since they are all concerned with analyzing data to extract useful patterns and insights hence methodologiesconceptstechniquesand processes are shared among them the standard process for data mining followed in the industry is known as the crisp-dm modelwhich we discuss in more detail in an upcoming section in this artificial intelligence the field of artificial intelligence encompasses multiple sub-fields including machine learningnatural language processingdata miningand so on it can be defined as the artscience and engineering of making intelligent agentsmachines and programs the field aims to provide solutions for one simple yet extremely tough objective"can machines thinkreasonand act like human beings?ai in fact existed as early as the when people started asking such questions and conducting research and development on building tools that could work on concepts instead of numbers like calculator does progress in ai took place in steady pace with discoveries and inventions by alan turingmccullouchand pitts artificial neurons ai was revived once again after slowdown till the with success of expert systemsthe resurgence of neural networks thanks to hopfieldrumelhartmcclellandhintonand many more faster and better computation thanks to moore' law led to fields like data miningmachine learning and even deep learning come into prominence to solve complex problems that would otherwise have been impossible to solve using traditional approaches figure - shows some of the major facets under the broad umbrella of ai |
15,777 | figure - diverse major facets under the ai umbrella some of the main objectives of ai include emulation of cognitive functions also known as cognitive learningsemanticsand knowledge representationlearningreasoningproblem solvingplanningand natural language processing ai borrows toolsconceptsand techniques from statistical learningapplied mathematicsoptimization methodslogicprobability theorymachine learningdata miningpattern recognitionand linguistics ai is still evolving over time and lot of innovation is being done in this field including some of the latest discoveries and inventions like self-driving carschatbotsdronesand intelligent robots natural language processing the field of natural language processing (nlpis multi-disciplinary field combining concepts from computational linguisticscomputer science and artificial intelligence nlp involves the ability to make machines processunderstandand interact with natural human languages the major objective of applications or systems built using nlp is to enable interactions between machines and natural languages that have evolved over time major challenges in this aspect include knowledge and semantics representationnatural language understandinggenerationand processing some of the major applications of nlp are mentioned as follows machine translation speech recognition question answering systems context recognition and resolution text summarization text categorization |
15,778 | information extraction sentiment and emotion analysis topic segmentation using techniques from nlp and text analyticsyou can work on text data to processannotateclassifyclustersummarizeextract semanticsdetermine sentimentand much morethe following example snippet depicts some basic nlp operations on textual data where we annotate document (text sentencewith various components like parts of speechphrase level tagsand so on based on its constituent grammar you can refer to page of text analytics with python (apressdipanjan sarkar for more details on constituency parsing from nltk parse stanford import stanfordparser sentence 'the quick brown fox jumps over the lazy dogcreate parser object scp stanfordparser(path_to_jar=' :/stanford/stanford-parser-full-/stanfordparser jar'path_to_models_jar=' :/stanford/stanford-parser-full-/stanfordparser--models jar'get parse tree result list(scp raw_parse(sentence)tree result[ in [ ]print the constituency parse tree print(tree(root (np (np (dt the(jj quick(jj brown(nn fox)(np (np (nns jumps)(pp (in over(np (dt the(jj lazy(nn dog)))))in [ ]visualize constituency parse tree tree draw( |
15,779 | figure - constituency parse tree for our sample sentence thus you can clearly see that figure - depicts the constituency grammar based parse tree for our sample sentencewhich consists of multiple noun phrases (npeach phrase has several words that are also annotated with their own parts of speech (postags we cover more on processing and analyzing textual data for various steps in the machine learning pipeline as well as practical use cases in subsequent eep learning the field of deep learningas depicted earlieris sub-field of machine learning that has recently come into much prominence its main objective is to get machine learning research closer to its true goal of "making machines intelligentdeep learning is often termed as rebranded fancy term for neural networks this is true to some extent but there is definitely more to deep learning than just basic neural networks deep learning based algorithms involves the use of concepts from representation learning where various representations of the data are learned in different layers that also aid in automated feature extraction from the data in simple termsa deep learning based approach tries to build machine intelligence by representing data as layered hierarchy of conceptswhere each layer of concepts is built from other simpler layers this layered architecture itself is one of the core components of any deep learning algorithm in any basic supervised machine learning techniquewe basically try to learn mapping between our data samples and our output and then try to predict output for newer data samples representational learning tries to understand the representations in the data itself besides learning mapping from inputs to outputs this makes deep learning algorithms extremely powerful as compared to regular techniqueswhich require significant expertise in areas like feature extraction and engineering deep learning is also extremely effective with regard to its performance as well as scalability with more and more data as compared to older machine learning algorithms this is depicted in figure - based on slide from andrew ng' talk at the extract data conference |
15,780 | figure - performance comparison of deep learning and traditional machine learning by andrew ng indeedas rightly pointed out by andrew ngthere have been several noticeable trends and characteristics related to deep learning that we have noticed over the past decade they are summarized as follows deep learning algorithms are based on distributed representational learning and they start performing better with more data over time deep learning could be said to be rebranding of neural networksbut there is lot into it compared to traditional neural networks better software frameworks like tensorflowtheanocaffemxnetand kerascoupled with superior hardware have made it possible to build extremely complexmulti-layered deep learning models with huge sizes deep learning has multiple advantages related to automated feature extraction as well as performing supervised learning operationswhich have helped data scientists and engineers solve increasingly complex problems over time the following points describe the salient features of most deep learning algorithmssome of which we will be using in this book hierarchical layered representation of concepts these concepts are also called features in machine learning terminology (data attributesdistributed representational learning of the data happens through multi-layered architecture (unsupervised learningmore complex and high-level features and concepts are derived from simplerlowlevel features |
15,781 | "deepneural network usually is considered to have at least more than one hidden layer besides the input and output layers usually it consists of minimum of three to four hidden layers deep architectures have multi-layered architecture where each layer consists of multiple non-linear processing units each layer' input is the previous layer in the architecture the first layer is usually the input and the last layer is the output can perform automated feature extractionclassificationanomaly detectionand many other machine learning tasks this should give you good foundational grasp of the concepts pertaining to deep learning suppose we had real-world problem of object recognition from images figure - will give us good idea of how typical machine learning and deep learning pipelines differ (sourceyann lecunfigure - comparing various learning pipelines by yann lecun you can clearly see how deep learning methods involve hierarchical layer representation of features and concept from the raw data as compared to other machine learning methods we conclude this section with brief coverage of some essential concepts pertaining to deep learning |
15,782 | important concepts in this sectionwe discuss some key terms and concepts from deep learning algorithms and architecture this should be useful in the future when you are building your own deep learning models artificial neural networks an artificial neural network (annis computational model and architecture that simulates biological neurons and the way they function in our brain typicallyan ann has layers of interconnected nodes the nodes and their inter-connections are analogous to the network of neurons in our brain typical ann has an input layeran output layerand at least one hidden layer between the input and output with inter-connectionsas depicted in figure - figure - typical artificial neural network any basic ann will always have multiple layers of nodesspecific connection patterns and links between the layersconnection weights and activation functions for the nodes/neurons that convert weighted inputs to outputs the process of learning for the network typically involves cost function and the objective is to optimize the cost function (typically minimize the costthe weights keep getting updated in the process of learning |
15,783 | backpropagation the backpropagation algorithm is popular technique to train anns and it led to resurgence in the popularity of neural networks in the the algorithm typically has two main stages--propagation and weight updates they are described briefly as follows propagation the input data sample vectors are propagated forward through the neural network to generate the output values from the output layer compare the generated output vector with the actual/desired output vector for that input data vector compute difference in error at the output units backpropagate error values to generate deltas at each node/neuron weight update compute weight gradients by multiplying the output delta (errorand input activation use learning rate to determine percentage of the gradient to be subtracted from original weight and update the weight of the nodes these two stages are repeated multiple times with multiple iterations/epochs until we get satisfactory results typically backpropagation is used along with optimization algorithms or functions like stochastic gradient descent multilayer perceptrons multilayer perceptronalso known as mlpis fully connectedfeed-forward artificial neural network with at least three layers (inputoutputand at least one hidden layerwhere each layer is fully connected to the adjacent layer each neuron usually is non-linear functional processing unit backpropagation is typically used to train mlps and even deep neural nets are mlps when they have multiple hidden layers typically used for supervised machine learning tasks like classification convolutional neural networks convolutional neural networkalso known as convnet or cnnis variant of the artificial neural networkwhich specializes in emulating functionality and behavior of our visual cortex cnns typically consist of the following three components multiple convolutional layerswhich consist of multiple filters that are convolved across the height and width of the input data ( image raw pixelsby basically computing dot product to give two-dimensional activation map on stacking all the maps across all the filterswe end up getting the final output from convolutional layer |
15,784 | pooling layerswhich are basically layers that perform non-linear down sampling to reduce the input size and number of parameters from the convolutional layer output to generalize the model moreprevent overfitting and reduce computation time filters go through the heights and width of the input and reduce it by taking an aggregate like sumaverageor max typical pooling components are average or max pooling fully connected mlps to perform tasks such as image classification and object recognition typical cnn architecture with all the components is depicted as follows in figure - which is lenet cnn model (sourcedeeplearning netfigure - lenet cnn model (sourcedeeplearning netrecurrent neural networks recurrent neural networkalso known as rnnis special type of an artificial neural network that allows persisting information based on past knowledge by using special type of looped architecture they are used lot in areas related to data with sequences like predicting the next word of sentence these looped networks are called recurrent because they perform the same operations and computation for each and every element in sequence of input data rnns have memory that helps in capturing information from past sequences figure - (sourcecolah' blog at the typical structure of rnn and how it works by unrolling the network based on input sequence length to be fed at any point in time figure - recurrent neural network (sourcecolah' blog |
15,785 | figure - clearly depicts how the unrolled network will accept sequences of length in each pass of the input data and operate on the same long short-term memory networks rnns are good in working on sequence based data but as the sequences start increasingthey start losing historical context over time in the sequence and hence outputs are not always what is desired this is where long short-term memory networkspopularly known as lstmscome into the pictureintroduced by hochreiter schmidhuber in lstms can remember information from really long sequence based data and prevent issues like the vanishing gradient problemwhich typically occurs in anns trained with backpropagation lstms usually consist of three or four gatesincluding inputoutputand special forget gate figure - shows high-level pictorial representation of single lstm cell figure - an lstm cell (sourcedeeplearning netthe input gate usually can allow or deny incoming signals or inputs to alter the memory cell state the output gate usually propagates the value to other neurons as needed the forget gate controls the memory cell' self-recurrent connection to remember or forget previous states as necessary multiple lstm cells are usually stacked in any deep learning network to solve real-world problems like sequence prediction autoencoders an autoencoder is specialized artificial neural network that is primarily used for performing unsupervised machine learning tasks its main objective is to learn data representationsapproximationsand encodings autoencoders can be used for building generative modelsperforming dimensionality reductionand detecting anomalies machine learning methods machine learning has multiple algorithmstechniquesand methodologies that can be used to build models to solve real-world problems using data this section tries to classify these machine learning methods under some broad categories to give some sense to the overall landscape of machine learning methods that are ultimately used to perform specific machine learning tasks we discussed in previous section typically the same machine learning methods can be classified in multiple ways under multiple umbrellas following are some of the major broad areas of machine learning methods |
15,786 | methods based on the amount of human supervision in the learning process supervised learning unsupervised learning semi-supervised learning reinforcement learning methods based on the ability to learn from incremental data samples batch learning online learning methods based on their approach to generalization from data samples instance based learning model based learning we briefly cover the various types of learning methods in the following sections to build good foundation with regard to machine learning methods and the type of tasks they usually solve this should give you enough knowledge to start understanding which methods should be applied in what scenarios when we tackle various real-world use cases and problems in the subsequent of the book #discussing mathematical details and internals of each and every machine learning algorithm would be out of the current scope and intent of the booksince the focus is more on solving real-world problems by applying machine learning and not on theoretical machine learning hence you are encouraged to refer to standard machine learning references like pattern recognition and machine learningchristopher bishop and the elements of statistical learningrobert tibshirani et al for more theoretical and mathematical details on the internals of machine learning algorithms and methods supervised learning supervised learning methods or algorithms include learning algorithms that take in data samples (known as training dataand associated outputs (known as labels or responseswith each data sample during the model training process the main objective is to learn mapping or association between input data samples and their corresponding outputs based on multiple training data instances this learned knowledge can then be used in the future to predict an output yfor any new input data sample xwhich was previously unknown or unseen during the model training process these methods are termed as supervised because the model learns on data samples where the desired output responses/labels are already known beforehand in the training phase supervised learning basically tries to model the relationship between the inputs and their corresponding outputs from the training data so that we would be able to predict output responses for new data inputs based on the knowledge it gained earlier with regard to relationships and mappings between the inputs and their target outputs this is precisely why supervised learning methods are extensively used in predictive analytics where the main objective is to predict some response for some input data that' typically fed into trained supervised ml model supervised learning methods are of two major classes based on the type of ml tasks they aim to solve |
15,787 | classification regression let' look at these two machine learning tasks and observe the subset of supervised learning methods that are best suited for tackling these tasks classification the classification based tasks are sub-field under supervised machine learningwhere the key objective is to predict output labels or responses that are categorical in nature for input data based on what the model has learned in the training phase output labels here are also known as classes or class labels are these are categorical in nature meaning they are unordered and discrete values thuseach output response belongs to specific discrete class or category suppose we take real-world example of predicting the weather let' keep it simple and say we are trying to predict if the weather is sunny or rainy based on multiple input data samples consisting of attributes or features like humiditytemperaturepressureand precipitation since the prediction can be either sunny or rainythere are total of two distinct classes in totalhence this problem can also be termed as binary classification problem figure - depicts the binary weather classification task of predicting weather as either sunny or rainy based on training the supervised model on input data samples having feature vectors(precipitationhumiditypressureand temperaturefor each data sample/observation and their corresponding class labels as either sunny or rainy figure - supervised learningbinary classification for weather prediction task where the total number of distinct classes is more than two becomes multi-class classification problem where each prediction response can be any one of the probable classes from this set simple example would be trying to predict numeric digits from scanned handwritten images in this case it becomes -class classification problem because the output class label for any image can be any digit from in |
15,788 | both the casesthe output class is scalar value pointing to one specific class multi-label classification tasks are such that based on any input data samplethe output response is usually vector having one or more than one output class label simple real-world problem would be trying to predict the category of news article that could have multiple output classes like newsfinancepoliticsand so on popular classification algorithms include logistic regressionsupport vector machinesneural networksensembles like random forests and gradient boostingk-nearest neighborsdecision treesand many more regression machine learning tasks where the main objective is value estimation can be termed as regression tasks regression based methods are trained on input data samples having output responses that are continuous numeric values unlike classificationwhere we have discrete categories or classes regression models make use of input data attributes or features (also called explanatory or independent variablesand their corresponding continuous numeric output values (also called as responsedependentor outcome variableto learn specific relationships and associations between the inputs and their corresponding outputs with this knowledgeit can predict output responses for newunseen data instances similar to classification but with continuous numeric outputs one of the most common real-world examples of regression is prediction of house prices you can build simple regression model to predict house prices based on data pertaining to land plot areas in square feet figure - shows two possible regression models based on different methods to predict house prices based on plot area figure - supervised learningregression models for house price prediction the basic idea here is that we try to determine if there is any relationship or association between the data feature plot area and the outcome variablewhich is the house price and is what we want to predict thus once we learn this trend or relationship depicted in figure - we can predict house prices in the future for any given plot of land if you have noticed the figure closelywe depicted two types of models on purpose to show that there can be multiple ways to build model on your training data the main objective is to minimize errors during training and validating the model so that it generalized welldoes not overfit or get biased only to the training data and performs well in future predictions simple linear regression models try to model relationships on data with one feature or explanatory variable and single response variable where the objective is to predict methods like ordinary least squares (olsare typically used to get the best linear fit during model training |
15,789 | multiple regression is also known as multivariable regression these methods try to model data where we have one response output variable in each observation but multiple explanatory variables in the form of vector instead of single explanatory variable the idea is to predict based on the different features present in real-world example would be extending our house prediction model to build more sophisticated model where we predict the house price based on multiple features instead of just plot area in each data sample the features could be represented in vector as plot areanumber of bedroomsnumber of bathroomstotal floorsfurnishedor unfurnished based on all these attributesthe model tries to learn the relationship between each feature vector and its corresponding house price so that it can predict them in the future polynomial regression is special case of multiple regression where the response variable is modeled as an nth degree polynomial of the input feature basically it is multiple regressionwhere each feature in the input feature vector is multiple of the model on the right in figure - to predict house prices is polynomial model of degree non-linear regression methods try to model relationships between input features and outputs based on combination of non-linear functions applied on the input features and necessary model parameters lasso regression is special form of regression that performs normal regression and generalizes the model well by performing regularization as well as feature or variable selection lasso stands for least absolute shrinkage and selection operator the norm is typically used as the regularization term in lasso regression ridge regression is another special form of regression that performs normal regression and generalizes the model by performing regularization to prevent overfitting the model typically the norm is used as the regularization term in ridge regression generalized linear models are generic frameworks that can be used to model data predicting different types of output responsesincluding continuousdiscreteand ordinal data algorithms like logistic regression are used for categorical data and ordered probit regression for ordinal data nsupervised learning supervised learning methods usually require some training data where the outcomes which we are trying to predict are already available in the form of discrete labels or continuous values howeveroften we do not have the liberty or advantage of having pre-labeled training data and we still want to extract useful insights or patterns from our data in this scenariounsupervised learning methods are extremely powerful these methods are called unsupervised because the model or algorithm tries to learn inherent latent structurespatterns and relationships from given data without any help or supervision like providing annotations in the form of labeled outputs or outcomes unsupervised learning is more concerned with trying to extract meaningful insights or information from data rather than trying to predict some outcome based on previously available supervised training data there is more uncertainty in the results of unsupervised learning but you can also gain lot of information from these models that was previously unavailable to view just by looking at the raw data often unsupervised learning could be one of the tasks involved in building huge intelligence system for examplewe could use unsupervised learning to get possible outcome labels for tweet sentiments by using the knowledge of the english vocabulary and then train supervised model on similar data points and their outcomes which we obtained previously through unsupervised learning there is no hard and fast rule with regard to using just one specific technique you can always combine multiple methods as long as they are relevant in solving the problem unsupervised learning methods can be categorized under the following broad areas of ml tasks relevant to unsupervised learning clustering dimensionality reduction anomaly detection association rule-mining |
15,790 | we explore these tasks briefly in the following sections to get good feel of how unsupervised learning methods are used in the real world clustering clustering methods are machine learning methods that try to find patterns of similarity and relationships among data samples in our dataset and then cluster these samples into various groupssuch that each group or cluster of data samples has some similaritybased on the inherent attributes or features these methods are completely unsupervised because they try to cluster data by looking at the data features without any prior trainingsupervisionor knowledge about data attributesassociationsand relationships consider real-world problem of running multiple servers in data center and trying to analyze logs for typical issues or errors our main task is to determine the various kinds of log messages that usually occur frequently each week in simple wordswe want to group log messages into various clusters based on some inherent characteristics simple approach would be to extract features from the log messageswhich would be in textual format and apply clustering on the same and group similar log messages together based on similarity in content figure - shows how clustering would solve this problem basically we have raw log messages to start with our clustering system would employ feature extraction to extract features from text like word occurrencesphrase occurrencesand so on finallya clustering algorithm like -means or hierarchical clustering would be employed to group or cluster messages based on similarity of their inherent features figure - unsupervised learningclustering log messages it is quite clear from figure - that our systems have three distinct clusters of log messages where the first cluster depicts disk issuesthe second cluster is about memory issuesand the third cluster is about processor issues top feature words that helped in distinguishing the clusters and grouping similar data samples (logstogether are also depicted in the figure of coursesometimes some features might be present across multiple data samples hence there can be slight overlap of clusters too since this is unsupervised learning howeverthe main objective is always to create clusters such that elements of each cluster are near each other and far apart from elements of other clusters there are various types of clustering methods that can be classified under the following major approaches centroid based methods such as -means and -medoids hierarchical clustering methods such as agglomerative and divisive (ward'saffinity propagationdistribution based clustering methods such as gaussian mixture models density based methods such as dbscan and optics |
15,791 | besides thiswe have several methods that recently came into the clustering landscapelike birch and clarans dimensionality reduction once we start extracting attributes or features from raw data samplessometimes our feature space gets bloated up with humongous number of features this poses multiple challenges including analyzing and visualizing data with thousands or millions of featureswhich makes the feature space extremely complex posing problems with regard to training modelsmemoryand space constraints in fact this is referred to as the "curse of dimensionalityunsupervised methods can also be used in these scenarioswhere we reduce the number of features or attributes for each data sample these methods reduce the number of feature variables by extracting or selecting set of principal or representative features there are multiple popular algorithms available for dimensionality reduction like principal component analysis (pca)nearest neighborsand discriminant analysis figure - shows the output of typical feature reduction process applied to swiss roll structure having three dimensions to obtain two-dimensional feature space for each data sample using pca figure - unsupervised learningdimensionality reduction from figure - it is quite clear that each data sample originally had three features or dimensionsnamely ( and after applying pcawe reduce each data sample from our dataset into two dimensionsnamely '( dimensionality reduction techniques can be classified in two major approaches as follows feature selection methodsspecific features are selected for each data sample from the original list of features and other features are discarded no new features are generated in this process feature extraction methodswe engineer or extract new features from the original list of features in the data thus the reduced subset of features will contain newly generated features that were not part of the original feature set pca falls under this category |
15,792 | anomaly detection the process of anomaly detection is also termed as outlier detectionwhere we are interested in finding out occurrences of rare events or observations that typically do not occur normally based on historical data samples sometimes anomalies occur infrequently and are thus rare eventsand in other instancesanomalies might not be rare but might occur in very short bursts over timethus have specific patterns unsupervised learning methods can be used for anomaly detection such that we train the algorithm on the training dataset having normalnon-anomalous data samples once it learns the necessary data representationspatternsand relations among attributes in normal samplesfor any new data sampleit would be able to identify it as anomalous or normal data point by using its learned knowledge figure - depicts some typical anomaly detection based scenarios where you could apply supervised methods like one-class svm and unsupervised methods like clusteringk-nearest neighborsauto-encodersand so on to detect anomalies based on data and its features figure - unsupervised learninganomaly detection anomaly detection based methods are extremely popular in real-world scenarios like detection of security attacks or breachescredit card fraudmanufacturing anomaliesnetwork issuesand many more association rule-mining typically association rule-mining is data mining method use to examine and analyze large transactional datasets to find patterns and rules of interest these patterns represent interesting relationships and associationsamong various items across transactions association rule-mining is also often termed as market basket analysiswhich is used to analyze customer shopping patterns association rules help in detecting and predicting transactional patterns based on the knowledge it gains from training transactions using this techniquewe can answer questions like what items do people tend to buy togetherthereby indicating frequent item sets we can also associate or correlate products and itemsi insights like people who buy beer also tend to buy chicken wings at pub figure - shows how typical association rulemining method should work ideally on transactional dataset |
15,793 | figure - unsupervised learningassociation rule-mining from figure - you can clearly see that based on different customer transactions over period of timewe have obtained the items that are closely associated and customers tend to buy them together some of these frequent item sets are depicted like {meateggs}{milkeggsand so on the criterion of determining good quality association rules or frequent item sets is usually done using metrics like supportconfidenceand lift this is an unsupervised methodbecause we have no idea what the frequent item sets are or which items are more strongly associated with which items beforehand only after applying algorithms like the apriori algorithm or fp-growthcan we detect and predict products or items associated closely with each other and find conditional probabilistic dependencies we cover association rule-mining in further details in semi-supervised learning the semi-supervised learning methods typically fall between supervised and unsupervised learning methods these methods usually use lot of training data that' unlabeled (forming the unsupervised learning componentand small amount of pre-labeled and annotated data (forming the supervised learning componentmultiple techniques are available in the form of generative methodsgraph based methodsand heuristic based methods simple approach would be building supervised model based on labeled datawhich is limitedand then applying the same to large amounts of unlabeled data to get more labeled samplestrain the model on them and repeat the process another approach would be to use unsupervised algorithms to cluster similar data samplesuse human-in-the-loop efforts to manually annotate or label these groupsand then use combination of this information in the future this approach is used in many image tagging systems covering semi-supervised methods would be out of the present scope of this book einforcement learning the reinforcement learning methods are bit different from conventional supervised or unsupervised methods in this contextwe have an agent that we want to train over period of time to interact with specific environment and improve its performance over period of time with regard to the type of actions it performs on the environment typically the agent starts with set of strategies or policies for interacting with the environment on observing the environmentit takes particular action based on rule or policy and by observing the current state of the environment based on the actionthe agent gets rewardwhich could be beneficial or detrimental in the form of penalty it updates its current policies and strategies if needed and |
15,794 | this iterative process continues till it learns enough about its environment to get the desired rewards the main steps of reinforcement learning method are mentioned as follows prepare agent with set of initial policies and strategy observe environment and current state select optimal policy and perform action get corresponding reward (or penalty update policies if needed repeat steps iteratively until agent learns the most optimal policies consider real-world problem of trying to make robot or machine learn to play chess in this case the agent would be the robot and the environment and states would be the chessboard and the positions of the chess pieces suitable reinforcement learning methodology is depicted in figure - figure - reinforcement learningtraining robot to play chess the main steps involved for making the robot learn to play chess is pictorially depicted in figure - this is based on the steps discussed earlier for any reinforcement learning method in factgoogle' deepmind built the alphago ai with components of reinforcement learning to train the system to play the game of go batch learning batch learning methods are also popularly known as offline learning methods these are machine learning methods that are used in end-to-end machine learning systems where the model is trained using all the available training data in one go once training is done and the model completes the process of learningon getting satisfactory performanceit is deployed into production where it predicts outputs for new data samples howeverthe model doesn' keep learning over period of time continuously with the new data once the training is complete the model stops learning thussince the model trains with data in one single batch and it is usually one-time procedurethis is known as batch or offline learning |
15,795 | we can always train the model on new data but then we would have to add new data samples along with the older historical training data and again re-build the model using this new batch of data if most of the model building workflow has already been implementedretraining model would not involve lot of efforthoweverwith the data size getting bigger with each new data samplethe retraining process will start consuming more processormemoryand disk resources over period of time these are some points to be considered when you are building models that would be running from systems having limited capacity online learning online learning methods work in different way as compared to batch learning methods the training data is usually fed in multiple incremental batches to the algorithm these data batches are also known as mini-batches in ml terminology howeverthe training process does not end there unlike batch learning methods it keeps on learning over period of time based on new data samples which are sent to it for prediction basically it predicts and learns in the process with new data on the fly without have to re-run the whole model on previous data samples there are several advantages to online learning--it is suitable in real-world scenarios where the model might need to keep learning and re-training on new data samples as they arrive problems like device failure or anomaly prediction and stock market forecasting are two relevant scenarios besides thissince the data is fed to the model in incremental mini-batchesyou can build these models on commodity hardware without worrying about memory or disk constraints since unlike batch learning methodsyou do not need to load the full dataset in memory before training the model besides thisonce the model trains on datasetsyou can remove them since we do not need the same data again as the model learns incrementally and remembers what it has learned in the past one of the major caveats in online learning methods is the fact that bad data samples can affect the model performance adversely all ml methods work on the principle of "garbage in garbage outhence if you supply bad data samples to well-trained modelit can start learning relationships and patterns that have no real significance and this ends up affecting the overall model performance since online learning methods keep learning based on new data samplesyou should ensure proper checks are in place to notify you in case suddenly the model performance drops also suitable model parameters like learning rate should be selected with care to ensure the model doesn' overfit or get biased based on specific data samples instance based learning there are various ways to build machine learning models using methods that try to generalize based on input data instance based learning involves ml systems and methods that use the raw data points themselves to figure out outcomes for newerpreviously unseen data samples instead of building an explicit model on training data and then testing it out simple example would be -nearest neighbor algorithm assuming we have our initial training data the ml method knows the representation of the data from the featuresincluding its dimensionsposition of each data pointand so on for any new data pointit will use similarity measure (like cosine or euclidean distanceand find the three nearest input data points to this new data point once that is decidedwe simply take majority of the outcomes for those three training points and predict or assign it as the outcome label/response for this new data point thusinstance based learning works by looking at the input data points and using similarity metric to generalize and predict for new data points |
15,796 | model based learning the model based learning methods are more traditional ml approach toward generalizing based on training data typically an iterative process takes place where the input data is used to extract features and models are built based on various model parameters (known as hyperparametersthese hyperparameters are optimized based on various model validation techniques to select the model that generalizes best on the training data and some amount of validation and test data (split from the initial datasetfinallythe best model is used to make predictions or decisions as and when needed the crisp-dm process model the crisp-dm model stands for cross industry standard process for data mining more popularly known by the acronym itselfcrisp-dm is triedtestedand robust industry standard process model followed for data mining and analytics projects crisp-dm clearly depicts necessary stepsprocessesand workflows for executing any project right from formalizing business requirements to testing and deploying solution to transform data into insights data sciencedata miningand machine learning are all about trying to run multiple iterative processes to extract insights and information from data hence we can say that analyzing data is truly both an art as well as sciencebecause it is not always about running algorithms without reasona lot of the major effort involves in understanding the businessthe actual value of the efforts being investedand proper methods to articulate end results and insights the crisp-dm model tells us that for building an end-to-end solution for any analytics project or systemthere are total of six major steps or phasessome of them being iterative just like we have software development lifecycle with several major phases or steps for software development projectwe have data mining or analysis lifecycle in this scenario figure - depicts the data mining lifecycle with the crisp-dm model |
15,797 | figure - the crisp-dm model depicting the data mining lifecycle figure - clearly shows there are total of six major phases in the data mining lifecycle and the direction to proceed is depicted with arrows this model is not rigid imposition but rather framework to ensure you are on the right track when going through the lifecycle of any analytics project in some scenarios like anomaly detection or trend analysisyou might be more interested in data understandingexplorationand visualization rather than intensive modeling each of the six phases is described in detail as follows business understanding this is the initial phase before kick starting any project in full flow however this is one of the most important phases in the lifecyclethe main objective here starts with understanding the business context and requirements for the problem to be solved at hand definition of business requirements is crucial to convert the business problem into data mining or analytics problem and to set expectations and success criteria for both the customer as well as the solution task force the final deliverable from this phase would be detailed plan with the major milestones of the project and expected timelines along with success criteriaassumptionsconstraintscaveatsand challenges |
15,798 | define business problem the first task in this phase would be to start by understanding the business objective of the problem to be solved and build formal definition of the problem the following points are crucial toward clearly articulating and defining the business problem get business context of the problem to be solvedassess the problem with the help of domainand subject matter experts (smesdescribe main pain points or target areas for business objective to be solved understand the solutions that are currently in placewhat is lackingand what needs to be improved define the business objective along with proper deliverables and success criteria based on inputs from businessdata scientistsanalystsand smes assess and analyze scenarios once the business problem is defined clearlythe main tasks involved would be to analyze and assess the current scenario with regard to the business problem definition this includes looking at what is currently available and making note of various items required ranging from resourcespersonnelto data besides thisproper assessment of risks and contingency plans need to be discussed the main steps involved in the assessment stage here are mentioned as follows assess and analyze what is currently available to solve the problem from various perspectives including datapersonnelresource timeand risks build out brief report of key resources needed (both hardware and softwareand personnel involved in case of any shortcomingsmake sure to call them out as necessary discuss business objective requirements one by one and then identify and record possible assumptions and constraints for each requirement with the help of smes verify assumptions and constraints based on data available ( lot of this might be answered only after detailed analysishence it depends on the problem to be solved and the data availabledocument and report possible risks involved in the project including timelinesresourcespersonneldataand financial based concerns build contingency plans for each possible scenario discuss success criteria and try to document comparative return on investment or cost versus valuation analysis if needed this just needs to be rough benchmark to make sure the project aligns with the company or business vision |
15,799 | define data mining problem this could be defined as the pre-analysis phasewhich starts once the success criteria and the business problem is defined and all the risksassumptions and constraints have been documented this phase involves having detailed technical discussions with your analystsdata scientistsand developers and keeping the business stakeholders in sync the following are the key tasks that are to be undertaken in this phase discuss and document possible machine learning and data mining methods suitable for the solution by assessing possible toolsalgorithmsand techniques develop high-level designs for end-to-end solution architecture record notes on what the end output from the solution will be and how will it integrate with existing business components record success evaluation criteria from data science standpoint simple example could be making sure that predictions are at least accurate project plan this is the final stage under the business understanding phase project plan is generally created consisting of the entire major six phases in the crisp-dm modelestimated timelinesallocated resources and personneland possible risks and contingency plans care is taken to ensure concrete high-level deliverables and success criteria are defined for each phase and iterative phases like modeling are highlighted with annotations like feedback based on smes might need models to be rebuilt and retuned before deployment you should be ready for the next step once you have the following points covered definition of business objectives for the problem success criteria for business and data mining efforts budget allocation and resource planning clearwell-defined machine learning and data mining methodologies to be followedincluding high-level workflows from exploration to deployment detailed project plan with all six phases of the crisp-dm model defined with estimated timelines and risks data understanding the second phase in the crisp-dm process involves taking deep dive into the data available and understanding it in further detail before starting the process of analysis this involves collecting the datadescribing the various attributesperforming some exploratory analysis of the dataand keeping tabs on data quality this phase should not be neglected because bad data or insufficient knowledge about available data can have cascading adverse effects in the later stages in this process data collection this task is undertaken to extractcurateand collect all the necessary data needed for your business objective usually this involves making use of the organizations historical data warehousesdata martsdata lakes and so on an assessment is done based on the existing data available in the organization and if there is any need for additional data this can be obtained from the webi open data sources or it can be obtained from other channels like surveyspurchasesexperiments and simulations detailed documents should keep |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.