├── .gitignore ├── bn-demo ├── run-demo.sh ├── bn-demo.R ├── adult.names └── dataprep.R ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # History files 2 | .Rhistory 3 | 4 | # Example code in package build process 5 | *-Ex.R 6 | 7 | # R data files from past sessions 8 | .Rdata 9 | -------------------------------------------------------------------------------- /bn-demo/run-demo.sh: -------------------------------------------------------------------------------- 1 | hadoop fs -rm -r adult.test 2 | hadoop fs -rm -r adult.out 3 | if [ $1 -eq -1 ]; 4 | then 5 | hadoop fs -put adult.test adult.test 6 | else 7 | head -$1 adult.test > temp1 8 | hadoop fs -put temp1 adult.test 9 | rm temp1 10 | fi 11 | export HADOOP_CMD=/usr/bin/hadoop 12 | export HADOOP_STREAMING=/usr/lib/hadoop-mapreduce/hadoop-streaming-*.jar 13 | Rscript bn-demo.R 14 | hadoop fs -getmerge adult.out adult.out 15 | -------------------------------------------------------------------------------- /bn-demo/bn-demo.R: -------------------------------------------------------------------------------- 1 | require(bnlearn) 2 | require(data.table) 3 | require(rmr2) 4 | source('dataprep.R') 5 | 6 | NUM_REDUCERS = 4 7 | 8 | # Function to trim leading + trailiing whitespace from string 9 | trim <- function (x) gsub("^\\s+|\\s+$", "", x) 10 | 11 | # Load input training set 12 | data = read.table("adult.data", sep=",",header=F, stringsAsFactors=F, 13 | col.names=c("age", "type_employer", "fnlwgt", "education", "education_num","marital", "occupation", "relationship", "race","sex", "capital_gain", "capital_loss", "hr_per_week","country", "income"), fill=FALSE,strip.white=T) 14 | 15 | # Convert raw fields into features, and represent as factors 16 | cvt_data = do.call(rbind.data.frame, lapply(as.list(1:dim(data)[1]), function(x) dataprep(data[x[1],]))) 17 | train = as.data.frame(lapply(cvt_data, factor)) 18 | 19 | # Whitelist 20 | wl = data.frame( 21 | from = c('income', 'occupation', 'hr_per_week', 'education', 'country', 'type_employer'), 22 | to = c('capital_gain', 'income', 'income', 'occupation', 'education', 'income') 23 | ) 24 | node_names = names(train) 25 | bl = data.frame( 26 | from = rep(node_names, 3), 27 | to = c(rep('race', length(node_names)), rep('age', length(node_names)), rep('sex', length(node_names))) 28 | ) 29 | 30 | # Learn network structure 31 | print("Learning structure") 32 | net = tabu(train, whitelist=wl, blacklist=bl, score='bde') 33 | 34 | # Learn parameters 35 | fitted = bn.fit(net, train, method="bayes", iss=5) 36 | 37 | # 38 | # Inference: 39 | # event to predict: income 40 | # evidence: all other non-NA variables 41 | # 42 | 43 | # Reduce: perform infernece one row at a time 44 | reduce_func <- function(., values) 45 | { 46 | out_klist = list() 47 | out_vlist = list() 48 | for (v in values) { 49 | 50 | # Increment counter so that Hadoop does not think reducer is "Dead" 51 | increment.counter('bn-demo', 'row', 1) 52 | 53 | fvec = sapply(strsplit(v, ',', fixed=T), trim) 54 | names(fvec)=c("age", "type_employer", "fnlwgt", "education", "education_num","marital", "occupation", "relationship", "race","sex", "capital_gain", "capital_loss", "hr_per_week","country", "income") 55 | pv = dataprep(fvec) 56 | 57 | # Generate evidence vector, and perform CPQuery() 58 | evidence = as.list(pv[1,setdiff(colnames(pv), 'income')]) 59 | prob = cpquery(fitted, event = (income == ">50K"), evidence = evidence, method="lw") 60 | 61 | # Update output key/value lists 62 | out_klist = c(out_klist, v) 63 | out_vlist = c(out_vlist, format(prob, digits=2)) 64 | } 65 | return (keyval(out_klist, out_vlist)) 66 | } 67 | 68 | # map: do-nothing, just transition to reducer with "dummy" key of age+country string 69 | map_func <- function(., values) 70 | { 71 | out_klist = list() 72 | out_vlist = list() 73 | for (v in values) { 74 | 75 | # Split row into fields 76 | fvec = unlist(strsplit(v, ',', fixed=T)) 77 | 78 | # Ignore if row does not have all fields 79 | if (length(fvec)<15) { next; } 80 | 81 | # Create new random key, and output key/value 82 | key = floor(runif(1,0,NUM_REDUCERS)) 83 | out_klist = c(out_klist, key) 84 | out_vlist = c(out_vlist, v) 85 | } 86 | return (keyval(out_klist, out_vlist)) 87 | } 88 | 89 | # 90 | # Inference with RMR 91 | # 92 | opt = rmr.options(backend = "hadoop", 93 | backend.parameters = list(hadoop=list(D="mapreduce.reduce.memory.mb=1024", 94 | D=paste0("mapreduce.job.reduces=", NUM_REDUCERS)))) 95 | inpFile = 'adult.test' 96 | outFile = 'adult.out' 97 | mapreduce(input=inpFile, input.format="text", 98 | output=outFile, output.format=make.output.format("csv", sep=","), 99 | map=map_func, reduce=reduce_func) 100 | -------------------------------------------------------------------------------- /bn-demo/adult.names: -------------------------------------------------------------------------------- 1 | | This data was extracted from the census bureau database found at 2 | | http://www.census.gov/ftp/pub/DES/www/welcome.html 3 | | Donor: Ronny Kohavi and Barry Becker, 4 | | Data Mining and Visualization 5 | | Silicon Graphics. 6 | | e-mail: ronnyk@sgi.com for questions. 7 | | Split into train-test using MLC++ GenCVFiles (2/3, 1/3 random). 8 | | 48842 instances, mix of continuous and discrete (train=32561, test=16281) 9 | | 45222 if instances with unknown values are removed (train=30162, test=15060) 10 | | Duplicate or conflicting instances : 6 11 | | Class probabilities for adult.all file 12 | | Probability for the label '>50K' : 23.93% / 24.78% (without unknowns) 13 | | Probability for the label '<=50K' : 76.07% / 75.22% (without unknowns) 14 | | 15 | | Extraction was done by Barry Becker from the 1994 Census database. A set of 16 | | reasonably clean records was extracted using the following conditions: 17 | | ((AAGE>16) && (AGI>100) && (AFNLWGT>1)&& (HRSWK>0)) 18 | | 19 | | Prediction task is to determine whether a person makes over 50K 20 | | a year. 21 | | 22 | | First cited in: 23 | | @inproceedings{kohavi-nbtree, 24 | | author={Ron Kohavi}, 25 | | title={Scaling Up the Accuracy of Naive-Bayes Classifiers: a 26 | | Decision-Tree Hybrid}, 27 | | booktitle={Proceedings of the Second International Conference on 28 | | Knowledge Discovery and Data Mining}, 29 | | year = 1996, 30 | | pages={to appear}} 31 | | 32 | | Error Accuracy reported as follows, after removal of unknowns from 33 | | train/test sets): 34 | | C4.5 : 84.46+-0.30 35 | | Naive-Bayes: 83.88+-0.30 36 | | NBTree : 85.90+-0.28 37 | | 38 | | 39 | | Following algorithms were later run with the following error rates, 40 | | all after removal of unknowns and using the original train/test split. 41 | | All these numbers are straight runs using MLC++ with default values. 42 | | 43 | | Algorithm Error 44 | | -- ---------------- ----- 45 | | 1 C4.5 15.54 46 | | 2 C4.5-auto 14.46 47 | | 3 C4.5 rules 14.94 48 | | 4 Voted ID3 (0.6) 15.64 49 | | 5 Voted ID3 (0.8) 16.47 50 | | 6 T2 16.84 51 | | 7 1R 19.54 52 | | 8 NBTree 14.10 53 | | 9 CN2 16.00 54 | | 10 HOODG 14.82 55 | | 11 FSS Naive Bayes 14.05 56 | | 12 IDTM (Decision table) 14.46 57 | | 13 Naive-Bayes 16.12 58 | | 14 Nearest-neighbor (1) 21.42 59 | | 15 Nearest-neighbor (3) 20.35 60 | | 16 OC1 15.04 61 | | 17 Pebls Crashed. Unknown why (bounds WERE increased) 62 | | 63 | | Conversion of original data as follows: 64 | | 1. Discretized agrossincome into two ranges with threshold 50,000. 65 | | 2. Convert U.S. to US to avoid periods. 66 | | 3. Convert Unknown to "?" 67 | | 4. Run MLC++ GenCVFiles to generate data,test. 68 | | 69 | | Description of fnlwgt (final weight) 70 | | 71 | | The weights on the CPS files are controlled to independent estimates of the 72 | | civilian noninstitutional population of the US. These are prepared monthly 73 | | for us by Population Division here at the Census Bureau. We use 3 sets of 74 | | controls. 75 | | These are: 76 | | 1. A single cell estimate of the population 16+ for each state. 77 | | 2. Controls for Hispanic Origin by age and sex. 78 | | 3. Controls by Race, age and sex. 79 | | 80 | | We use all three sets of controls in our weighting program and "rake" through 81 | | them 6 times so that by the end we come back to all the controls we used. 82 | | 83 | | The term estimate refers to population totals derived from CPS by creating 84 | | "weighted tallies" of any specified socio-economic characteristics of the 85 | | population. 86 | | 87 | | People with similar demographic characteristics should have 88 | | similar weights. There is one important caveat to remember 89 | | about this statement. That is that since the CPS sample is 90 | | actually a collection of 51 state samples, each with its own 91 | | probability of selection, the statement only applies within 92 | | state. 93 | 94 | 95 | >50K, <=50K. 96 | 97 | age: continuous. 98 | workclass: Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked. 99 | fnlwgt: continuous. 100 | education: Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool. 101 | education-num: continuous. 102 | marital-status: Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse. 103 | occupation: Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces. 104 | relationship: Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried. 105 | race: White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other, Black. 106 | sex: Female, Male. 107 | capital-gain: continuous. 108 | capital-loss: continuous. 109 | hours-per-week: continuous. 110 | native-country: United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands. 111 | -------------------------------------------------------------------------------- /bn-demo/dataprep.R: -------------------------------------------------------------------------------- 1 | # Adapted from http://scg.sdsu.edu/dataset-adult_r/ 2 | 3 | dataprep <- function(inp) { 4 | out = c() 5 | 6 | data = switch(as.character(inp['marital']), 7 | 'Never-married' = 'Never-Married', 8 | 'Married-AF-spouse' = 'Married', 9 | 'Married-civ-spouse' = 'Married', 10 | 'Married-spouse-absent' = 'Not-Married', 11 | 'Separated' = 'Not-Married', 12 | 'Divorced' = 'Not-Married', 13 | 'Widowed' = 'Widowed', 14 | 'Other') 15 | out['marital'] = data 16 | 17 | data = as.character(inp['country']) 18 | if (grepl('?',data,fixed=T)) { data = 'Unknown' } 19 | else { 20 | data = switch(as.character(inp['country']), 21 | "Cambodia" = "SE-Asia", 22 | "Canada" = "British-Commonwealth", 23 | "China" = "China", 24 | "Columbia" = "South-America", 25 | "Cuba" = "Other", 26 | "Dominican-Republic" = "Latin-America", 27 | "Ecuador" = "South-America", 28 | "El-Salvador" = "South-America", 29 | "England" = "British-Commonwealth", 30 | "France" = "Euro_1", 31 | "Germany" = "Euro_1", 32 | "Greece" = "Euro_2", 33 | "Guatemala" = "Latin-America", 34 | "Haiti" = "Latin-America", 35 | "Holand-Netherlands" = "Euro_1", 36 | "Honduras" = "Latin-America", 37 | "Hong" = "China", 38 | "Hungary" = "Euro_2", 39 | "India" = "British-Commonwealth", 40 | "Iran" = "Other", 41 | "Ireland" = "British-Commonwealth", 42 | "Italy" = "Euro_1", 43 | "Jamaica" = "Latin-America", 44 | "Japan" = "Other", 45 | "Laos" = "SE-Asia", 46 | "Mexico" = "Latin-America", 47 | "Nicaragua" = "Latin-America", 48 | "Outlying-US(Guam-USVI-etc)" = "Latin-America", 49 | "Peru" = "South-America", 50 | "Philippines" = "SE-Asia", 51 | "Poland" = "Euro_2", 52 | "Portugal" = "Euro_2", 53 | "Puerto-Rico" = "Latin-America", 54 | "Scotland" = "British-Commonwealth", 55 | "South" = "Euro_2", 56 | "Taiwan" = "China", 57 | "Thailand" = "SE-Asia", 58 | "Trinadad&Tobago" = "Latin-America", 59 | "United-States" = "United-States", 60 | "Vietnam" = "SE-Asia", 61 | "Yugoslavia" = "Euro_2", 62 | "Other") 63 | } 64 | out['country'] = data 65 | 66 | data = as.character(inp['education']) 67 | data = gsub("^10th","Dropout",data) 68 | data = gsub("^11th","Dropout",data) 69 | data = gsub("^12th","Dropout",data) 70 | data = gsub("^1st-4th","Dropout",data) 71 | data = gsub("^5th-6th","Dropout",data) 72 | data = gsub("^7th-8th","Dropout",data) 73 | data = gsub("^9th","Dropout",data) 74 | data = gsub("^Assoc-acdm","Associates",data) 75 | data = gsub("^Assoc-voc","Associates",data) 76 | data = gsub("^Bachelors","Bachelors",data) 77 | data = gsub("^Doctorate","Doctorate",data) 78 | data = gsub("^HS-Grad","HS-Graduate",data) 79 | data = gsub("^Masters","Masters",data) 80 | data = gsub("^Preschool","Dropout",data) 81 | data = gsub("^Prof-school","Prof-School",data) 82 | data = gsub("^Some-college","HS-Graduate",data) 83 | out['education'] = data 84 | 85 | data = as.character(inp['type_employer']) 86 | if (grepl('?',data,fixed=T)) { data = 'Unknown' } 87 | else { 88 | data = gsub("^Federal-gov","Federal-Govt",data) 89 | data = gsub("^Local-gov","Other-Govt",data) 90 | data = gsub("^State-gov","Other-Govt",data) 91 | data = gsub("^Private","Private",data) 92 | data = gsub("^Self-emp-inc","Self-Employed",data) 93 | data = gsub("^Self-emp-not-inc","Self-Employed",data) 94 | data = gsub("^Without-pay","Not-Working",data) 95 | data = gsub("^Never-worked","Not-Working",data) 96 | } 97 | out['type_employer'] = data 98 | 99 | data = as.character(inp['occupation']) 100 | if (grepl('?',data,fixed=T)) { data = 'Unknown' } 101 | else { 102 | data = gsub("^Adm-clerical","Admin",data) 103 | data = gsub("^Armed-Forces","Military",data) 104 | data = gsub("^Craft-repair","Blue-Collar",data) 105 | data = gsub("^Exec-managerial","White-Collar",data) 106 | data = gsub("^Farming-fishing","Blue-Collar",data) 107 | data = gsub("^Handlers-cleaners","Blue-Collar",data) 108 | data = gsub("^Machine-op-inspct","Blue-Collar",data) 109 | data = gsub("^Other-service","Service",data) 110 | data = gsub("^Priv-house-serv","Service",data) 111 | data = gsub("^Prof-specialty","Professional",data) 112 | data = gsub("^Protective-serv","Other-Occupations",data) 113 | data = gsub("^Sales","Sales",data) 114 | data = gsub("^Tech-support","Other-Occupations",data) 115 | data = gsub("^Transport-moving","Blue-Collar",data) 116 | } 117 | out['occupation'] = data 118 | 119 | data = switch(as.character(inp['race']), 120 | "White" = "White", 121 | "Black" = "Black", 122 | "Amer-Indian-Eskimo" = "Amer-Indian", 123 | "Asian-Pac-Islander" = "Asian", 124 | "Other") 125 | out['race'] = data 126 | 127 | data = as.numeric(inp['capital_gain']) 128 | if (data <= 0) { out['capital_gain'] = 'None' } 129 | else if (data <= 4100) { out['capital_gain'] = 'Low' } 130 | else if (data <= 5000) { out['capital_gain'] = 'Med' } 131 | else { out['capital_gain'] = 'High' } 132 | 133 | data = as.numeric(inp['capital_loss']) 134 | if (data <= 0) { out['capital_loss'] = 'None' } 135 | else if (data <= 1500) { out['capital_loss'] = 'Low' } 136 | else if (data <= 2000) { out['capital_loss'] = 'Med' } 137 | else { out['capital_loss'] = 'High' } 138 | 139 | out['sex'] = inp['sex'] 140 | out['relationship'] = inp['relationship'] 141 | out['income'] = gsub("50K.","50K",as.character(inp['income'])) 142 | out['age'] = as.character(cut(as.numeric(inp['age']), breaks=c(0, 18, 25, 34, 45, 50, 55, 60, 80, 120), right=F)) 143 | out['hr_per_week'] = as.character(cut(as.numeric(inp['hr_per_week']), breaks=c(0, 20, 40, 50, 60, 100), right=F)) 144 | 145 | df = data.frame(t(rep(NA, length(out)))) 146 | names(df) = names(out) 147 | df[1,] = out 148 | return(df) 149 | } 150 | 151 | 152 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Bayesian networks with R and Hadoop

