Image from Microsoft

by George Taniwaki

This post describes the final six classes I took to obtain the Microsoft Artificial Intelligence Certificate. Four were required and two were optional. For a description of the first six classes I took, see this May 2019 blog post.

DAT236x – Deep Learning Explained

Deep learning is the use of machine learning on large datasets, often using neural networks. It is used in fields such as computer vision, speech recognition, and language processing (topics covered in more detail in later classes). Techniques include logistic regression, multilayer perceptron, convolutional neural networks, recurrent neural networks, and long short-term memory.

Time: 10 hours on 6 modules

Score: Missed 4 homework questions and 2 knowledge check questions for a score of 92%

DAT257x – Reinforcement Learning Explained

Reinforcement learning assumes a problem can be modeled as a Markov decision process. There is a set of discrete states (S), an agent that can perform a set of actions (A) selected from a set of decision policies (Π). Each possible action will result in a reward (R) and a new state (S’). The goal is to find the optimum policy π(s) for all s in S or to determine if a given policy is optimal.

Solutions to the reinforcement learning problem include use of multi-arm bandits, regret minimization, dynamic programming (Bellman equation), policy evaluation and optimization, linear function approximation, deep neural networks, and deep Q-learning. Advanced topics include likelihood ratio methods, variance reduction, and actor-critic.

I have an undergraduate degree in chemical engineering where I learned about control theory and Markov chains. However, that coursework only covered analog PID controllers. The topics in this class were new to me and so it was slow going.

Time: 16 hours for 10 modules

Score: Missed 7 knowledge check questions early on, then slowed down and got the rest right. Missed 3 lab questions. Final score of 91%

DEV287x – Speech Recognition Systems

Speech recognition is an interdisciplinary activity that combines signal processing, acoustics, linguistics, and domain knowledge with computer science. The topics covered in this course include:

  1. Fundamental theory – Phonetics, words and syntax, performance metrics
  2. Speech signal processing – Feature extraction, mel filtering, log compression, Feature normalization
  3. Acoustic modeling – Markov chains, feedforward deep neural networks, sequence based objective function
  4. Language modeling – N-gram models, language model evaluation (likelihood, entropy, perplexity), LM operations (n-gram pruning, interpolating probabilities, merging), class-based LMs, neural network LMs
  5. Speech decoding – Weighted finite state transducers, WFST and acceptors, graph composition
  6. Advanced topics – Improved objective functions, sequential objective function, sequence discriminative objective functions

This class was pretty awful and I’m glad I didn’t pay for it. It consists mostly of text displayed in the edX courseware. It would have been helpful to if video or audio lectures were included to show voice recognition in action. The text itself was a split into multiple web pages containing embedded MathML equations, making is unsearchable. I ended up copying and pasting all the text into a Word document.

The lab assignments in this class are provided as Python files designed for Linux. Some labs require a Linux shell and would not run in Visual Studio on Windows. I would expect instructors in a Microsoft sponsored course to design lessons that could run on Windows. Simply putting the code in Jupyter notebooks would have made it easier to read and to work with.

Some labs require a Python package called OpenFST that does not compile with the latest build tools available from Microsoft. Again, I would expect instructors to design lessons that could run on Windows.

Time: 6 hours for 6 modules

Score: None, I did not take this class for credit

DEV288x – Natural Language Processing (NLP)

Natural language processing consists of many separate but related tasks. These include transcription, translation, conversation, and image captioning.

Machine translation has evolved from conventional statistical machine translation (STM) that uses hand-coded phrase pairs, to neural machine translation that use deep neural networks to create end-to-end sequence probabilities to translate entire sentences at a time.

The deep semantic similarity model (DSSM) is a DNN model for representing text strings as vectors. It can be used for information retrieval and entity ranking tasks.

Natural language understanding requires spoken language processing, continuous word representations, neural knowledgebase embedding, and KB-based question answering. NLP can be enhanced using deep reinforcement learning.

Finally, image captioning requires multimodal intelligence, combining image recognition and assigning labels to images in a natural language format.

Time: 10 hours for 6 modules

Score: None, I did not take this class for credit

DEV290x – Computer Vision and Image Analysis

This course is an excellent overview of the state-of-the-art in computer vision. It starts with a description of classical methods including thresholding, clustering, region growing, template matching, and feature detection (Sobel edges and Harris corners).

Next it covers object classification and detection algorithms such as Viola-Jones, histogram of oriented gradients (HOG), deep learning, extending classifiers into detectors, object proposals, and introduces convolutional neural networks (CNN).

Finally, the course introduces advanced topics such as super-pixels and conditional random fields, deep segmentation, and transfer learning.

Time: 10 hours for 20 modules

Score: Missed 4 quiz questions and 1 final exam question for a score of 94%

DAT264x – Microsoft Professional Capstone : Artificial Intelligence

This is the last class for the certificate. Similar to the capstone for the Microsoft Data Science certificate, it is a month-long project designed as a contest hosted by datasciencecapstone.org. Unlike the capstone class for the Data Science certificate, there is no report, the grade is based solely on the contest score. For a description of the April 2019 contest, see this [future date] blog post.

I used Microsoft’s cognitive neural toolkit (CNTK) package for Python for my solution. I had a hard time debugging my code. CNTK is not as popular as Google’s Tensorflow, so searching error messages on the web gives few results.

Time: 30 hours for single assignment

Score: Log-loss error of 0.22 for a final score of 95%

Final certificate

Below is my certificate of completion for the Microsoft Professional Program, Artificial Intelligence Certificate, guid b5499a34-5674-4993-bfe9-66ed514f96db.

* * * *

