Sunday, 9 July 2017

(Dis)Similarity Measures

This post is basically my white-paper on the topic already available in pdf at my home site. Since I am an old Latex hand, most of my writings, especially those with mathematical notations, starts there and end up in pdf. Here essentially I am trying to figure out an economic way to convert Latex  content into web-friendly content 😏, already tried a few automated conversion/export methods - did not work properly. So, trying to develop an economic copy-paste method. However, hope those who of you have not seen the pdf version, will enjoy this.


Motivation

The ability to recognize objects and their relationships is at the core of intelligent behavior. This, in turn, depend on one's ability of perceiving similarity or dissimilarity between objects, be physical or abstract ones. Hence, if we are interested to make computers behave with any degree of intelligence, we have to write programs that can work with relevant representation of objects and means to compute their similarities or lack thereof, i.e., dissimilarity (obviously, they are two faces of the same coin).

The motivation for writing this white paper (hopefully, the first of a series, depends on its reception and utilization ) is to introduce our young data scientists to some subtleties of the art (and of course,
science) they have taken up to practice. First, please look at two emphasized phrases of the paragraph above. They are most crucial and fundamental issues. Hope you do not represent a 'chair', to your computer program for identifying objects to seat on, as just something that has four legs - then the computer is very likely to advise you to sit on your house-puppy. Similarly, you don't want to compare prices of two objects by comparing their binary string representations.

In short, 
  • we need to work with a representation of objects of interest containing adequate information relevant for the problem at hand. For example, information needed about a chair for distinguishing it from a table is quite different if we want to distinguish between an easy
    chair and a work chair; 
  • once we have a proper representation of the objects, we need to incorporate into a relevant mathematical framework which will enable us to compute a measure of similarity or dissimilarity between objects. 

There are quite a number of available measures for each type of commonly used representations. We can find a good listing here. Unfortunately, the measures within each group has many, some obvious and some subtle, differences. Thus, we need to choose and evaluate them in context of our problems. A nice survey of many of these measures is available on internet. Advanced readers can and urged to) directly go there and read it and its alikes.

In this white paper we shall discuss the objects represented by a set of their attributes and computing distances between pairs of them as points in feature space. The computed distance is interpreted as a measure of dissimilarity, and thus, inverse of similarity - in the sense, the less is distance the more is similarity and vice-versa. We shall also find a measure, the cosine similarity that can be directly interpreted as similarity. Don’t worry my friends, I shall take you there very gently.

Working with Object data

As far as organization of the data is concerned, there are three major categories:
  • Object data: Objects are represented by an ordered set of their attributes/ characteristics/ features. We shall use the term “feature” henceforth - these are the data which we store and perceive as one record/instance per row in a file/table; 
  • Relational/relationship data: The data captures various relationships among
    the objects - we often call them “graph data”; and
  • Sequence data: includes time-series data, natural language text data, ...
Remember, there can be many situations while solving real-life problem, when more than one types of data may be used as well as may be converted to one another. Nevertheless, here we concentrate on object data only.

Attributes

Features in object data can be numerical, Boolean as well as categorical. Again, let us consider some features of a chair:
  • Height of the chair: numerical;
  • Area of the seat: numerical;
  • Has armrest: Boolean - either has or not (1/0)
  • Reclinable: Boolean - yes/no
  • Color of the chair: categorical
  • Number of legs: ? - can be 4, 3, 1 (not 2, I guess), is it meaningful to consider it numeric, so that we can do all kind of mathematical and/or statistical jugglery or should we consider it categorical - 4-legged etc.?
Example, my chair is 22 inch in height, with seat area 400 sq. inch. and armrests, is fixed-back, red with 4 legs. Hence, $MyChair = (22; 400; 1; 0; 4L)$, a 5-tuple is the representation of my chair. In statistical literature such data are often called multivariate data. 

Numerical features allow us to apply a vast array of mathematical and statistical tools in order to work with them. Thus, in most cases we try to frame the problems in terms of numerical features (even when the raw data is something different such as text). In majority of cases, Boolean features also can be treated as numerical with values 0 and 1.