2 | 3 | Welcome to my demo of Bayesian Networks with R and Hadoop. 4 | 5 | This page is accompanying my 2014 Hadoop Summit talk, about the same topic. In this page, I provide more details about the implementation, so that you can do-it-yourself. For the demo, I use the famous adult dataset. Please note that this dataset is not really large in the big-data sense, but I used it to exemplify the technique used, in a way that is easy to replicate the exercise on a single-node VM sandbox such as HDP Sandbox 6 | 7 | 8 |

Installation

9 | 10 | * Install HDP sandbox into VMWare or Virtualbox. For this demo, I've used HDP 2.1 Sandbox. 11 | * Make sure the HDP Sandbox on the VM has enough memory. At least 4GB is recommended, 8GB is better if possible. 12 | * Login to the sandbox with username=root, password=hadoop 13 | * as root, install R 14 | ``` 15 | yum update 16 | yum install R 17 | ``` 18 | * as root, install needed R packages 19 | ``` 20 | export JAVA_HOME=/usr/jdk64/jdk1.7.0_45/ 21 | R CMD javareconf 22 | R 23 | > install.packages(c("bnlearn", "data.table")) 24 | > install.packages(c("rJava", "Rcpp", "RJSONIO", "bitops", "digest", "functional", "stringr", "plyr", "reshape2", "caTools")) 25 | ``` 26 | * as root, install the RMR2 package 27 | ``` 28 | git clone https://github.com/RevolutionAnalytics/rmr2 29 | cd rmr2 30 | git checkout 3.1.0 31 | R CMD build pkg/ 32 | R CMD INSTALL rmr2_3.1.0.tar.gz 33 | ``` 34 | * Switch to guest user: 35 | ``` 36 | su - guest 37 | ``` 38 | 39 | * Clone this repository and move to demo folder: 40 | ``` 41 | git clone https://github.com/ofermend/bayes-net-r-hadoop/ 42 | cd bayes-net-r-hadoop/bn-demo 43 | ``` 44 | 45 | Note that the demo folder (bayes-net-r-hadoop/bn-demo) contains 6 files: 46 | * adult.dat: the training dataset 47 | * adult.test: validation dataset 48 | * adult.names: column descriptions 49 | * dataprep.R: R function to transform raw data into features 50 | * bn-demo.R: main R script to perform training and inference with RMR/Hadoop 51 | * run-demo.sh: shell script to execute the whole demo 52 | 53 |