As an aside, starting in January 2019, edX has changed the way it handles students who audit courses. To encourage more students to pay for its courses, edX now limits access to course content to 30 days after enrollment. After 30 days, you lose access, even if you have posted items on the discussion board. Further, it eliminated access to the assessment content (quizzes, labs, and exams) entirely unless you pay. This sucks.

I hope Microsoft will provide funding to edX to allow audit students to participate. Or Microsoft should stop working with edX and move its content to another MOOC platform that supports audit students. I’ve paid over $2000 to participate in the edX courses. But I always audit a course before paying for the content. I think the try-before-you-buy model is essential to get students to trust they will get their money’s worth. Preventing audit students from seeing the assessment content will make it difficult to gain their trust in the value of that content.

Image from Microsoft

by George Taniwaki

After completing the requirements for the Microsoft Data Science Certificate (see Jul 2017 blog post), I decided to continue my training and obtain a Microsoft Artificial Intelligence Certificate.

The AI certificate is similar to the Data Science certificate. It consists of ten courses with content produced by Microsoft and administered by edX. However, unlike the data science courses, none of the AI course assignments use the drag-and-drop Azure Machine Learning interface. Instead, most projects require Python programming ability. A summary of my progress in the first six classes is shown below.

DAT 263x – Introduction to Artificial Intelligence (AI)

This is a brief overview of artificial intelligence and a plug for the Azure services that support AI. It covers the following topics:

  1. Machine learning – Azure machine learning studio
  2. Language – text processing, natural language processing, Azure language understanding intelligent services (LUIS)
  3. Computer vision – Image processing, Azure face detection and recognition, Azure video indexer
  4. Conversation – Microsoft Bot Framework, Cortana skills  (Text analytics API, Linguistic analysis API, Bing speech-to-text, text-to-speech, translation)
  5. Deep learning – Microsoft cognitive toolkit (CNTK), Azure Data science virtual machine

Oddly, none of the classes that follow use any of the Azure services introduced in this course. Instead, most rely on Python code contained in Jupyter notebooks.

Another quibble. I work at Microsoft (but not for Microsoft since I am a contractor) and most Azure subscriptions are not available to me. Who knows why Microsoft lets me create an account but then doesn’t give me access to resources. See screenshot below.

Time: 6 hours for 4 modules

Score: No missed question for score of 100%

DAT 208x – Introduction to Python for Data Science

This is a DataCamp course using an interactive window for quizzes and a timed final exam. (For my earlier experiences with DataCamp courses, see DAT209x in this Jul 2018 blog post.) The topics covered in this Python course are lists, functions and methods, flow control, installing packages, arrays using NumPy, graphing using MatPlotLib, and dataframes using Pandas.

Time: 12 hours for 20 modules

Score: 100% on the quizzes and labs. Missed 7 on final exam for combined score of 94%

DAT 256x – Essential Math for Machine Learning: Python Edition

This basic math course covers algebra, calculus, tensors, eigenvectors and eigenvalues, statistics, probability theory, sampling, and hypothesis testing. All lessons use Python in Jupyter notebooks.

Time: 8 hours for 4 modules

Score: Missed 1 question for score of 97%

DAT249x – Ethics and Law in Data and Analytics

This is a new course that is now required for both the data science certificate and the artificial intelligence certificate. It covers privacy (including GDPR), explainability (XAI), and power and trust (bias). The course is taught using the traditional legal framework called Issue, Rule, Application, Conclusion (IRAC).

Time: 5 hours for 4 modules

Score: No error in the labs and missed 2 questions on the final exam for 96%

DAT203.1x – Data Science Essentials

I took this class as part of my certificate for Data Science. See my Jul 2017 blog post for details.

DAT203.2x – Principles of Machine Learning

I took this class as part of my certificate for Data Science. See my Jul 2018 blog post for details.

For my results in the remaining classes, see Microsoft Artificial Intelligence Certificate-Part 2

Image from Microsoft

by George Taniwaki

I have now completed all ten classes required to receive the Microsoft Data Science Certificate. As a newly minted data scientist, I am ready to dig into large datasets and make incredible (and if I am not careful, potentially unverifiable) predictions. A description of the four I took during the past two quarters is shown below. (For a list of the first six classes I took, see this Jul 2017 blog post.)

DAT209x – Programming with R for Data Science

This class is a continuation of DAT204x. Topics covered include functions and data structures, loops and flow control, working with vectors and matrices, reading and writing data files, reading SQL databases, manipulating data (i.e., merging, subsetting, filtering, introduction to grep and text functions, using date and time functions, aggregating, grouping, and summarizing), simulation, linear models, and graphics.

The final exam for this course used the same DataCamp-based timed format as in DAT204x. I didn’t do well on that test, but felt confident going in this time because I was prepared for it. Unfortunately, I ended up failing the test because I could not answer the first question and then could not navigate past it. After spending over half an hour trying to resolve the issue and contacting tech support (which promised a reply within 24 hours but never responded), I gave up. How annoying. Luckily, it didn’t matter since I already had enough points to pass the class. If I was susceptible to test anxiety, this would have been a traumatic experience.

Time: 12 hours for 12 modules

Score: 100% on all exercises (not graded) and labs. Missed 1 quiz question because my instance of the ggplot2 library behaved differently than the one used in class. Got zero on the final exam (see above) for a combined score of 79%

DAT203.2x – Principles of Machine Learning

This class is a continuation of DAT203.1x. It covers the the theory and application (using Microsoft Azure Machine Learning) of popular classification models including logistic regression, boosted decision trees, neural networks, and support vector machines (SVM). The models are tuned (that is, optimized for accuracy on the data outside the training set) using permutation, regularization, and cross-validation, which are all ensemble learning methods.

