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.

Google rewards reputable reporting, not left-wing politics, from The Economist

by George Taniwaki

A few months ago The Economist added a new feature to its back section called Graphic detail. It’s a pleasure to read because it nearly always contains bivariate plots where the x-axis is something more interesting than the date.

This week’s entry does not disappoint. It is entitled, Seek and you shall find and contains two charts (see above) with interesting x-axes. The charts analyze the impact of Google news search on the traffic a news source receives. It uses two independent measures, Accuracy score and Ideology score to rate different news sources. Accuracy and bias were determined using data from Adfontesmedia.com and Mediabiasfactcheck.com.

Many people claim that Google favors liberal news sources to the detriment of conservative views. Google claims it has a set of outside reviewers who check news sources for accuracy and reach. Point of view is not considered. However, one could imagine that a news source that has a strong point of view may report facts to match a point of view and that would reduce accuracy. As can be seen on the chart on the left, news sources with a strong ideological bias (darker red and blue dots) tend to have lower accuracy scores than less biased sources. I encourage you to go to the website because the data is interactive.

The dependent y-axis is the share of web traffic that comes from search engines. This is a bit problematic since if users believe that Google’s results are biased against their favorite news sources, they will visit it directly without using a search engine. Nonetheless, the data shows that search engine (mostly Google) share of web traffic increases with accuracy, not with ideology. That is, the plot on the left shows a linear relationship while the right plot does not.

Expected v. Actual

A separate experiment confirms the results. The Economist built a model to predict the number of news results appearing in 37 publications should receive from Google’s search engine based on their accuracy and their reach. It then compared the model results to actual search results on a “clean” computer using “a browser with no history, in a politically centrist part of Kansas.” (Why Kansas, you wonder? I’m guessing that is where the author lives.)

No bias detected, from The Economist

Again, no bias was detected. The difference between left and right are small and could be due to how they are defined, time of study, keywords searched, or other factors. The story is an excellent example of combining data from multiple sources, programming a bot to collect data, and visual display of statistical analysis.

Figure 1. Eight data points spread across two charts. From J. Exper. Psy.: General, Apr 2019

by George Taniwaki

In a paper authored by Erin Cooley, et al., (J. Exper. Psy.: General, Apr 2019), (subscription required), there is a pair of line charts, reproduced above. I found them hard to interpret. There are 3 issues.

  1. Even though there are only 8 data points, the data is split between two charts making it difficult to compare Sympathy scores between the treatment groups (those who received the white privilege lesson vs those who did not)
  2. The x-axis in the charts displays conservative vs liberals. Study subjects did not change categories during the study. They should not be connected with a line. Bar charts would be better than line charts to display their Sympathy scores
  3. The x-axis should be the treatment used in the study. If the treatment groups are randomly selected, then the Sympathy scores can also be interpreted as before and after treatment and a line can connect them

Explanation of data

As I explain in a May 2019 blog post, the data is a result of two studies with eight sample cells, each represented by one of the points in the charts above. There are three pairs of groupings shown in Table 1.

  1. Social group – based on a questionnaire, study subjects were classified as either social conservatives or social liberals
  2. Treatment – some study subjects received a lesson on white privilege and others did not
  3. Race story – some study subjects read a story of a poor black man and some read a story of a poor white man
Social groupTreatment: Received white privilege lessonRace of poor person in storyAverage sympathy score
ConservativeNoBlack60
ConservativeYesBlack61
ConservativeNoWhite53
ConservativeYesWhite59
LiberalNoBlack72
LiberalYesBlack76
LiberalNoWhite71
LiberalYesWhite60
Table 1. Average Sympathy scores by Social group, Treatment, and Race in story

The improved chart

Using the data from Table 1, I created my own version of the chart, shown in Figure 2.

Figure 2. Improved line graph showing effect of white privilege lesson on sympathy scores

Let’s compare the updated chart in Figure 2 to the original chart in Figure 1.

  1. All eight data points now fit on a single chart, making comparisons easier.
  2. The main point of this research was to determine the effect of providing a lesson on white privilege on sympathy scores. The new chart sets the horizontal axis to show the treatment categories, those who received the lesson on white privilege and those who did not
  3. A line connects the cases to show the slope, positive to indicate the lesson increases sympathy to a race or negative to indicate the lesson decreases sympathy to a race
  4. Finally, my chart has a smaller scale (50 to 80 instead of 50 to 100), fewer rule lines, and no box around the legend. All reduce clutter so you can concentrate on the data

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.