id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
15,800 | track of all datasets which would be used for analysis and additional data sources if any are necessary this document can be combined with the subsequent stages of this phase data description data description involves carrying out initial analysis on the data to understand more about the dataits sourcevolumeattributesa... |
15,801 | data preparation the third phase in the crisp-dm process takes place after gaining enough knowledge on the business problem and relevant dataset data preparation is mainly set of tasks that are performed to cleanwranglecurateand prepare the data before running any analytical or machine learning methods and building mod... |
15,802 | modeling the fourth phase in the crisp-dm process is the core phase in the process where most of the analysis takes place with regard to using cleanformatted data and its attributes to build models to solve business problems this is an iterative processas depicted in figure - earlieralong with model evaluation and all ... |
15,803 | evaluation the fifth phase in the crisp-dm process takes place once we have the final models from the modeling phase that satisfy necessary success criteria with respect to our data mining goals and have the desired performance and results with regard to model evaluation metrics like accuracy the evaluation phase invol... |
15,804 | learning algorithms and techniques this is more of technical or solution based pipeline and it assumes that several aspects of the crisp-dm model are already coveredincluding the following points business and data understanding ml/dm technique selection riskassumptionsand constraints assessment machine learning pipelin... |
15,805 | feature scaling and selectiondata features often need to be normalized and scaled to prevent machine learning algorithms from getting biased besides thisoften we need to select subset of all available features based on feature importance and quality this process is known as feature selection "feature engineering and se... |
15,806 | learning (supervisedalgorithm and training data features and corresponding labels this model will take features from new data samples and output predicted labels in the prediction phase unsupervised machine learning pipeline unsupervised machine learning is all about extracting patternsrelationshipsassociationsand clus... |
15,807 | detail we will be using python in this bookyou can refer to "the python machine learning ecosystemto understand more about python and the various tools and frameworks used in machine learning you can follow along with the code snippets in this section or open the predicting student recommendation machine learning pipel... |
15,808 | figure - raw data depicting student records and their recommendations now that we can see data samples showing records for each student and their corresponding recommendation outcomes in figure - we will perform necessary tasks relevant to data preparation data preparation based on the dataset we saw earlierwe do not h... |
15,809 | figure - dataset features in [ ]view outcome labels outcome_labels figure - dataset recommendation outcome labels for each student |
15,810 | now that we have extracted our initial available features from the data and their corresponding outcome labelslet' separate out our available features based on their type (numerical and categoricaltypes of feature variables are covered in more detail in "processingwranglingand visualizing datain [ ]list down features b... |
15,811 | now that we have successfully scaled our numeric features (see figure - )let' handle our categorical features and carry out the necessary feature engineering needed based on the following code in [ ]training_features pd get_dummies(training_featurescolumns=categoricial_feature_namesview newly engineering features train... |
15,812 | model evaluation typically model evaluation is done based on some holdout or validation dataset that is different from the training dataset to prevent overfitting or biasing the model since this is an example on toy datasetlet' evaluate the performance of our model on the training data using the following snippet in [ ... |
15,813 | prediction in action we are now ready to start predicting with our newly built and deployed modelto start predictionswe need to load our model and scalar objects into memory the following code helps us do this in [ ]load model and scaler objects model joblib load( 'model/model pickle'scaler joblib load( 'scaler/scaler ... |
15,814 | figure - updated feature set for new students we now have the relevant features for the new studentshowever you can see that some of the categorical features are missing based on some grades like bcand this is because none of these students obtained those grades but we still need those attributes because the model was ... |
15,815 | figure - new student records with model predictions for grant recommendations we can clearly see from figure - that our model has predicted grant recommendation labels for both the new students thomas clearly being diligenthaving straight average and decent scoresis most likely to get the grant recommendation as compar... |
15,816 | product recommendations in online shopping platforms sentiment and emotion analysis anomaly detection fraud detection and prevention content recommendation (newsmusicmoviesand so onweather forecasting stock market forecasting market basket analysis customer segmentation object and scene recognition in images and video ... |
15,817 | the python machine learning ecosystem in the first we explored the absolute basics of machine learning and looked at some of the algorithms that we can use machine learning is very popular and relevant topic in the world of technology today hence we have very diverse and varied support for machine learning in terms of ... |
15,818 | different from major compiled languages like and +as python code is not required to be built and linked like code for these languages this distinction makes for two important pointspython code is fast to developas the code is not required to be compiled and builtpython code can be much readily changed and executed this... |
15,819 | setting up python environment the starting step for our journey into the world of data science is the setup of our python environment we usually have two options for setting up our environmentinstall python and the necessary libraries individually use pre-packaged python distribution that comes with necessary libraries... |
15,820 | figure - downloading the anaconda package installing the downloaded file is as simple as double-clicking the file and letting the installer take care of the entire process to check if the installation was successfuljust open command prompt or terminal and start up python you should be greeted with the message shown in ... |
15,821 | installing libraries we will not be covering the basics of pythonas we assume you are already acquainted with basic python syntax feel free to check out any standard course or book on python programming to pick up on the basics we will cover one very basic but very important aspect of installing additional libraries in... |
15,822 | easy to collaborate data science solutions are rarely one man job often lot of collaboration is required in data science team to develop great analytical solution luckily python provides tools that make it extremely easy to collaborate for diverse team one of the most liked featureswhich empowers this collaborationare ... |
15,823 | and hence the code among peers who can replicate our research and analyses by themselves these jupyter notebooks can contain codetextimagesoutputetc and can be arranged in step by step manner to give complete step by step illustration of the whole analysis process this capability makes notebooks valuable tool for repro... |
15,824 | different kernel (for example python kernelif installed in your systema notebook is just collection of cells there are three major types of cells in notebook code cellsjust like the name suggeststhese are the cells that you can use to write your code and associated comments the contents of these cells are sent to the k... |
15,825 | numpy numpy is the backbone of machine learning in python it is one of the most important libraries in python for numerical computations it adds support to core python for multi-dimensional arrays (and matricesand fast vectorized operations on these arrays the present day numpy library is successor of an early libraryn... |
15,826 | creating arrays arrays can be created in multiple ways in numpy one of the ways was demonstrated earlier to create singledimensional array similarly we can stack up multiple lists to create multidimensional array in [ ]arr np array([[ , , ],[ , , ],[ , , ]]arr shape out[ ]( in [ ]arr out[ ]array([[ ][ ][ ]]in addition... |
15,827 | in practicemost of the arrays are created during reading in the data we will cover the text data retrieval operations of numpy very briefly as we will try to use pandas generallyfor our data ingestion process (more on this in later part of the one of the functions that we can use to read data from text file to numpy ar... |
15,828 | in [ ]arr[ out[ ]array([[ ][ ]]here we see that using similar indexing scheme as abovewe get an array having one lesser dimension than the original array the next important concept in accessing arrays is the concept of slicing arrays suppose we want to have collection of elements only instead of all the elements then w... |
15,829 | [[ ][ ][ ]]]now if we want to access the third columnwe can use two different notations to access that columnin [ ]arr[:,:, out[ ]array([ ][ ][ ]]we can also use dot notation in the following way both of the methods gets us the same value but the dot notation is concise the dot notation stands for as many colons as req... |
15,830 | boolean indexingthis advanced indexing occurs when the reference object is an array of boolean values this is used when we want to access data based on some conditionsin that caseboolean indexing can be used we will illustrate it with an example suppose in one arraywe have the names of some cities and in another arrayw... |
15,831 | ufuncs are simple and easy to understand once you are able to relate the output they produce on particular array in [ ]arr np arange( reshape( , arr out[ ]array([ ] ][ ]]in [ ]arr out[ ]array([ ][ ][ ]]in [ ]arr out[ ]array([ ][ ][ ]]we see that the standard operators when used in conjunction with arrays work element-w... |
15,832 | array([[ ][ ][ ][ ][ ]]here we see that we were able to add up two arrays even when they were of different sizes this is achieved by the concept of broadcasting we will conclude this brief discussion on operations on arrays by demonstrating function that will return two arrays in [ ]arr np random randn( , arr out[ ]arr... |
15,833 | in [ ] dot(bout[ ]array([ ] ][ ]]similarlythere are functions implemented for finding different products of matrices like innerouterand so on another popular matrix operation is transpose of matrix this can be easily achieved by using the function in [ ] np arange( reshape( , in [ ] out[ ]array([ ] ] ] ] ]]oftentimeswe... |
15,834 | we can also check if the solution is correct using the np allclose function in [ ]np allclose(np dot(ax)bout[ ]true similarlyfunctions are there for finding the inverse of matrixeigen vectors and eigen values of matrixnorm of matrixdeterminant of matrixand so onsome of which we covered in detail in take look at the det... |
15,835 | data retrieval pandas provides numerous ways to retrieve and read in data we can convert data from csv filesdatabasesflat filesand so on into dataframes we can also convert list of dictionaries (python dictinto dataframe the sources of data which pandas allows us to handle cover almost all the major data sources for ou... |
15,836 | figure - sample csv file we can convert this file into dataframe with the help of the following code leveraging pandas in [ ]import pandas as pd in [ ]city_data pd read_csv(filepath_or_buffer='simplemaps-worldcities-basic csv'in [ ]city_data head( = out[ ]city city_ascii lat lng pop country qal eh-ye now qal eh-ye afgh... |
15,837 | the entire gamut of parameters available and you are encouraged to read the documentation of this function as this is one of the starting point of most python based data analysis databases to dataframe the most important data source for data scientists is the existing data sources used by their organizations relational... |
15,838 | kadoma kadoma - zimbabwe chitungwiza chitungwiza - zimbabwe harare harare - zimbabwe bulawayo bulawayo - zimbabwe iso iso province zw zwe manicaland zw zwe mashonaland west zw zwe harare zw zwe harare zw zwe bulawayo slicing and dicing the usual rules of slicing and dicing data that we used in python lists apply to the... |
15,839 | the examples given here are self-explanatory and you can refer to the numpy section for more details similar slicing rules apply for dataframes also but the only difference is that now simple slicing refers to the slicing of rows and all the other columns will end up in the result consider the following example in [ ]c... |
15,840 | - - - - - - when we select data based on some conditionwe always get the part of dataframe that satisfies the condition supplied sometimes we want to test condition against dataframe but want to preserve the shape of the dataframe in these caseswe can use the where function (check out numpy' where function also to see ... |
15,841 | in this sectionwe learned some of the core data access mechanisms of pandas dataframes the data access mechanism of pandas are as simple and extensive to use as with numpy this ensures that we have various way to access our data data operations in subsequent of our bookthe pandas dataframe will be our data structure of... |
15,842 | - - - - - - - nan - - - in [ ]df fillna ( out[ ] - - - - - - - - - - here we have substituted the missing value with default value we can use variety of methods to arrive at the substituting value (meanmedianand so onwe will see more methods of missing value treatment (like imputationin subsequent descriptive statistic... |
15,843 | in [ ]city_data[columns_numericcount(out[ ]lat lng pop dtypeint in [ ]city_data[columns_numericmedian(out[ ]lat lng pop dtypefloat in [ ]city_data[columns_numericquantile( out[ ]lat lng pop dtypefloat all these operations were applied to each of the columnsthe default behavior we can also get all these statistics for e... |
15,844 | concatenating dataframes most data science projects will have data from more than one data source these data sources will mostly have data that' related in some way to each other and the subsequent steps in data analysis will require them to be concatenated or joined pandas provides rich set of functions that allow us ... |
15,845 | in [ ]df out[ ]col col col col col col col col col col col col col col col col col col col col in [ ]df pd dataframe({'col '['col ''col ''col ''col ']'col '['col ''col ''col ''col ']'col '['col ''col ''col ''col ']}index=[ ]in [ ]pd concat([df ,df ]axis= out[ ]col col col col col col col col col col col nan nan nan col... |
15,846 | in [ ]del(city_data['country']in [ ]city_data merge(country_data'inner'head(out[ ]city city_ascii lat lng pop iso iso qal eh-ye now qal eh-ye af afg chaghcharan chaghcharan af afg lashkar gah lashkar gah af afg zaranj zaranj af afg tarin kowt tarin kowt af afg province country badghis afghanistan ghor afghanistan hilma... |
15,847 | core apis scikit-learn is an evolving and active projectas witnessed by its github repository statistics this framework is built on quite small and simple list of core api ideas and design patterns in this section we will briefly touch on the core apis on which the central operations of scikit-learn are based dataset r... |
15,848 | transformerstransformation of input data before learning of model is very common task in machine learning some data transformations are simplefor example replacing some missing data with constanttaking log transformwhile some data transformations are similar to learning algorithms themselves (for examplepcato simplify ... |
15,849 | model tuning and selectioneach learning algorithm will have bunch of parameters or hyperparameters associated with it the iterative process of machine learning aims at finding the best set of parameters that give us the model having the best performance for examplethe process of tuning various hyperparameters of random... |
15,850 | in [ ] shape out[ ]( lin [ ] [: out[ ]array([ - - - - - ][- - - - - - - - - ] - - - - - - ][- - - - - - ] - - - - - ]in [ ] [: out[ ]array( ]since we are using the data in the form of numpy arrayswe don' get the name of the features in the data itself but we will keep the reference to the variable names as they may be ... |
15,851 | then we will define the model we want to use and the parameter space for one of the model' hyperparameters here we will search the parameter alpha of the lasso model this parameter basically controls the strictness our regularization in [ ]lasso lasso(random_state= alphas np logspace(- - then we will initialize an esti... |
15,852 | neural networks and deep learning deep learning has become one of the most well-known representations of machine learning in the recent years deep learning applications have achieved remarkable accuracy and popularity in various fields especially in image and audio related domains python is the language of choice when ... |
15,853 | figure - simple neural network this network is having an input vector of size hidden layer of size and binary output layer the process of learning an ann will involve the following steps define the structure or architecture of the network we want to use this is critical as if we choose very extensive network containing... |
15,854 | decide on loss function we will use for the output layer this is applicable in the case when we have supervised learning problemi we have an output label associated with each of the input data points learning the parameters of the neural network determine the values of each connection weight each arrow in figure - carr... |
15,855 | theano the first library popularly used for learning neural networks is theano although by itselftheano is not traditional machine learning or neural network learning frameworkwhat it provides is powerful set of constructs that can be used to train both normal machine learning models and neural networks theano allows ... |
15,856 | herewe defined symbolical operation (denoted by the symbol zand then bound the input and the operations in function this was achieved by using the function construct provided by theano contrast it with the normal programming paradigm and we would need to define the whole function by ourselves this is one of the most po... |
15,857 | tensorflow tensorflow is an open source software library for machine learning released by google in november tensorflow is based on the internal system that google uses to power its research and production systems tensorflow is quite similar to theano and can be considered as google' attempt to provide an upgrade to t... |
15,858 | keras keras is high-level deep learning framework for pythonwhich is capable of running on top of both theano and tensorflow developed by francois cholletthe most important advantage of using keras is the time saved by its easy-to-use but powerful high level apis that enable rapid prototyping for an idea keras allows ... |
15,859 | model building the model building process with keras is three-step process the first step is specifying the structure of the model this is done by configuring the base model that we want to usewhich is either sequential model or functional model once we have identified base model for our problem we will further enrich... |
15,860 | in [ ]from sklearn datasets import load_breast_cancer cancer load_breast_cancer(x_train cancer data[: y_train cancer target[: x_test cancer data[ :y_test cancer target[ :the next step of the process is to define the model architecture using the keras model class we see that our input vector is having attributes so we w... |
15,861 | thus if you have observations and your batch size is each epoch will consist of iterations where observations (data pointswill be passed through the network at time and the weights on the hidden layer units will be updated however we can see that the overall loss and training accuracy remains the same which means the m... |
15,862 | epochs= batch_size= epoch / / [============================== loss acc epoch / / [============================== loss acc epoch / / [============================== loss acc epoch / / [============================== loss acc epoch / / [============================== loss acc we see remarkable jump in the training accura... |
15,863 | the natural language tool kit perhaps the most important library of python to work with text data is nltk or the natural language tool kit this section introduce nltk and its important modules we go over the installation procedure of the library and brief description of its important modules installation and introduc... |
15,864 | you can also choose to download all necessary datasets without the gui by using the following command from the ipython or python shell nltk download('all'halt_on_error=falseonce the download is finished we will be able to use all the necessary functionalities and the bundled data of the nltk package we will now take lo... |
15,865 | chunking chunking is process which is similar to parsing or tokenization but the major difference is that instead of trying to parse each wordwe will target phrases present in the document consider the sentence "the brown fox saw the yellow dogin this sentencewe have two phrases which are of interest the first is the p... |
15,866 | textblobthis is another python library that promises simplified text processing it provides simple api for doing common text processing tasks including parts of speech taggingtokenizationphrase extractionsentiment analysisclassificationtranslationand much morespacythis is recent addition to the python text processing l... |
15,867 | inear regression linear regression is the simplest form of statistical modeling for modeling the relationship between response dependent variable and one or more independent variables such that the response variable typically follows normal distribution the statsmodels regression module allows us to learn linear mode... |
15,868 | the mean and variance of that metric this is the key difference in non-parametric methodsi we don' have fixed number of parameters that are required to describe an unknown random variable instead the number of parameters are dependent on the amount of training data the module nonparametric in the statsmodels library wi... |
15,869 | the machine learning pipeline |
15,870 | processingwranglingand visualizing data the world around us has changed tremendously since computers and the internet became mainstream with the ubiquitous mobile phones and now internet enabled devicesthe line between the digital and physical worlds is more blurred than it ever was at the heart of all this is data dat... |
15,871 | data collection data collection is where it all begins though listed as step that comes post business understanding and problem definitiondata collection often happens in parallel this is done in order to assist in augmenting the business understanding process with facts like availabilitypotential valueand so on befor... |
15,872 | the reader function takes file object as input to return an iterator containing the information read from the csv file the following code snippet uses the csv reader(function to read given file csv_reader csv reader(open(file_name'rb')delimiter=','once the iterator is returnedwe can easily iterate through the contents ... |
15,873 | with single line and few optional parameters (as per requirements)pandas extracts data from csv file into dataframewhich is tabular representation of the same data one of the major advantages of using pandas is the fact that it can handle lot of different variations in csv filessuch as files with or without headersattr... |
15,874 | figure - is sample json depicting record of glossary with various attributes of different data types figure - sample json (referencejsons are widely to send information across systems the python equivalent of json object is the dict data typewhich itself is key-value pair structure python has various json related libra... |
15,875 | the json object in figure - depicts fairly nested structure that contains values of stringnumericand array type json also supports objectsbooleansand other data types as values as well the following snippet reads the contents of the file and then utilizes json loads(utility to parse and convert it into standard python ... |
15,876 | figure - sample json depicting records with similar attributes we can easily parse such json using pandas by setting the orientation parameter to "records"as shown here df pd read_json(file_name,orient="records"the output is tabular dataframe with each data point represented by two attribute values as follows col_ col_ |
15,877 | you are encouraged to read more about pandas read_json(at xml having covered two of the most widely used data formatsso now let' take look at xml xmls are quite dated format yet is used by lot many systems xml or extensible markup language is markup language that defines rules for encoding data/documents to be shared a... |
15,878 | most xml parsers use this tree-like structure to read xml content the following are the two major types of xml parsersdom parserthe document object model parser is the closest form of tree representation of an xml it parses the xml and generates the tree structure one big disadvantage with dom parsers is their instabil... |
15,879 | tag:sub_element_with_attrattribute:{'attr''complex'tag datasub_element_text tag:sub_element_only_attrattribute:{'attr_val''only_attr'tag data:none tag:recordattribute:{'name''rec_ 'tag datatag:sub_elementattribute:{tag datatag:detail attribute:{tag data:attribute tag:detail attribute:{tag data: tag:sub_element_with_att... |
15,880 | html and scraping we began the talking about the immense amount of information/data being generated at breakneck speeds the internet or the web is one of the driving forces for this revolution coupled with immense reach due to computerssmartphones and tablets the internet is huge interconnected web of information conn... |
15,881 | figure - sample html page as rendered in browser browsers use markup tags to understand special instructions like text formattingpositioninghyperlinksand so on but only renders the content for the end user to see for use cases where datainformation resides in html pageswe need special techniques to extract this content... |
15,882 | figure - blog post on apress com now that we have the required page and its urlwe will use the requests library to query the required url and get response the following snippet does the same base_url "blog_suffix "/wannacry-how-to-prepare/ response requests get(base_url+blog_suffixif the get request is successfulthe re... |
15,883 | figure - depicts snapshot of the html behind the blog post we are interested in figure - inspecting the html content of blog post on apress com upon careful inspectionwe can clearly see text of the blog post is contained within the div tag now that we have narrowed down to the tag of interestwe use python' regular expr... |
15,884 | this was straightforward and very basic approach to get the required data what if we want to go step further and extract information related to all blog posts on the page and perform better cleanupfor such taskwe utilize the beautifulsoup library beautifulsoup is the go-to standard library for web scraping and related ... |
15,885 | now that we have the listthe final step it to iterate through this list of urls and extract each blog post' text the following function showcases how beautifulsoup simplifies the task as compared to our previous method of using regular expressions the method of identifying the required tag remains the samethough we uti... |
15,886 | oracleand so on the sqlite library provides lightweight easy-to-use interface to work with sqlite databasesthough the same can be handled by the other two libraries as well the second way of interacting with databases is the orm or the object relational mapper method this method is synonymous to the object oriented mod... |
15,887 | it is important to note that standard mathematical operations likeadditionsubtractionmultiplicationetc do not carry meaning for categorical variables even though that may be allowed syntactically (categorical variables represented as numbersthus is it important to handle categorical variables with care and we will see ... |
15,888 | ##note the dataset in consideration has been generated using standard python libraries like randomdatetimenumpypandasand so on this dataset has been generated using utility function called generate_sample_data(available in the code repository for this book the data has been randomly generated and is for representationa... |
15,889 | product id int quantity purchased int serial no int user id int user type object dtypeobject the column names are clearly listed and have been explained previously upon inspecting the data typeswe can clearly see that the date attribute is represented as an object before we move on to transformations and cleanuplet' di... |
15,890 | serial no non-null int user id non-null int user type non-null object dtypesfloat ( )int ( )object( memory usage kb none summary stats:price product id quantity purchased serial no user id count mean std min - - max filtering data we have completed our first pass of the dataset at hand and understood what it has and w... |
15,891 | figure - dataset with columns renamed for different algorithmsanalysis and even visualizationswe often require only subset of attributes to work with with pandaswe can vertically slice (select subset of columnsin variety of ways pandas provides different ways to suit different scenarios as we shall see in the following... |
15,892 | selecting specific attributes/columns is one of the ways of subsetting dataframe there may be requirements to horizontally splitting dataframe as well to work with subset of rowspandas provides ways as outlined in the following snippet print("select specific row indices::"print(df iloc[[ , , ]print(excluding specific r... |
15,893 | typecasting typecasting or converting data into appropriate data typesis an important part of cleanup and wrangling in general often data gets converted into wrong data types while being extracted or converted from one form to the other also different platforms and systems handle each data type differently and thus get... |
15,894 | along the same lineswe use the applymap(function to perform another element-wise operation to get the week of the transaction from the date attribute for this casewe use the lambda function to get the job done quickly refer to previous for more details on lambda functions the following snippet gets us the week for each... |
15,895 | the result is dataframe with rows without any missing dates the output dataframe is depicted in figure - figure - dataframe without any missing date information often dropping rows is very expensive and unfeasible option in many scenariosmissing values are imputed using the help of other values in the dataframe one com... |
15,896 | handling duplicates another issue with many datasets is the presence of duplicates while data is important and more the merrierduplicates do not add much value per se even moreduplicates help us identify potential areas of errors in recording/collecting the data itself to identify duplicateswe have utility called dupl... |
15,897 | the output is generated as depicted in figure - and figure - figure - shows the output of dummy encoding with the map(approach we keep the number of features in checkyet have to be careful about the caveats mentioned in this section figure - dataframe with user_type attribute dummy encoded the second imagefigure - show... |
15,898 | figure - original and normalized values for price string manipulations raw data presents all sorts of issues and complexities before it can be used for analysis strings are another class of raw data which needs special attention and treatment before our algorithms can make sense out of them as mentioned while discussin... |
15,899 | the first statement calculates the mean price for all transactions by user_typewhile the second one counts the number of transactions per week though these calculations are helpfulgrouping data based on attributes helps us get better understanding of it the groupby(function helps us perform the sameas shown in the foll... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.