The class covers the two most popular continuous models, regression and random forest. Beyond prediction models, the class covers K-mean clusters and the matchbox recommender system developed by Microsoft Research.

Similar to my experience with DAT203.1x, I am really impressed with the power of MAML but a bit disappointed in the cookbook nature of the labs in the class.

The final exam was an assignment to create a prediction model for the number of minutes difference between the actual arrival time and the scheduled arrival time for commercial airline flights. The grade was based on quality of the predictions for 25 flights outside the training set. The final was graded with one point for each prediction that was within 10 minutes of the actual arrival time.

My model had a mean absolute error of about 8.5 (a bit high since the goal is to get within 10 minutes), but I got 22 out of 25 predictions within the allowed range (88%). I am guessing that with more engineering effort I could reduce my error size. For instance, I could have created a categorical variable for gate load that segmented flight arrivals into weekday morning (a busy time), weekday midday, weekday evening (also busy), weekend day, any night, and heavy traffic days before and after major holidays.

But I don’t think those improvements would help with the 3 cases that my model got wrong. They appear to be outliers that could not be predicted using the variables at hand. A better prediction would need to include variables that were not available in the dataset like weather at the arrival airport, airport construction status, and if any landing restrictions were in effect at the airport that day.

Time: 12 hours for 6 modules

Score: 100% on the 6 labs, 88% accuracy in final model, and 100% on 2 surveys, for a combined score of 95%

DAT203.3x – Applied Machine Learning

This class is a continuation of DAT203.2x. It consists of four distinct modules. The first introduces time series analysis with emphasis on seasonal decomposition of time series using LOESS (STL) and transforming the data into a stationary process using autoreressive integrated moving average (ARIMA).

Next, the class covers spatial data analysis with interpolation using kernel density estimation and K-nearest neighbor. The data is modeled using spatial Poisson process, variograms, and Kriging. The resulting output can be displayed using dot maps, bubble maps, heat maps, and chloropleth maps. The analysis is done using R in both a Jupyter notebook in MAML and as a stored procedure in SQL Server 2016 R services and R script in Power BI .

The third module covers text analysis. English text is processed using text normalization, removing stop words, and stemming. These methods may not be applicable in other languages or scripts. Once the text is clean, the text can be analyzed for word frequency, word importance, named entity recognition, text mining, and sentiment analysis. All of these techniques are used in natural language processing.

The final module introduces image processing and image analysis using Python routines in matplotlib. Example techniques include denoising using convolution with Gaussian blur or median filter and prewhitening using Gaussian noise. Python code is used to show how to resize and rotate images. Feature extraction is demonstrated using Sobel edge detection, segmentation, and Harris corner detection. The basic image morphology operators are introduced, including dilation, eroding, opening, and closing. The course also introduces the cognitive services APIs available in Azure portal and how to access them using Python and C#.

Time: 12 hours for 4 modules

Score: 100% on the 4 labs and missed one question on the final exam for a combined score of 95%

DAT102x – Data Science Professional Capstone

This is the tenth and final course needed to receive the Microsoft Data Science Certificate. The class lasts one month and consists of a machine learning contest and report. The project changes every quarter. For a description of the April contest, see the 3 part blog entry that starts  June 2018.

Time: 10 hours for creating a machine learning model and writing the report

Score: Missed one question in the data analysis section (because the mean and standard deviation had to be reported to six decimal places and I only entered them to 2 decimals), scored 86% on my machine learning model, and 100% on my report graded by 3 class peers, for a final score of 91%

Final Certificate

And below is the Data Science Certificate, guid 9855e15f-fddd-41f6-8bd8-6e3c3b5d76ca.

Town of Barpak after Gorkha earthquake. Image from The Telegraph (UK)

by George Taniwaki

This is the final set of my notes from a machine learning class offered by edX. Part 1 of this blog entry is posted in June 2018.

Step 7: Optimize model

At the end of step 6, I discovered that none of my three models met the minimum F score (at least 0.60) needed to pass the class. Starting with the configuration shown in Figure 5, I modified my experiment by replacing the static data split with partition and sampling using 10 evenly split folds. I used a random seed of 123 to ensure reproducibility.

I added both a cross-validation step and a hyperparameter tuning step to optimize results. To improve performance, I added a Convert to indicator values module. This converts the categorical variables into dummy binary variables before running the model.

Unfortunately, the MAML ordinal regression module does not support hyperparameter tuning. So I replaced it with the one-vs-all multiclass classifier. The new configuration is shown in Figure 6 below. (Much thanks to my classmate Robert Ritz for sharing his model.)

Figure 6. Layout of MAML Studio experiment with partitioning and hyperparameter tuning steps

For an explanation of how hyperparameter tuning works, see Microsoft documentation and MSDN blog post.

Model 5 – One-vs-all multiclass model using logistic regression classifier

In the earlier experiments, the two-class logistic regression classifier gave the best results. I will use it again with the one-vs-all multiclass model. The default parameter ranges for the two-class logistic regression classifier are: Optimization tolerance = 1E-4, 1E-7, L1 regularization weight = 0 .01, 0.1, 1.0, L2 regularization weight = 0.01, 0.1, 1.0, and memory size for L-BFGS = 5, 20, 50.

Truth tableIs 1Is 2Is 3TOTAL
Predict 129615620472
Predict 2621463316516905
Predict 32184717552623
TOTAL9365636342610000
Table 12a. Truth table for one-vs-all multiclass model using logistic regression classifier
PerformanceValue
Avg Accuracy0.76
F1 Score0.64
F1 Score (test data)Not submitted
Table 12b. Performance measures for one-vs-all multiclass model using logistic regression classifier