Quick review of the code

54 | First we have to pre-process the data. For this demo, I adapted the general pre-processing flow described in this blog post. The final pre-processing step is implemented in the function dataprep() in dataprep.R. 55 | 56 | Now let's review bn-demo.R 57 | 58 |

Initialization

59 | * Starting off, we load the needed packages: bnlearn, data.table and rmr2. We also source the dataprep.R file so that we can call dataprep() 60 | * We define the trim() function to trim a string from leading or trailing whitespace 61 | ``` 62 | trim <- function (x) gsub("^\\s+|\\s+$", "", x) 63 | ``` 64 | * Loading the training data from the adult.data file: 65 | ``` 66 | data = read.table("adult.data", sep=",",header=F, stringsAsFactors=F, 67 | col.names=c("age", "type_employer", "fnlwgt", "education", "education_num","marital", "occupation", "relationship", "race","sex", "capital_gain", "capital_loss", "hr_per_week","country", "income"), fill=FALSE,strip.white=T) 68 | ``` 69 | * We then transform the raw dataset into the desired features, in the variable "train" 70 | ``` 71 | cvt_data = do.call(rbind.data.frame, lapply(as.list(1:dim(data)[1]), function(x) dataprep(data[x[1],]))) 72 | train = as.data.frame(lapply(cvt_data, factor)) 73 | ``` 74 | Note that we call dataprep() in the "lapply" row by row, and then rbind the results together into a single data frame. 75 | 76 |

