id
int64
0
25.6k
text
stringlengths
0
4.59k
16,800
case study building recommender system inside database let' look at an actual implementation in python to make this all clearer step research question let' say you're working in video store and the manager asks you if it' possible to use the information on what movies people rent to predict what other movies they might...
16,801
handling large data on single computer listing creating customers in the database import mysqldb import pandas as pd user '****password '****database 'testmc mysqldb connect('localhost',user,password,databasecursor mc cursor(nr_customers colnames ["movie% % for in range( , )pd np random seed( generated_customers pd np ...
16,802
case study building recommender system inside database listing creating bit strings we represent the string as numeric value the string will be concatenation of zeros ( and ones ( because these indicate whether someone has seen certain movie or not the strings are then regarded as bit code for example is the same as th...
16,803
handling large data on single computer creating hash function the hash functions we create take the values of movies for customer we decided in the theory part of this case study to create hash functionsthe first function combines the movies and the second combines movies and and the third one combines and it' up to yo...
16,804
case study building recommender system inside database adding an index to the table now you must add indices to speed up retrieval as needed in real-time system this is shown in the next listing listing creating an index create function to easily create indices indices will quicken retrieval def createindex(columncurso...
16,805
handling large data on single computer if all is wellthe output of this code should be now that we have our hamming distance function in positionwe can use it to find similar customers to given customerand this is exactly what we want our application to do let' move on to the last partutilizing our setup as sort of app...
16,806
table the most similar customers to customer cust_id distance finding new movie we need to look at movies customer hasn' seen yetbut the nearest customer hasas shown in the following listing this is also good check to see if your distance function worked correctly although this may not be the closest customerit' good m...
16,807
handling large data on single computer mission accomplished our happy movie addict can now indulge himself with new movietailored to his preferences in the next we'll look at even bigger data and see how we can handle that using the horton sandbox we downloaded in summary this discussed the following topicsthe main pro...
16,808
this covers taking your first steps with two big data applicationshadoop and spark using python to write big data jobs building an interactive dashboard that connects to data stored in big data database over the last two we've steadily increased the size of the data in we worked with data sets that could fit into the m...
16,809
first steps in big data you to explore data from lenders of bank by the end of this you'll have gone through the following stepsload data into hadoopthe most common big data platform transform and clean data with spark store it into big data database called hive interactively visualize this data with qlik sensea visual...
16,810
distributing data storage and processing with frameworks hadoopa framework for storing and processing large data sets apache hadoop is framework that simplifies working with cluster of computers it aims to be all of the following things and morereliable--by automatically creating multiple copies of the data and redeplo...
16,811
first steps in big data it' possible to use the popular tool impala to query hive data up to times faster we won' go into impala in this bookbut more information can be found at impala iowe already had short intro to mapreduce in but let' elaborate bit here because it' such vital part of hadoop mapreducehow hadoop achi...
16,812
distributing data storage and processing with frameworks input files each line passed to mapper every key gets mapped to value of keys get sorted (or shuffledreduce (aggregatekey-value pairs collect output to file green blue greenblueblueorange greenredblueorange blue blue greenblue blue blue blueorange orange green gr...
16,813
first steps in big data what is sparkspark is cluster computing framework similar to mapreduce sparkhoweverdoesn' handle the storage of files on the (distributedfile system itselfnor does it handle the resource management for this it relies on systems such as the hadoop file systemyarnor apache mesos hadoop and spark a...
16,814
now let' dip our toes into loan data using hadoophiveand spark case studyassessing risk when loaning money enriched with basic understanding of hadoop and sparkwe're now ready to get our hands dirty on big data the goal of this case study is to have first experience with the technologies we introduced earlier in this a...
16,815
first steps in big data the default user and password are (at the time of writing"rootand "hadoop"respectively you'll need to change this password at the first loginthough once connectedissue the following commandsyum - install python-pip--this installs pipa python package manager pip install git+at the time of writing...
16,816
case studyassessing risk when loaning money accessible in dashboard toolthus enabling other people to explore it as well in sense this is the secondary goal of this caseopening up the data for self-service bi self-service business intelligence is often applied in data-driven organizations that don' have analysts to spa...
16,817
first steps in big data knowing exactly on which server as on normal file systemyou can createrenameand delete files and folders using the command line to interact with the hadoop file system let' first retrieve the currently present list of directories and files in the hadoop root folder using the command line type th...
16,818
case studyassessing risk when loaning money table list of common hadoop file system commands goal hadoop file system command local file system command change the permission of files hadoop fs -chmod mode uri chmod mode uri move or rename file hadoop fs -mv olduri newuri mv olduri newuri there are two special commands y...
16,819
first steps in big data we download the file "loanstats csv zipfrom the lending club' website at resources lendingclub com/loanstats csv zip and unzip it we use methods from the requestszipfileand stringio python packages to respectively download the datacreate virtual fileand unzip it this is only single fileif you wa...
16,820
figure retrieve file status on hadoop via the pyspark console with the file ready and waiting for us on hadoopwe can move on to data preparation using sparkbecause it' not clean enough to directly store in hive step data preparation now that we've downloaded the data for analysiswe'll use spark to clean the data before...
16,821
first steps in big data parts data map(lambda : split(',')firstline parts first(datalines parts filter(lambda : !firstlinedef cleans(row)row [ str(float(row [ ][:- ])/ return [ encode('utf 'replace( " ","lower(for in rowdatalines datalines map(lambda xcleans( )column (index has formatted numbers we don' need that sign ...
16,822
notice how similar this is to functional programming approach for those who've never encountered ityou can naively read lambda : split(','as "for every input ( row in this case)split this input when it encounters comma as in this case"for every inputmeans "for every row,but you can also read it as "split every row by c...
16,823
first steps in big data listing storing data in hive (fullcreates metadatathe spark sql structfield function represents field in structtype the structfield object is comprised of three fieldsname ( string)datatype ( datatype)and "nullable( booleanthe field of name is the name of structfield the field of datatype specif...
16,824
from pyspark sql types import fields [structfield(field_name,stringtype(),truefor field_name in firstlineschema structtype(fieldsschemaloans sqlcontext createdataframe(datalinesschemaschemaloans registertemptable("loans"with the metadata readywe're now able to insert the data into hive step execute queries and store ta...
16,825
first steps in big data figure windows hortonworks odbc configuration let' hope you didn' forget your sandbox passwordas you can see in figure you need it again now open qlik sense if installed in windows you should have gotten the option to place shortcut to the exe on your desktop qlik isn' freewareit' commercial
16,826
product with bait version for single customersbut it will suffice for now in the last we'll create dashboard using free javascript libraries qlik can either take the data directly into memory or make call every time to hive we've chosen the first method because it works faster this part has three steps load data inside...
16,827
first steps in big data confirmation box appears (figure if the app is created successfully figure box confirms that the app was created successfully click on the open app button and new screen will prompt you to add data to the application (figure figure start-adding-data screen pops up when you open new app click on ...
16,828
figure choose odbc as data source in the select data source screen figure choose hortonworks on the user dsn and specify the username and password
16,829
first steps in big data figure hive interface raw data column overview choose the hive dataand default as user in the next screen (figure select raw as tables to select and select every column for importthen click the button load and finish to complete this step after this stepit will take few seconds to load the data ...
16,830
figure an editor screen for reports opens substep adding selection filter to the report the first thing we'll add to the report is selection box that shows us why each person wants loan to achieve thisdrop the title measure from the left asset panel on the report pane and give it comfortable size and position (figure c...
16,831
first steps in big data substep adding kpi to the report kpi chart shows an aggregated number for the total population that' selected numbers such as the average interest rate and the total number of customers are shown in this chart (figure adding kpi to report takes four stepsas listed below and shown in figure choos...
16,832
in total we'll add four kpi charts to our reportso you'll need to repeat these steps for the following kpi'saverage interest rate total loan amount average loan amount total recoveries substep adding bar charts to our report next we'll add four bar charts to the report these will show the different numbers for each ris...
16,833
first steps in big data choose chart add measure choose an aggregation add dimension format figure adding bar chart takes five steps repeat this procedure for the following dimension and measure combinationsaverage interest rate per grade average loan amount per grade total loan amount per grade total recoveries per gr...
16,834
substep adding cross table to the report suppose you want to know the average interest rate paid by directors of risk group in this case you want to get measure (interest ratefor combination of two dimensions (job title and risk gradethis can be achieved with pivot table such as in figure figure an example of pivot tab...
16,835
first steps in big data choose chart add measure choose an aggregation add row dimension add column dimension figure adding pivot table takes six steps format
16,836
figure the end result in edit mode after resizing and repositioningyou should achieve result similar to figure click the done button on the left and you're ready to explore the data step explore the data the result is an interactive graph that updates itself based on the selections you make why don' you try to look for...
16,837
first steps in big data figure when we select directorswe can see that they pay an average rate of for loan figure when we select artistswe see that they pay an average interest rate of for loan
16,838
in this we got hands-on introduction to the hadoop and spark frameworks we covered lot of groundbut be honestpython makes working with big data technologies dead easy in the next we'll dig deeper into the world of nosql databases and come into contact with more big data technologies summary in this you learned that had...
16,839
this covers understanding nosql databases and why they're used today identifying the differences between nosql and relational databases defining the acid principle and how it relates to the nosql base principle learning why the cap theorem is important for multi-node database setup applying the data science process to ...
16,840
no doubt you've heard about nosql databases and how they're used religiously by many high-tech companies but what are nosql databases and what makes them so different from the relational or sql databases you're used tonosql is short for not only structured query languagebut although it' true that nosql databases can al...
16,841
join the nosql movement databases it' not the end of relational databases and certainly not the end of sqlas platforms like hive translate sql into mapreduce jobs for hadoop besidesnot every company needs big datamany do fine with small databases and the traditional relational databases are perfect for that if you look...
16,842
introduction to nosql as you've readthe goal of nosql databases isn' only to offer way to partition databases successfully over multiple nodesbut also to present fundamentally different ways to model the data at hand to fit its structure to its use case and not to how relational database requires it to be modeled to he...
16,843
join the nosql movement cap theoremthe problem with dbs on many nodes once database gets spread out over different serversit' difficult to follow the acid principle because of the consistency acid promisesthe cap theorem points out why this becomes problematic the cap theorem states that database can be any two of the ...
16,844
introduction to nosql local server fritz disconnection cap available but not consistentboth fritz and freddy order last available item local server freddy figure cap theoremif nodes get disconnectedyou can choose to remain availablebut the data could become inconsistent never receive it as good businesspersonyou might ...
16,845
join the nosql movement in all cases take popular festival such as tomorrowland festivals tend to have maximum allowed capacity for safety reasons if you sell more tickets than you're allowed because your servers kept on selling during node communication failureyou could sell double the number allowed by the time commu...
16,846
introduction to nosql consistent again in one node the data might say "aand in the other it might say "bbecause it was adapted laterat conflict resolution when the network is back onlineit' possible the "ain the first node is replaced by " even though no one did anything to explicitly change "ainto " ,it will take on t...
16,847
join the nosql movement nosql database types as you saw earlierthere are four big nosql typeskey-value storedocument storecolumn-oriented databaseand graph database each type solves problem that can' be solved with relational databases actual implementations are often combinations of these orientdbfor exampleis multi-m...
16,848
introduction to nosql column-oriented database traditional relational databases are row-orientedwith each row having row id and each field within the row stored together in table let' sayfor example' sakethat no extra data about hobbies is stored and you have only single table to describe peopleas shown in figure notic...
16,849
join the nosql movement column databases store each column separatelyallowing for quicker scans when only small number of columns is involvedsee figure row id birthday row id jos the boss name hobbies row id archery fritz von braun conquering the world freddy stark building things delphine thewiseone surfing swordplay ...
16,850
key value name jos the boss birthday hobbies archeryconquering the world figure key-value stores store everything as key and value the value in key-value store can be anythinga stringa numberbut also an entire new set of key-value pairs encapsulated in an object figure shows slightly more complex key-value structure ex...
16,851
join the nosql movement relational database approach comment table reader table article table author name author table document store approach "articles""title""title of the article""articleid" "body""body of the article""author""isaac asimov""comments""username""fritz"join date"""commentid" "body""this is great articl...
16,852
introduction to nosql can also be stored as single entitythis lowers the cognitive burden of working with the data for those used to seeing articles all the time examples of document stores are mongodb and couchdb graph databases the last big nosql database type is the most complex onegeared toward storing relations be...
16,853
figure join the nosql movement top databases ranked by popularity according to db-engines com in march figure shows that with entriesrelational databases still dominate the top at the time this book was writtenand with the coming of newsql we can' count them out yet neo jthe most popular graph databasecan be found at p...
16,854
data science process to work with the data and turn it into resource that' fast and easy to search here' how you'll apply the process setting the research goal data collection--you'll get your data from wikipedia there are more sources out therebut for demonstration purposes single one will do data preparation--the wik...
16,855
join the nosql movement elasticsearchthe open source search engine/nosql database to tackle the problem at handdiagnosing diseasethe nosql database you'll use is elasticsearch like mongodbelasticsearch is document store but unlike mongodbelasticsearch is search engine whereas mongodb is great at performing complex calc...
16,856
steps and data retrieval and preparation data retrieval and data preparation are two distinct steps in the data science processand even though this remains true for the case studywe'll explore both in the same section this way you can avoid setting up local intermedia storage and immediately do data preparation while t...
16,857
join the nosql movement data science process setting the research goal retrieving data errors from data entry physically impossible values missing values data cleansing outliers spacestyposerrors against codebook aggregating data data preparation extrapolating data data transformation derived measures creating dummies ...
16,858
now that you have an overview of the steps to comelet' get to work if you followed the instructions in the appendixyou should now have local instance of elasticsearch up and running first comes data retrievalyou need information on the different diseases you have several ways to get that kind of data you could ask comp...
16,859
join the nosql movement kneesspoiling the fun for everyone sending billions of requests at the same time is also one of the ways denial of service (doaattacks are performed if you do need to scrape websitescript in time gap between each page request this wayyour scraper more closely mimics the behavior of regular websi...
16,860
figure creating an elasticsearch index with python-elasticsearch needs to expect although this is true for simple casesyou can' avoid having schema in the long runso let' create oneas shown in the following listing listing adding mapping to the document type diseasemapping 'properties''name'{'type''string'}'title'{'typ...
16,861
join the nosql movement figure links on the wikipedia page lists of diseases it has more links than you'll need this page has considerable array of linksbut only the alphabetic lists interest youso keep only thosediseaselistarray [for link in dl links[ : ]trydiseaselistarray append(wikipedia page(link)except exception,...
16,862
case studywhat disease is thatfigure first wikipedia disease list"list of diseases ( - )figure shows the first entries of what you're afterthe diseases themselves diseaselistarray[ links it' time to index the diseases once they're indexedboth data entry and data preparation are effectively overas shown in the following...
16,863
join the nosql movement for several advanced elasticsearch features but also for quick lookup in the browser for exampletry this url in your browser % beta% hydroxylase% deficiency the title is indexed separatelyin most cases the link name and the page title will be identical and sometimes the title will contain an alt...
16,864
step data exploration it' not lupus it' never lupus--dr house of house data exploration is what marks this case studybecause the primary goal of the project (disease diagnosticsis specific way of exploring the data by querying for disease symptoms figure shows several data exploration techniquesbut in this case it' non...
16,865
join the nosql movement they're also temporarily stored within elasticsearch in case you use the same filter twice aggregations can be compared to the sql groupbuckets of words will be createdand for each bucket relevant statistics can be calculated each of these three compartments has loads of options and featuresmaki...
16,866
case studywhat disease is thatin searchbodywhich has json structureyou specify the fields you' like to see returnedin this case the name of the disease should suffice you use the query string syntax to search in all the indexed fieldsfulltexttitleand name by adding you can give each field weight if symptom occurs in th...
16,867
figure top three join the nosql movement lupus second search attempt with six results and lupus in the the results of the new search are shown in figure now the results have been narrowed down to six and lupus is in the top three at this pointthe search engine says human granulocytic ehrlichiosis (hgeis more likely hge...
16,868
case studywhat disease is thatfigure lupus third searchwith enough symptoms to determine it must be lupus handling spelling mistakesdamerau-levenshtein say someone typed "lupsuinstead of "lupus spelling mistakes happen all the time and in all types of human-crafted documents to deal with this data scientists often use ...
16,869
join the nosql movement of the number of times term is found in the result set as opposed to all the other documents this way elasticsearch profiles your result set by supplying the keywords that distinguish it from the other data let' do that on diabetesa common disease that can take many formslisting significant term...
16,870
simple query string searching for "diabetesin the disease name"query":"simple_query_string"query"'diabetes'"fields"["name" term filter filtering in all the diseases with "diabetesin the name"query":"filtered"filter"'term'{'name':'diabetes'although it won' show on the small amount of data at your disposalthe filter is w...
16,871
join the nosql movement awhile this waysubsequent requests with the same filter are even fasterresulting in huge performance advantage over search queries when should you use filters and when search queriesthe rule is simpleuse filters whenever possible and use search queries for full-text search when ranking between t...
16,872
relevant keywords for disease would be the actual definition and origin luckily we asked for keywordsso let' pick few more interesting ones such as ndi ndi is lowercased version of ndior "nephrogenic diabetes insipidus,the most common acquired form of diabetes lowercase keywords are returned because that' how they're s...
16,873
join the nosql movement needs to combine tokens to create -gramsalso called shingles the default elasticsearch tokenizer is called the standard tokenizerand it will look for word boundarieslike the space between wordsto cut the text into different tokens or terms take look at the new settings for your disease indexas s...
16,874
the analyzer shown in figure is the combination of all the operations required to go from input text to index it incorporates the shingle filterbut it' much more than this the tokenizer splits the text into tokens or termsyou can then use lowercase filter so there' no difference when searching for "diabetesversus "diab...
16,875
join the nosql movement client indices put_mapping(index=indexnamedoc_type=doctype,body=diseasemapping within fulltext you now have an extra parameterfields here you can specify all the different isotopes of fulltext you have only oneit goes by the name shingles and will analyze the fulltext with your new my_shingle_an...
16,876
step revisiteddata exploration for disease profiling you've once again arrived at data exploration you can adapt the aggregations query and use your new field to give you bigram key concepts related to diabeteslisting significant terms aggregation on "diabeteswith bigrams searchbody="fields":["name"]"query":"filtered"f...
16,877
join the nosql movement step presentation and automation your primary objectivedisease diagnosticsturned into self-service diagnostics tool by allowing physician to query it viafor instancea web application you won' build website in this casebut if you plan on doing soplease read the sidebar "elasticsearch for web appl...
16,878
of your project results the terms aren' weighted by their score in this casebut it already provides nice representation of the findings many improvements are possible for your applicationespecially in the area of data preparation but diving into all the possibilities here would take us too farthus we've come to the end...
16,879
this covers introducing connected data and how it' related to graphs and graph databases learning how graph databases differ from relational databases discovering the graph database neo applying the data science process to recommender engine project with the graph database neo where on one hand we're producing data at ...
16,880
introducing connected data and graph databases let' start by familiarizing ourselves with the concept of connected data and its representation as graph data connected data--as the name indicatesconnected data is characterized by the fact that the data at hand has relationship that makes it connected graphs--often refer...
16,881
the rise of graph databases relationships--this is the relationship between paul and jelme note that the relationship has directionit' paul who "knowsjelme and not the other way around user and user both represent people and could therefore be grouped labels--in graph databaseone can group nodes by using labels user an...
16,882
name "pauland traverse to cambodia via the relationship "has_been_inhence graph traversalwhich corresponds to database querywould be the following starting node--in this case the node with name property "paula traversal path--in this case path starting at node paul and going to cambodia end node--country node with name...
16,883
the rise of graph databases finding the right representation for your data since the early the most common type of database one had to rely on was relational one laterothers emergedsuch as the hierarchical database (for exampleims)and the graph database' closest relativethe network database (for exampleidmsbut during t...
16,884
relational database would rather strive for minimizing data redundancy this process is known as database normalizationwhere table is decomposed into smaller (less redundanttables while maintaining all the information intact in normalized database one needs to conduct changes of an attribute in only one table the aim of...
16,885
the rise of graph databases people table other ids first name last name id child id child id john mcbain wolf mcbain null arnold mcbain null moe mcbain null null null dave mcbain null null null jago mcbain null null null carl mcbain null null null find john mcbain figure use child ids to find wolf and arnold mcbain use...
16,886
decreasing popularity are neo jorientdband titan to showcase our case study we'll choose the most popular one at the moment of writing (see com/en/ranking/graph+dbmsseptember neo is graph database that stores the data in graph containing nodes and relationships (both are allowed to contain propertiesthis type of graph ...
16,887
the rise of graph databases figure neo interface with resolved query from the case study cyphera graph query language let' introduce cypher and its basic syntax for graph operations the idea of this section is to present enough about cypher to get us started using the neo browser at the end of this section you should b...
16,888
introducing neo ja graph database this query we'll start searching at the node user with the name property "paulnote how the node is enclosed within parenthesesas shown in the code snippet belowand the relationship is enclosed by square brackets relationships are named with colon (:prefixand the direction is described ...
16,889
the rise of graph databases we can insert the connected data in figure into neo by using cypher we can write cypher commands directly in the browser-based interface of neo jor alternatively through python driver (see databases to write an appropriate create statement in cypherfirst we should have good understanding of ...
16,890
cypher documentation to find out more about indexes and constraints (neo com/docs/stable/cypherdoc-labels-constraints-and-indexes htmlnow that we've created our datawe can query it the following query will return all nodes and relationships in the databasefind all nodes (nand all their relationships [rmatch ( )-[ ]-(re...
16,891
the rise of graph databases we can ask many questions here for examplequestion which countries has annelies visitedthe cypher code to create the answer (shown in figure is match( :user{name:'annelies'}[:has_been_in]-( :countryreturn namec name question who has been wherethe cypher code (explained in figure is match ()-...
16,892
this query is asking for all nodes with an outgoing relationship with the type "has_been_inmatch ()-[ :has_been_in]->(return limit the end nodes are all nodes with an incoming relationship of the type "has_been_infigure who has been wherequery buildup explained when we run this query we get the answer shown in figure f...
16,893
the rise of graph databases data the following query demonstrates how to delete all nodes and relationships in the databasematch(noptional match ( )-[ ]-(delete , now that we're acquainted with connected data and have basic knowledge of how it' managed in graph databasewe can go step further and look into reallive appl...
16,894
three data files ingredients txt)--self-compiled ingredients file recipes json)--contains all the ingredients elasticsearch index zip)--contains the "gastronomicalelasticsearch index you can use to skip data preparation part now that we have everything we needlet' look at the research goal and the steps we need to take...
16,895
the rise of graph databases our dish recommendations on the ingredientsoverlap in recipes network this is simple and intuitive approachyet already yields fairly accurate results let' look at the three data elements we require step data retrieval for this exercise we require three types of datarecipes and their respecti...
16,896
and so on we're only interested in the name and ingredients list sample recipe is shown in the following listing listing sample json recipe "_id"$oid" cc cc db }"name"drop biscuits and sausage gravy""ingredients"biscuits\ cups all-purpose flour\ tablespoons baking powder\ / teaspoon salt\ stick ( / cupcold buttercut in...
16,897
the rise of graph databases snippet in the following listing it' recommended not to run this code "as isin ipython (or jupyterbecause it prints every recipe key to the screen and your browser can handle only so much output either turn off the print statements or run in another python ide the code in this snippet can be...
16,898
connected data examplea recipe recommendation engine instancea recipe is called "lasagnathen this can be salmon lasagnabeef lasagnachicken lasagnaor any other type no single recipe is selected as the prototype lasagnathey are all uploaded to elasticsearch under the same name"lasagnathis is choiceso feel free to decide ...
16,899
the rise of graph databases "query":ingredientresult client search(index=indexname,doc_type=doctype,body=searchbodyprint ingredient print ingredientnumber print "totalstr(result['hits']['total']grandtotal grandtotal result['hits']['total'print "grand totalstr(grandtotalfor recipe in result['hits']['hits']loop through r...