The result is disappointing. The new model has an F1 score of 0.64, which is lower than the F1 score of the ordinal regression model using the logistic regression classifier.

Model 6 – Add geo_level_2 to model

Originally, I excluded geo_level_2 from the model even though the Chi-square test was significant because it consumed too many degrees of freedom. I rerun the experiment with the variable and keeping all other variables and parameters the same.

Truth tableIs 1Is 2Is 3TOTAL
Predict 135521827600
Predict 2564466214466672
Predict 31975619532728
TOTAL9385636342610000
Table 13a. Truth table for one-vs-all multiclass model using logistic regression classifier and including geo_level_2
PerformanceValue
Avg Accuracy0.80
F1 Score0.70
F1 Score (test data)Not submitted
Table 13b. Performance measures for one-vs-all multiclass model using logistic regression classifier and including geo_level_2

The resulting F1 score using the test dataset is 0.70, which is better than any prior experiments and meets our target of 0.70 exactly.

Model 7 – Add height/floor to the model

I will try to improve the model by adding a variable measuring height/floor. This variable is always positive, skewed toward zero and has a long tail. To normalize it, I apply the natural log transform and name the variable ln_height_per_floor. Table 14 and Figure 7 show the summary statistics.

Variable nameMinMedianMaxMeanStd dev
ln_height_per_floor-1.790.692.300.760.25
Table 14. Descriptive statistics for ln_height_per_floor
Figure 7. Histogram of ln_height_per_floor

I run the model again with no other changes.

Truth tableIs 1Is 2Is 3TOTAL
Predict 136622728621
Predict 2557464014366633
Predict 31576919622746
TOTAL9385636342610000
Table 15a. Truth table for one-vs-all multiclass model using logistic regression classifier, including geo_level_2, height/floor
PerformanceValue
Avg Accuracy0.80
F1 Score0.70
F1 Score (test data)Not submitted
Table 15b. Performance measures for one-vs-all multiclass model using logistic regression classifier, including geo_level_2, height/floor

The accuracy of predicting damage_level = 1 or 3 increases, but the accuracy of 2 decreases. Resulting in no change in average accuracy or the F1 score.

Model 8 – Go back to ordinal regression

The accuracy of the one-vs-all multiclass model was significantly improved by adding geo_level_2. Let’s see what happens if I add this variable to the ordinal regression model which produced a higher F1 score than the one-vs-all model.

Truth tableIs 1Is 2Is 3TOTAL
Predict 180591140
Predict 222715575422326
Predict 33246585834
TOTAL310186211283300
Table 16a. Truth table for ordinal regression model using logistic regression classifier, including geo_level_2, height/floor
PerformanceValue
Avg Accuracy0.78
F1 Score0.67
F1 Score (test data)Not submitted
Table 16b. Performance measures for ordinal regression model using logistic regression classifier, including geo_level_2, height/floor

Surprisingly, ordinal regression produces worse results when the geo_level_2 variable is included than without it.

Model 9 – Convert numeric to categorical

I spent a lot of effort adjusting and normalizing my numeric variables. They were mostly integer values with small range and did not appear to be correlated to damage_grade. Could the model be improved by treating them as categorical? Let’s find out.

First I perform a Chi Square test to confirm all of the variables are significant. Then run the model after converting all the values from numeric to strings, and converting all the variables from numeric to categorical.

Variable nameChi-squareDeg. of freedomP value
count_floor_pre_eq49514< 2.2E-16*
height36737< 2.2e-16*
age69060< 2.2e-16*
area738314< 2.2e-16*
count_families76141.3e-10*
count_superstructure104147.1e-16*
count_secondary_use7943.6e-16*
Table 17. Chi-square results of numerical values to damage_grade

*One or more enums have sample sizes too small to use Chi-square approximation
[ ] P value greater than 0.05 significance level

Truth tableIs 1Is 2Is 3TOTAL
Predict 183623148
Predict 222415445402308
Predict 33256585844
TOTAL310186211283300
Table 18a. Truth table for ordinal regression model using logistic regression classifier, including geo_level_2, height/floor, and converting numeric to categorical
PerformanceValue
Avg Accuracy0.78
F1 Score0.67
F1 Score (test data)Not submitted
Table 18b. Performance measures for ordinal regression model using logistic regression classifier, including geo_level_2, height/floor, and converting numeric to categorical

Changing the integer variables to categorical has almost no impact on the F1 score.

Conclusion

Table 19 below summarizes all nine models I built. Six of them achieved an F1 score of 0.60 or higher on the training data, which would probably have been sufficient to pass the class. Two of them had F1 score of 0.70 which would be a grade of 95 out of 100.

I was unable to run most of these models on the test dataset and submit the results to the data science capstone website. Thus, I do not know what my leaderboard F1 score would be. It is possible that I overfit my model to the training data and my leaderboard F1 score might be lower.

Finding the best combination of variables, models, and model hyperparameters is difficult to do manually. It took me several hours to build the nine models described in this blog post. Machine learning automation tools exist but are not yet robust, nor built into platforms like MAML Studio. (Much thanks again to Robert Ritz who pointed me to TPOT, a Python-based tool for auto ML.)