Learning

77 | * We seed the network with a whilelist, and also define a few restrictions as a blacklist, and then use rsmax2() from bnlearn to learn the structure. 78 | ``` 79 | wl = data.frame( 80 | from = c('country', 'capital_gain', 'capital_loss', 'occupation', 'hr_per_week', 'education', 'sex', 'race', 'race'), 81 | to = c('race', 'income', 'income', 'income', 'income', 'occupation', 'hr_per_week', 'occupation', 'education') 82 | ) 83 | bl = data.frame( 84 | from = c('marital', 'sex', 'relationship', 'marital'), 85 | to = c('race', 'race', 'sex', 'sex') 86 | ) 87 | net = rsmax2(train, whitelist=wl, blacklist=bl, restrict='si.hiton.pc', maximize='tabu') 88 | ``` 89 | * Next, we learn the network probabilities - the CPT 90 | ``` 91 | fitted = bn.fit(net, train, method="bayes", iss=5) 92 | ``` 93 | We use the "bayes" method instead of the default, with the iss parameter set to 5. 94 | 95 |

Inference

96 | Now that we have the network structure and parameters, we move to perform inference with RMR and Hadoop. 97 | * Recall that our design is to use the mapper as a no-op (pass-through) it's more difficult to control the number of mappers. We use the reducers as the compute processes, and as we'll see later we can control the number of reducers quite easily with a parameter. Therefore our mapper is rather simple, using a random key to just pass the instances to any reducer for processing: 98 | ``` 99 | map_func <- function(., vals) 100 | { 101 | key_list = list(); val_list = list() 102 | for (v in vals) { 103 | fvec = unlist(strsplit(v, ',', fixed=T)) 104 | if (length(fvec)<15) { next; } 105 | key = floor(runif(1,0,MAX_REDUCERS)) 106 | key_list = c(key_list, key) 107 | val_list = c(val_list, v) 108 | } 109 | return (keyval(key_list, val_list)) 110 | } 111 | ``` 112 | * Our "reduce" function is where the real bayesian network inference occurs: 113 | ``` 114 | reduce_func <- function(., vals) 115 | { 116 | key_list = list(); val_list = list() 117 | for (v in vals) { 118 | increment.counter('bn-demo', 'row', 1) 119 | fvec = sapply(strsplit(v, ',', fixed=T), trim) 120 | names(fvec)=c("age", "type_employer", "fnlwgt", "education", "education_num","marital", "occupation", "relationship", "race","sex", "capital_gain", "capital_loss", "hr_per_week","country", "income") 121 | pv = dataprep(fvec) 122 | evidence = as.list(pv[1,setdiff(colnames(pv), 'income')]) 123 | write(paste(names(evidence), collapse="|", sep=""), stderr()) 124 | write(paste(evidence, collapse="|", sep=""), stderr()) 125 | prob = cpquery(fitted, event = (income == ">50K"), evidence = evidence, method="lw") 126 | key_list = c(key_list, v) 127 | val_list = c(val_list, format(prob, digits=2)) 128 | } 129 | return (keyval(key_list, val_list)) 130 | } 131 | ``` 132 | * Now let's look at the invocation of RMR: 133 | ``` 134 | opt = rmr.options(backend = "hadoop", 135 | backend.parameters = list(hadoop=list(D="mapreduce.reduce.memory.mb=1024", 136 | D=paste0("mapreduce.job.reduces=", NUM_REDUCERS)))) 137 | 138 | inpFile = 'adult.test' 139 | outFile = 'adult.out' 140 | mapreduce(input=inpFile, input.format="text", 141 | output=outFile, output.format=make.output.format("csv", sep=","), 142 | map=map_func, reduce=reduce_func) 143 | ``` 144 | 145 | In rmr.options(), we increase the memory for the reducer to 1GB. This of course may need to be adjusted depending on the size of your bayesian network. We also set the number of reducers to NUM_REDUCERS. For this demo on a VM we set it to 3, but of course in a real world situation and a large clsuter can be 50, 100 or more. The more reducers, the more parallelism you would get. 146 | 147 | Then we simply call rmr's mapreduce() function, giving it the input file, output file, mapper and reducer functions, and off we go. 148 | 149 |