Categorical features are slightly difficult to deal with within same framework, since we cannot work out a concept of similarity among their values, e.g., it is somewhat absurd to say that the color green is more similar to black than blue or vice-versa. Nevertheless, we shall see later that the categorical features also can be transformed. Thus, without restricting the applicability, hereafter we shall consider all the features of an object. Now, let us set up some basic nomenclatures here.
  • Let $X$ denote a data set with $n$ instances of object data; 
  • Let $\mathbf{x}_{i}=\left(x_{i1},x_{i2},\cdots,x_{ip}\right)\in X$ be the $i^{th}$object with $p$ attributes/features with values $x_{i1},x_{i2},\cdots,x_{ip}$respectively; and 
  • To keep the things simple, let us posit that $\forall\mathbf{x}_{i}\in X$, the types of features available are same. In other words, each of the object instance is represented by a $p-tuple$ consisted of the values of the same set of attributes in the same order. 
    The Iris data, partial listing, sorted by sepal width (Courtesy: Wikipedia)
To understand this properly, let us consider one of the most well known (and classic!) data sets, the Iris data set. The data set is comprised of 50 sample observations from three species of Iris flowers. The measured features are length and widths of the sepals and petals of the flowers. Part of the data is shown above. Each row in the data represents measurements of one flower with the species of the flower noted in fifth column. Thus, this data has four numerical features, i.e., $p=4$ and $3\times50=150$ instances (rows), i.e., $n=150$. The inclusion of 'species' in the fifth column, makes it a labeled data, where each instance is labeled with a category or class. For the time being we shall ignore these labels in our discussion.
It is very important to remember that an object can potentially have many (often extremely large number of) attributes/features. For example, consider the Iris flowers. Other than the four collected in the Iris data set, there are many other possible attributes, including simple ones like color to very complex ones like genome sequence (think of others in between ). It is clear that we cannot use all possible attributes.
So, which ones do we use? This is one of the big questions almost always faced by data scientists in real world problems (in research labs one has the luxury of using well-known data sets). The problem is essentially that of determining relevance and accessibility/availability of the features with respect to the problem-in-hand.
Addressing this issue constitutes big and vital parts of data science known as feature selection and feature extraction, known collectively as feature engineering. While feature engineering is very much problem-specific (and thus out of current scope), let us  look into some of the guiding principles here.
Relevance: Usually we would like to use discerning features or discriminating features. They are the features which can be useful for computationally identifying similar and dissimilar objects in the sense relevant for the problem. For example, consider the species identification problem of Iris flowers. The attribute ‘color’ is not very discriminating (all Irises are violet), but genome data can be very useful. On the other hand, if the problem is to identifying between Irises and Roses, color can be one of the very useful features.
Let us try to understand the above in simpler terms. Again, consider the problem of Iris species identification. If the objects, i.e., Iris flowers are represented with a set of discriminating feature, we can expect that, in general, the similarity computed using the features is greater between two flowers from same species than otherwise. Let us add another feature to the representation. This will effect the similarities. Now, if the similarity between flowers from same species is increased and/or similarity between flowers from different species is decreased after introduction of the new feature, then the new feature is discriminating one.
Existence of non-discriminating/irrelevant/redundant features in data evidently do not contribute to the solutions, but can often worsen the situation. Their existence can be thought as noise in the data which essentially decreases signal-to-noise ratio in the information content of the data. This makes the task of extracting knowledge/information (signal) from the data more difficult. 
Pragmatics: Even after we have some idea on which features are useful, we have to consider the cost as well as feasibility of collecting and/or  processing them. Let us again consider the problem of Iris species identification. While the genome data can be extremely good in discriminating species, it is costly to collect as well as to process computationally. So, if we have the freedom to dictate the data collection strategy, we shall have to consider the cost-benefit tradeoff for selecting the features to be collected/measured. 
In a lot of real-world works we don’t have the above freedom. Instead we have to work with already available data, which is mostly collected for some other purpose (transactional, operational, etc.), with no plan of subjecting them to application of data science techniques. Such scenarios are known as data repurposing.
Here our challenge is to identify the relevant features from the data for use in solving the data science problem. In worst case, we might face a situation where there is not enough useful feature in the data for solving the problem to a satisfactory level .