ModelVariablesAlgorithmTraining dataF1 score (test data)
1NoneNaïve guess = 2None0.56
327 from Table 5Ordinal regression with decision forest0.67 split0.64
427 from Table 5Ordinal regression with SVM0.67 split0.57 (0.5644)
227 from Table 5Ordinal regression with logistic regression0.67 split0.68 (0.5687)
527 from Table 5One-vs-all multiclass with logistic regression, hyperparameter tuning10-fold partition0.64
627 from Table 5, plus geo_level_2One-vs-all multiclass with logistic regression, hyperparameter tuning10-fold partition0.70
727 from Table 5, plus geo_level_2, height/floorOne-vs-all multiclass with logistic regression, hyperparameter tuning10-fold partition0.70
827 from Table 5, plus geo_level_2, height/floorOrdinal regression with logistic regression0.67 split0.67
927 from Table 5, plus convert numeric to categorical, geo_level_2, height/floorOrdinal regression with logistic regression0.67 split0.67
Table 19. Summary of models. Green indicates differences from base case, model 2
Damage caused by Gorkha earthquake. Image by Prakash Mathema/AFP/Getty Images

by George Taniwaki

This is a continuation of my notes for a machine learning class offered by edX. Part 1 of this blog entry is posted in June 2018.

Step 4: Multivariate analysis

Pairwise scatterplots of the numerical variables after adjusting and normalizing are shown in Figure 4 below. The dependent variable (damage_grade) does not appear to be correlated with any of the numerical independent variables. Despite the lack of correlation, I included all the numeric variables when building the model. If I have time, I will convert these numerical variables into categorical ones.

Among the independent variables, covariance is highest between count_floors_pre_eq and height highlighted in green. This makes sense, taller buildings are likely to have more floors. If I have time, I will add a new variable height_per_floor (= height / count_floors_pre_eq).

Figure 4. Pairwise scatterplots of all numerical parameters. Correlations highlighted in green

There are 11 categorical and 23 binary parameters. I used the Chi-square test to compare distributions of these to the distribution of the dependent variable damage_grade, treated as categorical. The results are shown in Table 5 below.

All are statistically significant at 0.05 level, except for the 5 highlighted in red brackets. They will be excluded from the model. Two of the geo_level variables consume too many degrees of freedom given our sample size. (Even big datasets have limitations.) They are highlighted in orange and will be excluded from the model. If I have time, I will add a new custom geo_level variable with about 1000 degrees of freedom. The remaining 27 variables will be retained for use in the model.

Variable nameChi-squareDeg. of freedomP value
geo_level_1_id274660< 2.2e-16*
geo_level_2_id65922272< 2.2e-16*
geo_level_3_id1303910342< 2.2e-16*
land_surface_condition15.940.0032
foundation_type18578< 2.2e-16*
roof_type11224< 2.2e-16
ground_floor_type13478< 2.2e-16*
other_floor_type11176< 2.2e-16
position47.361.6e-08
plan_configuration46.5168.0e-05*
legal_ownership_status80.263.2e-15
has_superstructure_adobe_mud50.321.1e-11
has_superstructure_mud_mortar_stone10532< 2.2e-16
has_superstructure_stone_flag28.626.2e-07
has_superstructure_cement_mortar_stone53.822.1e-12
has_superstructure_mud_mortar_brick37.527.3e09
has_superstructure_cement_mortar_brick6322< 2.2e-16
has_superstructure_timber64.928.0e-15
has_superstructure_bamboo55.121.1e-12
has_superstructure_rc_non_engineered2962< 2.2e-16
has_superstructure_rc_engineered6032< 2.2e-16*
has_superstructure_other9.820.0072
has_secondary_use76.22< 2.2e-16
has_secondary_use_agriculture25.023.8e-06
has_secondary_use_hotel90.92< 2.2e-16
has_secondary_use_rental49.421.9e-11
has_secondary_use_institution10.820.0046*
has_secondary_use_school32.121.1e-07*
has_secondary_use_industry2.32[ 0.31 ]*
has_secondary_use_health_post1.52[ 0.46 ]*
has_secondary_use_gov_office4.22[ 0.12 ]*
has_secondary_use_use_police0.82[ 0.68 ]*
has_secondary_use_other15.320.00049*
has_missing_age3.12[ 0.21 ]*
Table 5. Chi-square results of categorical and Boolean values to damage_grade

*One or more enums have sample sizes too small to use Chi-square approximation
[ ] P value greater than 0.05 significance level

Step 5: Building the model

The dependent variable can take on the value 1, 2, or 3. I could use a classification method like multi-class logistic regression to create our model. However, there is a better way. I will use the ordinal regression algorithm available from Microsoft Azure Machine Learning (MAML).

Ordinal regression requires a binary classifier method. For this project, I will try three classifiers available in MAML, two-class logistic regression, two-class decision forest, and two-class support vector machine (SVM). I will use the default parameters for each classifier and submit all three models as entries in the contest. (This is sort of a cheat to improve the F1 score and my grade. In practice, you should only submit the results using the best model based on the training data.)

A simple model configuration using a static data split and without either a cross-validation step or a hyperparameter tuning step to optimize results is shown in Figure 5 below. I will add these steps later if the simple model does not meet the performance goals.

Figure 5. Layout of a simple MAML Studio experiment

I used a data split of 0.67, meaning 6,700 records were used to train the model and the remaining 3,300 were used to score and evaluate it. I used a random number seed of 123 to ensure every run of my experiment used the same split and produced replicable results.

Step 6: Measuring performance and testing results

A generic truth table for an experiment with 3 outcomes is shown in Table 6a below. Using data from the truth table, four performance metrics can be calculated, average accuracy, micro-average precision , micro-average recall, and geometric average F1 score. The calculation of the performance metrics is shown in Table 6b. Note that since all combinations are measured, recall, precision, and F1 score are all equal. Perhaps the contest should have used the macro-average recall and precision to calculate the F1 score.