running the demo: run-demo.sh

150 | I created a small script to execute the demo from start to finish. This script has a single parameter ($1) - a numeric with the number of rows for inference. For example, you can run this as follows: 151 | ``` 152 | ./run-demo.sh 100 153 | ``` 154 | Which will infer for the first 100 rows (instances) in the adult.test file. 155 | 156 | Let's look at this shell script: 157 | ``` 158 | hadoop fs -rm -r adult.test 159 | hadoop fs -rm -r adult.out 160 | if [ $1 -eq -1 ]; 161 | then 162 | hadoop fs -put adult.test adult.test 163 | else 164 | head -$1 adult.test > temp1 165 | hadoop fs -put temp1 adult.test 166 | rm temp1 167 | fi 168 | export HADOOP_CMD=/usr/bin/hadoop 169 | export HADOOP_STREAMING=/usr/lib/hadoop-mapreduce/hadoop-streaming-*.jar 170 | Rscript bn-demo.R 171 | hadoop fs -getmerge adult.out adult.out 172 | ``` 173 | * First, we remove any old files from HDFS, and copy the first $1 rows from adult.test into HDFS as "adult.test" 174 | * Then, we run the bn-demo.R script. Note that it will kick off the necessary map-reduce job with RMR. We need 2 export statements as you see above to let RMR know which Hadoop and streaming to use. 175 | * Finally, we copy back the output file from inference into the local folder so we can review it. 176 | 177 | Let's take a look at the output: 178 | ``` 179 | Loading required package: bnlearn 180 | Loading required package: data.table 181 | Loading required package: rmr2 182 | Loading required package: Rcpp 183 | Loading required package: RJSONIO 184 | Loading required package: bitops 185 | Loading required package: digest 186 | Loading required package: functional 187 | Loading required package: reshape2 188 | Loading required package: stringr 189 | Loading required package: plyr 190 | Loading required package: caTools 191 | [1] "Learning structure" 192 | 14/05/23 13:30:28 WARN streaming.StreamJob: -file option is deprecated, please use generic option -files instead. 193 | packageJobJar: [/tmp/RtmpuxcDAa/rmr-local-env46c4298421ad, /tmp/RtmpuxcDAa/rmr-global-env46c467216c19, /tmp/RtmpuxcDAa/rmr-streaming-map46c45461b065, /tmp/RtmpuxcDAa/rmr-streaming-reduce46c47bfd5d57] [/usr/lib/hadoop-mapreduce/hadoop-streaming-2.4.0.2.1.1.0-385.jar] /tmp/streamjob5500124204348219433.jar tmpDir=null 194 | 14/05/23 13:30:29 INFO client.RMProxy: Connecting to ResourceManager at sandbox.hortonworks.com/172.16.102.144:8050 195 | 14/05/23 13:30:30 INFO client.RMProxy: Connecting to ResourceManager at sandbox.hortonworks.com/172.16.102.144:8050 196 | 14/05/23 13:30:30 INFO mapred.FileInputFormat: Total input paths to process : 1 197 | 14/05/23 13:30:30 INFO mapreduce.JobSubmitter: number of splits:2 198 | 14/05/23 13:30:30 INFO Configuration.deprecation: mapred.textoutputformat.separator is deprecated. Instead, use mapreduce.output.textoutputformat.separator 199 | 14/05/23 13:30:31 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1400605562649_0005 200 | 14/05/23 13:30:31 INFO impl.YarnClientImpl: Submitted application application_1400605562649_0005 201 | 14/05/23 13:30:31 INFO mapreduce.Job: The url to track the job: http://sandbox.hortonworks.com:8088/proxy/application_1400605562649_0005/ 202 | 14/05/23 13:30:31 INFO mapreduce.Job: Running job: job_1400605562649_0005 203 | 14/05/23 13:30:38 INFO mapreduce.Job: Job job_1400605562649_0005 running in uber mode : false 204 | 14/05/23 13:30:38 INFO mapreduce.Job: map 0% reduce 0% 205 | 14/05/23 13:30:50 INFO mapreduce.Job: map 67% reduce 0% 206 | 14/05/23 13:30:51 INFO mapreduce.Job: map 100% reduce 0% 207 | 14/05/23 13:30:58 INFO mapreduce.Job: map 100% reduce 25% 208 | ``` 209 | Here is an example of 6 rows from adult.out: 210 | ``` 211 | 43, Private, 346189, Masters, 14, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 50, United-States, >50K.,0.75 212 | 40, Private, 85019, Doctorate, 16, Married-civ-spouse, Prof-specialty, Husband, Asian-Pac-Islander, Male, 0, 0, 45, ?, >50K.,0.64 213 | 34, Private, 238588, Some-college, 10, Never-married, Other-service, Own-child, Black, Female, 0, 0, 35, United-States, <=50K.,0.0019 214 | 23, Private, 134446, HS-grad, 9, Separated, Machine-op-inspct, Unmarried, Black, Male, 0, 0, 54, United-States, <=50K.,0.085 215 | 54, Private, 99516, HS-grad, 9, Married-civ-spouse, Craft-repair, Husband, White, Male, 0, 0, 35, United-States, <=50K.,0.099 216 | 46, State-gov, 106444, Some-college, 10, Married-civ-spouse, Exec-managerial, Husband, Black, Male, 7688, 0, 38, United-States, >50K.,0.93 217 | ``` 218 | Notice that for each row, the one-before-last column is the original income level (two values: "<=50K" or ">50K") - this is what we're trying to predict. The last column (which was added by our script output) is the (predicted) likelihood that this person's income is higher than 50K. You can find the full solution file at bn-demo/adult-solution.out. 219 | 220 |

Summary

221 | I hope you enjoyed this walk-through of using R, RMR and Hadoop to infer with Bayesian Networks. 222 | I'd love to hear of your own experiences applying these techniques to other problems in your domain. 223 | 224 | 225 | 226 | --------------------------------------------------------------------------------