Objects in feature space

The Euclidean space

Till now we have been discussing about a single object and its representation. Now, let us think about working with a number of objects (at the least, similarity refers to a pair of objects!). In this the concepts drawn from the study of vector spaces becomes most invaluable tool. To understand
how to use them let us start with a recalling of our school days when we have learnt as Euclidean geometry or plane geometry.

There we studied properties of various geometric objects, like straight line, parallel lines, triangles, circles, etc., based on a number of axioms or postulates. But, think carefully, at that time we did
not have any business with coordinates of the points. That came latter under the heading co-ordinate geometry (bit of nasty stuff for most of us ). Well, the person responsible for complicating our innocent(?) school days was René Descartes, inventor of, among a lot of other stuff, the Cartesian coordinate system shown below
A Cartesian coordinate plane (Wikipedia)
Cartesian coordinate system is a rectilinear coordinate system, whose axes are mutually perpendicular (in formal mathematical terms, orthogonal)and linear (i.e., straight lines). For Cartesian coordinate system in 3-dimension see below.
3-D Cartesian space (Wikipedia)
Introduction of Cartesian coordinate system endows each point in the Euclidean plane (2-D) with a unique address, called its coordinate, a pair of numeric values. This created a bridge between geometry and algebra, the marriage producing the offspring called the Algebraic Geometry. One of minor consequences of this is we can plot and thus visualize algebraic equations, e.g., $x^{2}+y^{2}=1$, a circle centered at origin with radius 1!.

A Euclidean plane equipped with a Cartesian coordinate system becomes a Euclidean space.
Notice that I have used 'a', not 'the' in the previous sentence. }Further, here the term ``space'' is not a common sense or colloquial term (like in 'a specious home'), rather it refers to an algebraic
geometric entity . Yes, we are venturing in a slightly dangerous territory, but have courage, we need not go too deep into it. For our purpose it will suffice to understand that a ``space'' is a
set of distinctly identifiable (by their coordinates) points with certain properties holding among them. These properties are the ones which essentially distinguish one type of space from another. The
points to remember: 

  • There are many types of spaces other than  Euclidean Spaces (yes, there are also quite a few different Euclidean spaces, even with non-Cartesian coordinates) called (obviously!) non-Euclidean spaces; and
  • There are  many coordinate systems other than Cartesians, (again!)the non-Cartesians. 
Thankfully, here we shall work only with real-valued (i.e., the coordinate
values are all real numbers) Euclidean space and its \emph{generalizations}
equipped with Cartesian coordinate systems. Let us have an intuitive
understanding how such a space relates to our object data. Let us,
for the time being, consider that the Iris data has only two features,
namely, \emph{petal length} and \emph{petal width. }If we conceive
the petal length as $x$ value and petal width as $y$ value, then
we can associate an iris flower with a point $p=(x,y)$ in the two
dimensional space.

Saturday, 24 June 2017

Building a Deep-Learning (and of course, general Data Science ) Workstation

A personal DIY project

A personal DIY project

Disclaimer:

Is it a worthwhile exercise?

How does GPUs help in deep learning

So, it is easy to see how GPGPU capability can support deep learning. Fortunate for us, most of the time we need not develop our code using CUDA toolkit directly. There are libraries availables in almost all of the popular languages which help us develop our deep learning code in our favorite language and takes up the burden of converting it to GPU executable.

Design issues

An interesting build case-study is available at Analytics Vidya blog. Here I intend to go little deep and somewhat pedantic . Here our discussion will attempt to help resolving the following issues:

3.1 CPU

Now, in the i7 family the stuff is little convoluted. At this moment, the consumer processors are into 7th generation – launched i7-7700 and i7-7700K only till now. These have (among other specs) 4 Cores, 8 MB Cache, 16 PCIe lanes and supports up to 64 GB memory over dual-channel. For our purpose, they are not very suitable.

3.2 GPU