Truth tableIs 1Is 2Is 3TOTAL
Predict 1TP1|TN2|TN3FP1|FN2|TN3FP1|TN2|FN3TP1+FP1
Predict 2FN1|FP2|TN3TN1|TP2|TN3TN1|FP2|FN3TP2+FP2
Predict 3FN1|TN2|FP3TN1|FN2|FP3TN1|TN2|TP3TP3+FP3
TOTALTP1+FN1TP2+FN2TP3+FN3Pop
Table 6a. Generic truth table for case with 3 outcomes
PerformanceCalculation
Avg Accuracy∑((TP + TN) / Pop) / 3
Avg Precision (micro)P = ∑TP / ∑(TP + FP)) = ∑TP / Pop
Avg Recall (micro)R = ∑TP / ∑(TP + FN)) = ∑TP / Pop
F1 Score(2 * P * R) / (P + R) = ∑TP / Pop
Table 6b. Performance measures for case with 3 outcomes

Grading for the course is based on the F1 score for a hidden subset of the test dataset as shown in Table 7 below. F1 scores between these points will receive linearly proportional grades. For instance,  an F1 score of 0.65 would earn a grade of 75.

F1 ScoreGrade
< 0.601 out of 100
0.6060/100
0.6470/100
0.6680/100
0.7095/100
Table 7. Grading of project based on F1 score (test data)

Below are the results of my models.

Model 1 – Naïve guessing

The most common value for damage_grade is 2. Any prediction model should perform better than the naïve guess of predicting the damage is 2 for all buildings.

Truth tableIs 1Is 2Is 3TOTAL
Predict 10000
Predict 2310186211283300
Predict 30000
TOTAL310186211283300
Table 8a. Truth table for naive guess of damage_grade = 2
PerformanceValue
Avg Accuracy0.71
F1 Score0.56
F1 Score (test data)Not submitted
Table 8b. Performance measures for naive guess of damage_grade = 2

Model 2 – Ordinal regression model using 2-class logistic regression classifier

The default parameters for the 2-class logistic regression classifier are: Optimization tolerance = 1E-07, L1 regularization weight = 1, L2 regularization weight = 1. Notice in Table 9b the large gap between the F1 score using the training data and the test data. This indicates the model is overfitted.

Truth tableIs 1Is 2Is 3TOTAL
Predict 184521137
Predict 222315675362326
Predict 33243591837
TOTAL310186211283300
Table 9a. Truth table for ordinal regression model using 2-class logistic regression classifier
PerformanceValue
Avg Accuracy0.79
F1 Score0.68
F1 Score (test data)0.5687
Table 9b. Performance measures for ordinal regression model using 2-class logistic regression classifier

Model 3 – Ordinal regression model using 2-class decision forest classifier

The default parameter settings are: Resampling method = Bagging, Trainer mode = Single parameter, Number of decision trees = 8, Maximum depth of trees = 32, Number of random splits per need = 128, minimum number of samples per node = 1.

Truth tableIs 1Is 2Is 3TOTAL
Predict 185551144
Predict 221813354321985
Predict 374726921171
TOTAL310186211283300
Table 10a. Truth table for ordinal regression model using decision forest classifier
PerformanceValue
Avg Accuracy0.76
F1 Score0.64
F1 Score (test data)Not submitted
Table 10b. Performance measures for ordinal regression model using decision forest classifier

Model 4 – Ordinal regression model using 2-class support vector machine (SVM) classifier

The default parameter settings are: Number of iterations = 1, Lambda = 0.001.

Truth tableIs 1Is 2Is 3TOTAL
Predict 13121355
Predict 227316679322872
Predict 36174193373
TOTAL310186211283300
Table 11a. Truth table for ordinal regression model using SVM classifier
PerformanceValue
Avg Accuracy0.72
F1 Score0.57
F1 Score (test data)0.5644
Table 11b. Performance measures for ordinal regression model using SVM classifier

Summary of models in step 6

Unfortunately, none of my initial models performed well. The F1 score never meets the target of 0.70. In fact, in some cases my model don’t do much better than just guessing. (Note: You can see my scores on the contest leaderboard.) In the next section, we will add a cross-validation step and a hyperparameter tuning step to optimize the models and and see if that improves them.

This completes steps 4 to 6 of building a machine learning model. The remaining optimization step and the results are posted at How to create a machine learning model – Part 3.

Damaged buildings resulting from Gorkha earthquake. Image from The Guardian

by George Taniwaki

At the beginning of each quarter edX and Microsoft offer a one-month long course called DAT 102x, Data Science Capstone. The class consists of a single machine learning project using real-world data. The class this past April used data collected by the Nepal government after the Gorkha earthquake in 2015. The earthquake killed nearly 9,000 people and left over 100,000 homeless.

The assignment was to predict damage level for individual buildings based on building characteristics such as age, height, location, construction materials, and use type. Below are the steps I used to solve this problem. The solution is general enough to apply to any machine learning problem. My description is a bit lengthy but shows the iterative nature of tuning a machine learning model.

About machine learning contests

The class project is operated as a contest. Students download training and test datasets, create a model using the training dataset, use the model to make predictions for the test dataset, submit their predictions, and see their scored results on a leaderboard.

As is common for machine learning contests, the training data consists of two files. The first file includes a large number of records (for the earthquake project, there were 10,000). Each record consists of an index and the independent variables (38 building parameters). A separate label file contains only two columns, the index and and their associated dependent variable(s) (in the earthquake project, there is only one, called damage_grade). The two files must be joined before creating a model.