Multiple GPUs in parallel:

What will happen if I throw in more than one GPUs? NVIDIA offers a multi-GPU scaling/parallelizing technology called Scalable Link Interface (SLI), which can support 2/3/4-way parallelism. It seems to work well for some games, especially those designed to take advantage of it. At this time, we do not know clearly about SLI scaling of deep-learning tasks. Tim Dettmers provides some useful pointers – from which it seems that only a few of all deep-learning libraries can take advantage of this. Nevertheless, he also argues that using multiple GPUs even independently, will allow to run multiple DL tasks simultaneously.

3.3 Motherboard (or Mobo for brevity)

3.4 Others

Budget Issues

My build

5.1 My budget

I am based in India and that has some cost implications. Almost none of the components are manufactured in-country, thus has to be imported and therefore import duty is levied, thus I shall get somewhat less bang for my bucks compared to someone in, say, USA. My strategy is to get a somewhat minimal (but sufficient for moderate-size problems) system up and running and then expanding its capability as required. So let us get down to the initial system budget and configuration.

5.2 CPU

Now, PCIe3.0:x8 has half bandwidth of x16, but it is still nearly 8 GB/s. The question is to ask is whether the x8 connection is enough for deep-learning workloads. Unfortunately, I could not find an exact answer. However, in context of gaming, some test results are available, which found inconsequential (within margin of error) difference in performance between x16 and x8 for PCIe 3.0. Now, whether graphics processing or deep-learning, computationally, more or less, both are multiplication of large matrices. So, we can expect the similar behavior of the system for DL tasks.

Budget impact:

5.3 Motherboard

Budget impact:

5.4 GPU

Budget impact:

5.5 Memory modules

Budget impact:

5.6 Secondary storage

  1. Samsung 960 EVO Series - 500GB PCIe NVMe - M.2 Internal SSD
  2. Seagate 2TB Firecuda (Solid State Hybrid) SATA 6GB/s 64MB Cache 3.5" – significantly better (claimed to be 5x faster) than traditional HDD.

Budget impact:

5.7 PSU

It is imperative that the PSU must comfortably meet the system's overall power demand. I have used an online tool for computing the system power requirement. I have calculated the power requirement for the system with 2 GPUs, 8 RAMs and 2 SATA drives. The details of the calculation is shown 7 in the Appendix. Based on that calculation, I selected CORSAIR CX Series CX850M 850W ATX12V / EPS12V 80 PLUS BRONZE Certified Modular Power Supply. Hopefully, this will be good enough till I try to add the third GPU.

Budget impact:

5.8 Cabinet

Budget impact:

5.9 CPU cooler

Budget impact:

Building

Before signing off

Appendix:

The build at a glance:

The power supply requirement calculation

Tuesday, 4 October 2016

Problem levels analysis for data science solutioning

A Data science-based solution needs to address problems at multiple levels. While it addresses a business problem, computationally it is comprised of a pipeline of algorithm which, in turn, operates on relevant data presented in proper format. Thus to understand the them we need to focus at least at the
  • Business level;
  • Algorithm level; and
  • Data level.
Contrary to the popular belief, almost all non-trivial data science solutions are needed to be built ground up with minute and interrelated attention to the details of the problem at all three levels. In the following we shall try to understand that with the help of an running example of aspects of a churn analysis solution.

It is vital to understand that in most real-world cases we are re-purposing the data for building the solution. In other words the data used is not collected for the purpose of kind of analysis we want to perform. They are collected as part of transactional and operational activities of the organization. Thus the strategies for collection, formatting and storage of the data is optimized for those purpose. Therefore, locating the relevant data and processing them to enable application of data science technique can be quite non-trivial, often herculean exercise.

From a user perspective a solution life-cycle can be understood as following:
  • Solution development: Using historical data, involves extensive experimentation, testing and validation;
  • Solution deployment: Using the solution to get the insight and/or decision support;
  • Solution assimilation: In the workflow enabling actions based on insight and/or prediction made by the solution;
  • Solution maintenance and update: Periodic checking and validation of the solution performance and update to improve performance if required.
It is the job of the data scientist(s) deliver on the above and for that she have to understand the problem at different levels. 

The Business/Domain level

At this level the broad business context, desired outcome of the solution are defined along with various parameters and constraints the solution should/must adhere to. Also, at this level desired/ acceptable performance parameters can be set in commensurate with business policies, especially the risk management. Let us try to understand this with respect to the popular churn analysis problem
Business level context for churn analysis
The churn analysis problem has a quite straight-forward context. Every business strives to retain
its good/valuable customers. Thus, if it is possible to identify the customers likely to stop doing business with the organization, it may be able to take proactive steps in order to retain the customer. However, we cannot only demand that a system should spout lists of customers whenever asked. We need to specify at the followings:
  • What should be the prediction lead time? Naturally, we don’t want to know a customer is going to churn within next five minutes. We cannot possibly do anything about it with the knowledge. We need enough lead time so that preventive actions can be taken.
  • What is the acceptable probability/likelihood measure of a prediction being correct? Predictions are always uncertain to some degree (otherwise they would be called facts). Usually, most of the customers run through the system will have non-zero likelihood of churning. This issue is often revisited in later stage and calibrated against the system output characteristics.
  • What is the acceptable level of accuracy of the predictions? No solution is going to be 100% accurate (As we humans are neither, after all ”to err is human...”) and taking action based on the predictions involve cost. Thus a cost/benefit analysis is required in order to determine an acceptable level of solution performance.
Note:
The meaning of probability or likelihood measure is not straightforward or very intuitive.
One individual customer will either churn or not. Thus post-facto or actual probability is either 1 or 0! So what does this likelihood value, which is somewhere in between, mean? It will always be ultimately proved wrong, isn’t it?
Well, actually I am misleading you slightly - probability is not about individuals, but large collections. So, the interpretation goes like this,
If there are large, very large number of customers with very same characteristics or attribute values used by the solution, the likelihood fraction of them will churn. Satisfactory?
Wait, there are many attributes used to in the solutions and they have varied range of values. How likely is it that many customers will have just the same values of the attributes? Actually, not very likely at all. What happened is this, the solution maintains knowledge, explicit or implicit, of an overall probability distribution over the attribute space.
This knowledge and knowledge of how to use it to make prediction constitute the underlying prediction model, which is usually learned from the training data using the machine-learning algorithm. This is used to compute the individual likelihoods. So, in simplistic terms we can interpret this as
If we had a lot of customers like this, likelihood fraction of them will churn. If the likelihood value is high, so is the chance of this guy being one of those churners. So let us see if that is so and we can prevent him to do so.
While it may not be immediately apparent, understanding the above subtlety is often useful in overall understanding of system performance.

The Algorithmic Level
Algorithmic level delivers the asks of the business level. In data science approach, the algorithm level creates, maintains and applies a model of the process in reality involving the objects of interest, hereafter referred as simply ”objects”. This process leads to the events or outcomes of interests. The following are the main characteristic of the data science algorithms.
  • An algorithm works with available data footprint of the process of interest;
  • It discovers the relationships between the process characteristics and the outcomes;
  • The above relationships are, more often than not, in form of complex patterns;
  • Discovering these patterns require application of powerful learning algorithms on the historical data;
  • Discovered patterns lead to learning the required model parameters;
  • An analysis/model application algorithm use these parameters to create the model and apply it on the new data in order to compute the output.
The algorithm level of a data science application is comprised of one or (often) more of algorithms from the basic types of algorithms:
  • Regression: Predicts the value of a continuous valued variable from the values of a set of numerical attributes;
  • Classification: Predict one discrete class/category out of a set of classes using numerical and/or categorical attributes;
  • Clustering: Discovers natural grouping of the objects;
  • Association discovery: Discovers propensity of similar behavior among two or more objects. described using numerical and/or categorical attributes;