The test file (10,000 more records of building indexes and parameters) has the same format as the training file. You use your model to create an output file consisting of the index and the predicted values of the dependent variable(s). You submit the file to a web service which then scores your results.

You can submit multiple predictions to be scored, adjusting your model after each submission in an attempt to improve your score. Your final score is based on the highest score achieved. To reduce the chance that competitors (students) overfit their model to the test data, the score is based on an undisclosed subset of records in the test file.

Approach to model building

The general approach to building a machine learning model is to first examine the dependent variables using univariate methods (step 1). Repeat for the independent variables (step 2). Normalize the variables (step 3). Examine correlations using multivariate methods (step 4).  Select the relevant variables, choose a model, and build it (step 5). Evaluate and test the model (step 6) and tune the parameters (step 7) to get the best fit without overfitting. Some iteration may be required.

Step 1: Univariate statistics for the dependent variable

There is one dependent variable, damage_grade, labeled with an integer from 1 to 3. Higher values mean worse damage. However, the intervals between each class are not constant, so the scale is ordinal not interval. Descriptive statistics are shown in Table 1 and Figure 1 below.

Variable nameMinMedianMaxMeanStd dev
damage_grade1232.250.61
Table 1. Descriptive statistics for dependent variable
Figure 1. Histogram of dependent variable

Step 2: Univariate statistics for the independent variables

As mentioned above, there are 38 building parameters. Details of the variables are given at Data Science Capstone. The 38 independent variables can be divided into 4 classes, binary, interval integer, float, and categorical as shown in Table 2 below. Notice that the parameter count_families is defined as a float even though it only takes on integer values.

Variable typeQuantityExamples
Binary (Boolean)22has_superstructure_XXXX, has_secondary_use, has_secondary_use_XXXX
Integer, interval4count_floors_pre_eq, height, age, area
Float1count_families
Categorical11geo_level_1_id, geo_level_2_id, geo_level_3_id, land_surface_condition, foundation type, roof_type, ground_floor_type, other_floor_type, position, plan_configuration, legal_ownership_status
Table 2. Summary of independent variables

The binary variables fall into three groups. First is has_superstructure_XXXX, where XXXX can be 11 possible materials used to produce the building superstructure such as adobe mud, timber, bamboo, etc. The second is has_secondary_use_XXXX, where XXXX can be 10 possible secondary uses for the building such as agriculture, hotel, school, etc. Finally, has_secondary_use indicates if any has_secondary_use_XXXX variables is true.

Whenever I have groups of binary variables, I like to create new interval integer variables based on them. In this case, they are named count_superstructure and count_secondary_use which are a count of the number of true values for each. count_superstructure can vary from 0 to 11 while count_secondary_use can vary from 0 to 10.

For the 7 numerical parameters, their minimum, median, maximum, mean, standard deviation, and histogram are shown in Table 3 and Figure 2 below. Possible outliers, which occur in all 7 numerical variables, are highlighted in red.

Variable nameMinMedianMaxMeanStd dev
count_floors_pre_eq1292.150.74
height15304.651.79
age01599525.3964.48
area63442538.4421.27
count_families0170.980.42
count_superstructure1181.450.78
count_secondary_use0020.110.32
Table 3. Descriptive statistics for the 7 numerical variables. Red indicates possible outliers
Figure 2. Histograms for the 7 numerical variables. Red indicates possible outliers

Upon inspection of the dataset, none of the numerical variables have missing values. However, it appears that for 40 records, age has an outlier values of 995. The next highest value is 200. Further, the lowest age value is zero, which does not work well with the log transform. To clean the data, I created a new binary variable named has_missing_age, with value = 1 if age = 995, else = 0 otherwise. I also created a new numerical variable named adjust_age, with value = 1 if age = 0, else = 15 (the median) if age = 995, else = age otherwise.

The variable area has a wide range, but does not appear to contain any outliers.

The variables count_families, count_superstructure, and count_secondary_use do not seem to have any outliers. They also do not need to be normalized.

For the 11 categorical variables, the number of categories (enums), and the names of the enums with the largest and smallest counts are shown in Table 4 below.

Variable nameCount enumsMax label / countMin label / countComments
geo_level_1_id310 / 90330 / 7hierarchical
geo_level_2_id11370 / 157tie / 1hierarchical
geo_level_3_id51727 / 24tie / 1hierarchical
land_surface_condition3d502 / 83112f15 / 347
foundation type5337f / 8489bb5f / 48
roof_type37g76 / 700767f9 / 579
ground_floor_type5b1b4 / 8118bb5f / 10
other_floor_type4f962 / 641267f9 / 415correlated with ground_floor_type
position43356 / 7792bcab / 477
plan_configuration9a779 / 9603cb88 / 1lumpy distribution
legal_ownership_status4c8e1 / 9627bb5f / 61lumpy distribution
Table 4. Descriptive statistics for the 11 categorical variables. Red indicates one or more enums has fewer than 10 recorded instances

None of the categorical or binary variables have missing values. None of the enums are empty, though some of the enums (highlighted in red in Table 4 above) have fewer than 10 recorded instance, so may bias the model. Unfortunately, we do not have any information about the meaning of the enum labels, so do not have a good way to group the sparse enums into larger categories. If this were a real-world problem I would take time to investigate this issue.

Step 3: Normalize the numerical variables

As can be seen in Figure 2 above, some of the independent numerical variables are skewed toward low values and have long tails. I normalized the distributions by creating new variables using the log transform function. The resulting variables have names prefixed with ln_. The descriptive statistics of the normalized variables are shown in Table 5 and Figure 3 below.