Again, there are many actual algorithms for each types, differing in their approaches, complexity, interpretability, acceptable data types and above all their efficacy in a particular problem scenario.
Churn analysis example:
Again, with respect to the churn analysis problem, we can easily discern that the objects here are the customers and the process of interest is their reaching a decision about whether to churn or not.
The data about a customer available to the organization contains the data footprint of his/her decision process, albeit hidden among a lot of dust and garbage. How to isolate/extract and possibly enhance the footprint is a matter we shall touch upon in next section. It can also be seen that here the task demands the system predict one of two discrete outcomes, churn or not-churn.
Hence, the heart of the system is likely to be a classification model and algorithms for learning and applying the model.
Note:
We should not straight-jacket an one-to-one correspondence between the business level and the algorithmic level of a problem. For example, at the algorithm level we can pose the churn analysis problem as a regression problem, trying to predict for each customer, after what time amount of time she is going to churn.
Actually, what you do at algorithm level may depend on a lot of factors. We should keep an open mind while exploring for best possible solution for a given problem.

The Data Level
Data Science algorithms work with object data in form of feature/attribute vectors describing the
objects of analysis/interest.  In a real life problem scenario, we seldom have the data readily available in the such form. Usually a lot of effort, often majority of the total, goes into transforming the available raw data into the usable form comprised of vectors of useful features.
This is the stage we identify, isolate and enhance the data footprint of the process of interest and encode it in form of feature vectors. Clearly, this is a momentous process that needs to take into account the format and content of actual data sources available, their quality as well as deep understanding of the problem domain. This exercise is most often solution-specific as well as organization-specific (because data collection and stewardship policies vary across organizations). The whole process is known as feature engineering. 
Problem-specific feature engineering
Coming up with features is difficult, time-consuming, requires expert knowledge.
"Applied machine learning" is basically feature engineering. —Andrew Ng, Machine
Learning and AI via Brain simulations

Let us again go back to the churn analysis/prediction problem. In order to enable algorithm level to perform adequately, it has to work with quality data, i.e., data with information-rich features.
Technically such features are called discriminative features, the features which can significantly contribute towards the algorithm discriminating/distinguishing between churners and non-churners.
There is often a lot of data available internally (customer demography, product data, transaction history, competitor intelligence, call center records, etc.) as well as accessible from outside (credit rating data, etc.). Not all of these data are useful nor all of them are readily usable (for example, the transaction history is event data over time) as features. Clearly, a naive approach of somehow putting together all the data and wish the algorithms work out can
meet with disastrous result.
Thus the feature selection and preparation can turn out to be a very complex issue to tackle. Most of the time we have to use understanding of the problem domain in conjunction with application of feature selection and transformation methods. For example, in our problem we might consider the following:
  • Why a customer would decide to leave?
    • Dissatisfied with the product/service
    • Product/service is not what is actually needed/expected
    • Has trouble enjoying facilities provided
    • Trouble accessing the delivery channels
    • ...
  • Got a better deal from a competitor
    • A similar product for less price
    • A better product for similar price
    • ...
The above issues, individually or together, may influence various aspects of customer behavior vis-a-vis the bank, which, in turn reflects in complex patterns hidden in the data. It is the aim of feature engineering to
  • identify the part of data in which such patterns likely to be hidden and
  • designing suitable processing or transformation of the data in order to enhance the information content.
Did you notice that earlier I have used the term “data footprint”? That fits nicely with my favorite analogy of this work - finding the footprints of a rare animal in a jungle.

Blind feature selection

This is what I feel is the (charitably speaking) lazy  approach or (less of charity, more to truth) incompetent approach. Get the whole data dump and run some in-box feature selection/ranking algorithm without trying to understand the data semantics. Unfortunately, I am observing too much of this. While this approach may help quickly build a solution, it will essentially become a black-box kind of solution. It definitely harms the interpretability/understandability/transparency of the solution as well as makes the solution maintenance and update a nightmare. 

Incidentally, practitioners of this approach usually finds Deep Learning extremely attractive, almost forming a "celebrity fan-base". Topmost reason for that, as far as I can discern from multiple sources, is that DL networks (supposedly) eliminate the need of feature engineering, both selection as well as transformation, in one fell swoop! 

Unfortunately, the reality is a slightly more complicated. But that will be subject of another post.