Variable nameMinMedianMaxMeanStd dev
ln_count_floors_pre_eq00.692.190.700.36
ln_height01.613.401.460.40
ln_adjust_age02.715.302.611.12
ln_area1.793.536.053.540.46
Table 5. Descriptive statistics for adjusted and normalized numerical parameters
Figure 3. Histograms of adjusted and normalized numerical parameters

This completes the first 3 steps of building a machine learning model. Steps 4 to 6 to solve this contest problem are posted at How to create a machine learning model – Part 2. The final optimization step 7 is posted at Part 3.

Image from Microsoft and edX

by George Taniwaki

Big data and machine learning are all the rage now. Articles in the popular press inform us that anyone who can master the skills needed to turn giant piles of previously unexplored data into golden nuggets of business insight can write their own ticket to a fun and remunerative career (efinancialcareers May 2017).

Conversely, the press also tells us that if we don’t learn these skills a computer will take our job (USA Today Mar 2014). I will have a lot more to say about changes in employment and income during the industrial revolution in future blog posts.

But how do you learn to become a data scientist. And which software stack should one specialize in? There are many tools to choose from. Since I live in the Seattle area and do a lot of work for Microsoft, I decided to do take an online class developed and sponsored by Microsoft and edX. Completion of the course leads to a Microsoft Data Science Certificate.

The program consists of 10 courses with some choices, like conducting analysis using either Excel or Power BI, and programming using either R or Python. Other parts of the Microsoft stack you will learn include SQL Server for queries and Microsoft Azure Machine Learning (MAML) for analysis and visualization of results. The courses are priced about $99 each. You can audit them for free if you don’t care about the certificates.

I started the program in February and am about half way done. In case any clients or potential employers are interested in my credentials, my progress is shown below.

DAT101x – Data Science Orientation

If you haven’t been in college in a while or have never taken an online class, this is a good introduction to online learning. The homework consists of some simple statistics and visualization problems.

Time: 3 hours for 3 modules

Score: 100% on 3 assignments

DAT201x – Querying with Transact-SQL

I took a t-SQL class online at Bellevue College two years ago. Taking a class with a real teacher, even one you never meet, was a significantly better experience than a self-paced mooc. This course starts with the basics like select, subqueries, and variables. It also covers intermediate topics like programming, expressions, stored procedures, and error handling. I did my homework using both a local instance of SQL Server and on an Azure SQL database.

Time: 20 hours for 11 modules

Score: I missed one question in the homework and two in the final exam for a combined score of 94%

DAT207x – Analyzing and Visualizing Data with Power BI

I already have experience creating reports using Power BI. I also use Power Query (now called get and transform data) and M language and Power Pivot and DAX language, so this was an easy class.

The course covers data transforms, modeling, visualization, Power BI web service, organization packs, security and groups. It also touches on the developer API and building mobile apps.

Time: 12 hours for 9 modules

Score: I missed one lab question for a combined score of 98%

DAT222x – Essential Statistics for Data Analysis using Excel

This class is comprehensive and covers all the standard statistics and probability topics including descriptive statistics, Bayes rule, random variables, central limit theorem, sampling and confidence interval, and hypothesis testing. Most analysis is conducted using the Data analysis pack add-in for Excel.

Time: I used to work in market research, so I know my statistics. However, there are 36 homework assignments and it took me over 20 hours to complete the 5 modules.

Score: I missed 9 questions on the quizzes (88%) and six in the final exam (81%) for a combined score of 86%. (Despite the time it takes to complete, homework counts very little toward the final grade)

DAT204x – Introduction to R for Data Science

Now we are getting into the meat of the program. R is a functional language. In many ways it is similar to the M language used in Power Query. I was able to quickly learn the syntax and grasp the core concepts.

The course covers vectors, matrices, factors, lists, data frames, and simple graphics.

The lab assignments use DataCamp which has a script window where you write code and a console window that displays results. That makes it easy to debug programs as you write them.

The final exam used an unexpected format. It was timed and consisted of about 50 questions, mostly fill-in-the-blank responses that include code snippets. You are given 4 minutes per question. If you don’t answer within the time limit, it goes to the next question. I completed the test in about 70 minutes, but I ran out of time on several questions, and was exhausted at the end. I’m not convinced that a timed test is the best way to measure subject mastery by a beginning programmer. But maybe that is just rationalization on my part.

Time: 15 hours for 7 modules

Score: I got all the exercises (ungraded) and labs right and missed two questions in the quizzes. I only got 74% on the final, for a combined score of 88%

DAT203.1x Data Science Essentials

The first three modules in this course covered statistics and was mostly a repeat of the material introduced in DAT222x. But the rest of the course provides an excellent introduction to machine learning. You learn how to create a MAML instance, import a SQL query, manipulate it using R or Python, create a model, score it, publish it as a web service, and use the web service to append predictions as a column in Excel. I really like MAML. I will post a review of my experience in a future blog post.

The course was a little too cookbook-like for my taste. It consisted mostly of following directions to drag-drop boxes onto the canvas UI and copy-paste code snippets into the panels. However, if you want a quick introduction to machine learning without having to dig into the details of SQL, R, or Python, this is a great course.

Time: 10 hours for 6 modules

Score: 100% on the 6 labs and the final

Next steps

I have now completed six out of the ten courses required for a certificate. I expect to finish the remaining 4 needed for a certificate by the end of the year. I will also probably take some of the other elective courses simply to learn more about Microsoft’s other machine learning and cloud services.

For my results in the remaining classes, see Microsoft Data Science Certificate-Part 2

* * * *

[Update: Modified the description of the final exam for DAT204x.]