Showing posts with label machine learning. Show all posts
Showing posts with label machine learning. Show all posts

Friday, April 28, 2017

Google Prediction API

Google Cloud Prediction API provides a RESTful API to build Machine Learning models.
steps:
  1. create a cloud platform project: predictionapi0
  2. enable billing
  3. enable API
  4. download training data (txt file)
  5. create bucket: jychstar-bucket, upload txt file to bucket
  6. project: predicitonapi0
    request body: {
    “id”: “language-identifier”,
    “storageDataLocation”: “jychstar_bucket/language_id.txt”
    }
It turns out this language-identifier API is only a toy, with 403 input instances and 3-class labels(English, French, Spanish). It is a blackbox that are written for a specific purpose.
The business model for prediction API is $0.50/ 1000 prediction after 10 k free prediction. And they charged the training as well. I think such API is application specific. As a black box, it should generalize well enough to be useful in the changing world.
Some mature APIs are:
  • Natural language analysis: syntax, entity, sentiment
  • speech to text
  • translation
  • image analysis
  • video analysis

Wednesday, March 1, 2017

Machine Learning ND 5, dropout and review

I am too busy for preparing the on-going interview and have no time to finish the capstone. So now I do a quick review and then drop out of the nanodegree. Dropout, as a powerful technique in deep neural network, is also useful for me to make real-life decision. If you are learning too hard, you may be overfit. It is time to step back and reflect.
As my previous post said, the deep learning section in this nano degree is poorly designed. I got stuck here in the last 2 months and made very slow progress. Deep learning really takes time and effort.
Step 4 of digit_recognition is a real challenge. It makes me realize the real-world scenario is much more complicated. I couldn’t figure out how to do a localizer that can deal with different size of inputs.
And it is my first time to use the 1:1 appointment via Zoom. However, the tutor seems not well prepared. I spend 20 mins getting him understand the difficulty of the project. At last, we look to the Forum for solution: https://discussions.udacity.com/t/tips-for-svhn-project-with-bounding-boxes/219969. But after that, I became super busy with a data scientist opportunity and have no time to go back.

capstone

The capstone project is kind of DIY thing. You learn by exploring yourself.
Below are a few suggested problem areas you could explore if you are unsure what your passion is:

Review: is this machine learning ND worth it?

The short answer is: Yes!
Of course, Udacity can do a better job. The point is l learned a lot at my own pace and get prompt feedback. I am pretty confident to talk about machine learning with other colleagues. And I know how to improve myself: keep practicing on the real-world dataset and keep sharing what I learn.
By the way, I didn’t realize that nanodegree is a trademark of Udacity, who applied it in 2004

Friday, February 10, 2017

Machine Learning ND 2, unsupervised learning

I am not satisfied with the unsupervised learning courses at Udacity. It is just not well organized! Seems like a random collection of “Intro” course and “Gatech” course. I lose my focus several times during the study.
To me, unsupervised learning is actually more important than supervised learning. Because all human knowledge begins with unlabelled data. After human discover the natural patterns behind the phenomenon, they begin to label various things to accumulate knowledge and gain further insights. Unsupervised learning is difficult to teach because, in the first place, you don’t even know whether there is a pattern to look at, let alone what’s the important features.

Unsupervised algorithms

  1. K-means clusters. cons: bad starting points may lead to the bad local minimum.
  2. Single Linkage clustering. consider each object a cluster, merge the closest together.
  3. Expectation Maximization. soft clustering.

Feature selection

from m features, select n features is an NP-hard problem, has a complexity of n^m
speed main characteristics implement
filtering fast ignore the learner and no feedback Information gain
wrapping slow takes into account model bias and learning forward (adding) backward (subtract)
  • Relevance: information, Bayes optimal classifier (no bias)
  • usefulness: reduce error, bias help break the tie.

PCA

  • a systematic way to transform input features into principal components.
  • use PCs as new features
  • Maximum variance as the principal component, so as to minimize the information loss.
  • PCs are independent features.
when to use:
  • latent features driving the patterns
  • dimensionality reduction (human can only draw 2D scatterplot!).
  • It is a data preprocessing. So it can be used in both supervised or unsupervised learning to reduce noise and reduce overfitting.

facial recognition

How many PCs to use? (measured by f1 score due to multi-class labels)
No of PC F1 score
15 0.65
25 0.74
50 0.81
100 0.85
250 0.82

Feature transformation

have overlap with feature selection.
independent component analysis

Customer segments

content has been merged into p3_Customer Segments

Thursday, February 2, 2017

Machine Learning ND 4, Deep learning, TensorFlow

[TOC]

Update 2017-4-1

When studying Deep Learning nanodegree, I noticed that Udacity has done a major overhaul for this course. It is much better than the old one.

Update 2017-3-1

This section is exactly the same with the free course: deep learning, by Vincent Vanhoucke at google research. However, he talked fast on the workflow. It is more like a review session. So it is extremely difficult to follow. To fill this gap, Udacity is currently developing Deep Learning Foundation ND.
To recap, I would recommend the following order to study:
  1. Read through Michael Nielsen’s online book, Neural network and deep learning. It does an amazaing job in explaining the key concepts and frankly explains what’s known and what’s unknown, how the technique evolved. Run his code and try to understand what’s happening. In Chapter 6, in order to implement convolutional network, he uses theano module to do the dirty job.
  2. Study tensorflow and finish its official documentation from basics up to the application of convolutional networks. Understand the terms like graph, session, interactive session, tensor, operation.
  3. The free course by Udacity provides 6 assignments, which is a good practice to be familiar the use of tensorflow after the official tutorial. I would recommend at least finish 1, 2, 3, 4, which are handwriting recognition tasks. I think 5,6 are optional, because they are about another topic, text processing. Personally, I believe computer is only able to “mechanically” understand the text by its context, losing the big picture of culture, human interaction, emotions. It can think, but it can’t feel, which is hard-coded to human’s genes by millions year of biological evolution.
  4. The final project: multi-digit recognition. Actually, the difficulty of this project is not about how to apply deep learning, but how to get a high-quality dataset from messy reality. How does the computer know there is a digit, how to catch it, resize it and convert into trainable data. Make this automation is possible, but not so easy.
The comeback of neural networks due to data & GPU power:
  • 2009 speech recognition
  • 2012 computer vision
  • 2014 machine translation
The following 6 notebooks are originally hosted at https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/udacity . It is subject to future update.

1_notmnist.ipynb

It basically do the following things:
  1. the notMNIST data seems be hosted in an internal url of google: http://commondatastorage.googleapis.com/books1000/notMNIST_large.tar.gz. The data is ==500 k== training+ 19 k testing examples, with 10-factor labels from ‘A’ to “J”, “notMNIST_Large.tar.gz” is ~250 MB, the “notMNIST_Large.tar.gz” is ~8 MB, which serves as test set.
  2. use tarfile.open(), extractall() to open the .tar.gz file, extract to 10 file folders, each folder is a collection of the letter writing, e.g. ‘A’, with 52 k png files. The folder names are stored in variable called “train_folders“ or “test_folders”, a list of strings.
  3. use scipy.ndimage.imread() to convert a png file into a 2D imbeded array (28*28), normalize their pixel value by maximum(i.e., 255), put such ~52.9 k png files of each folder in a 52.9 k*28*28 numpy array, and pickle.dump() them into a .pickle file. 10 pickle files are stored in a list named “train_datasets”
  4. use np.random.shuffle() and extract 20k training, 1 k valid, 1k testing dataset within each class. The total training set is ==200k==.
  5. use np.random.permutation to shuffle the whole dataset
main codes
train_filename =maybe_download('notMNIST_larget.tar.gz',247336696) # string
train_folders =maybe_extract(train_filename) # list of string, each represent a folder
train_datasets =maybe_pickle(train_folders,45000) # list of string, each represent a .pickle file of a np.ndarray
valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets(train_datasets,200e3,10e3) # np.ndarray
train_dataset, train_labels = randomize(train_dataset, train_labels) # np.ndarray
At last, the 6 datasets (feature and labels of train, valid, test) are packed into a dictionary and pickle.dump into “notMNIST.pickle”, with a size of 690 MB. The large size is only because its compress rate worse than a .tar.gz file.

Logistic Regression

from sklearn.linear_model import LogisticRegression
clf=LogisticRegression()

nsamples, nx, ny = train_dataset.shape
X_train = train_dataset.reshape((nsamples,nx*ny))
y_train = train_labels

nsamples, nx, ny = test_dataset.shape
X_test = test_dataset.reshape((nsamples,nx*ny))
y_test = test_labels

train_size = 5000
test_size = 1000
clf.fit(X_train[0:train_size], y_train[0:train_size])
print(clf.score(X_test[0:test_size], y_test[0:test_size])) #0.864

2_fullyconnected.ipynb

  1. Data reshape.
  2. TensorFlow with simple gradient descent. Use 10 k samples and 801 epoches, get ~ 80% accuracy. Remember that 10 k subset is only 2% of the total 500 k dataset. The reason of doing so is to save time because gradient descent is time expensive.
  3. TensorFlow with stochastic gradient descent. 10 k samples, 128 batch size, 3001 epoches, get ~ 85% accuracy. This is actually the “beginner” tutorial, which has 92%.
One of the difficulty is the accuracy function, because the size of training set and test set is different. The trick is when creating placeholder, set shape =(None,neuron_num).
get 89%. Strange thing is valididation accuracy is only 82%. see complete code

3_regularization.ipynb

why did we don’t figure out earlier that neural network were effective?
Many reasons.
  1. deep learning model only really shines when you have enough data to train them.
  2. better regularization techniques: L2 regulation, dropout
what changes train size, bacth,epoch accuracy
L2 regularization 200k, 128,4k 0.905
drop out 200k, 128,4k 0.906
learning rate decay 200k,128,4k 0.901

4_convolutions.ipynb

Follow “expert” tutorial can do the job.

5_word2vec.ipynb

The father of information retrieval is Gerard Salton, who proposed Vector Space Model in 1975. The basic idea of this model is Distributional Hypothesis, that the words that appear in the same contexts share semantic meaning.
A group led by Tomas Mikolov at Google created a word embedding toolkit word2vec, which is based on 2-layer neural networks.Two popular flavors are Continuous Bag-of-Words model and Skip_gram Model. TensorFlow website provide a tutorial for the latter. The notebook is adapted from word2vec_basic.py. A more serious implementation is here.
The principle in word2vec is use a noise classifier. In the same context, the realtarget word is assigned high probability, other k imaginary noise word low probabilities. It is computationally efficient because only k words instead of the whole dictionary is consindered. Such a binary logistic function is called noise-contrastive estimation(NCE) loss.
A vanilla definitionof the context is to use the right& left words, i.e., (context, target)=([left, right], middle) as input/output pairs, the noisy (contrastive) examples are drawn from some noise distribution, like nuigram distribution.
visualize the learned vectors by projecting to 2D, using t-SNE.
One way of evaluation is to calculate the distance between target and other words. Another way is to use analogical reasoning.

6_lstm.ipynb

LSTM, recurrent NN

Practical Methodology for Deploying machine learning

2015.10, AI with the best.
3 step process
  1. use needs to define metric-based goals
  2. build an end-to-edn system
  3. data-driven refinement
identify the most difficult part as soon as possible.
Deep or not?
  • lots of noise, little structure -> not deep
  • little noise, complex structure -> deep
Just get familiar with one ML and know how to tune is enough.
what kind of deep?
  • No structure -> fully connected
  • spatial structucture -> convolutional
  • sequential structure -> recurrent
baseline: 2-3 hidden layer, ReLU, dropout, SGD+momentum

Friday, January 6, 2017

Fundamental of machine learning for predictive data analytics

by John D. Kelleher 2015
Best book in machine learning I have read so far! Cover very practical perspectives of machine learning problem.

1 Introduction

Because of the noise nature and finite sampling, Machine learning is an ill-posed problem, which can’t be completely determined by a unique solution.
In fact, searching for predictive models that are consistent with the dataset is equivalent to just memorizing the dataset. As a result, no learning is taking place it tells us nothing about the underlying relationship between the descriptive and target features. If a predictive model captures this underlying relationship between the descriptive and target features, it is said to generalize well. The goal of machine learning is to find the one generalizes best.
Machine learning is sometimes called inductive learning, because it learns a general rule from a finite set of examples. Every machine learning algorithm has inductive bias, which is a set of assumptions. Two types of inductive bias are restriction bias and preference bias. A inductive bias is a necessary prerequisite for learning to occur; without inductive bias, a machine learning algorithm cannot learn anything beyond what is in the data.
No particular inductive bias on average is the best one to use. (No Free Lunch Theorem). A core skill for a data analyst is to select the appropriate model. An inappropriate inductive bias can lead to underfitting or overfitting, when the model is too simple or too complex. The goal is to strike a good balance.
CRISPDM: cross industry standard process for data mining:
  • Business understanding. The goal of predictive data analytics projects is not building a prediction model, but things like gaining new customers, selling more products, or adding efficiencies ot a process. So, during the first phase in any analytics project, **the primary goal of the data analyst is to fully understand the business or organizational problem that is being addressed, and then to design a data analytics solution for it.
  • Data Understanding
  • Data preparation. convert required data sources into a well-form analytics base table(ABT)
  • Modeling
  • Evaluation
  • Deployment
predictive data analytics tools
  • application-based solution: IBM SPSS, SAS
  • programming. This has more flexibilities and newest analytics techniques, but learning curve is steeper and need to put extra burden on developers to implement infrastructural support as data management.

2 Data to insights to decisions

Albert Einstein
We cannot solve our problems with the same thinking we used when we created them
Organizations don’t exist to do predictive data analytics. Organizations exist to do things like make more money, gain new customers, sell more product or reduce loss. The prediction don’t solve business problems, but provide insight that help the organization make better decision to solve their business problem.
converting a business problem into an analytics solution:
  1. What’s the business problem? What are the goals that the business wants to achieve? Most of the time, organizations begin analytics projects because they have a clear issue that they want to address; but sometimes it’s simply because somebody in the organization feels that this is an important new technique that they should use it. Unless a project is focused on clearly stated goals, it is unlikely to be successful
  2. How does the business currently work? It’s not feasible for an analytics practitioner to learn everything about the business because they will move quickly between different areas. But they must possess situational fluency, that they can use correct terminology to build analytics solution for that domain.

data availability

A lack of appropriate data will simply rule out proposed analytics solutions to a business problem. The easy availability of data for some solutions might favor them over others.

4 Information-based learning

decision tree

Model Ensembles

Rather than creating a single model, they generate a set of models and then make predictions by aggregating(such as voting) the outputs of these models. A prediction model that is composed of a set of models is called a model ensembles.
Two standard approaches:
  • boosting. works by iterating creating models, which add biased to pay more attention to instanced misclassified by last model.
  • bagging(or bootstrap aggregating). Each training data set has a random sampling with replacement. A decision tree bagging and subspace sampling is called random forest.

5 Similarity-based learning

nearest neighbor algorithm is a lazy learner, which delays abstracting from the data until it is asked to make a prediction. It is relatively slow because it needs to store a large number of instances. It’s sensitive to redundant and irrelevant descriptive features. The advantage is that it’s robust to concept drift, which means the relationship between features and target may change over time.

6 Probability-based learning

Bayes’ Theorem
P(X|Y)= \frac{P(Y|X)P(X)}{P(Y)}
As early as 1700, Reverend Thomas Rayes wrote an essay that described how to update beliefs as new information arises. The modern mathematical form was developed by Laplace.
If X is target, Y is features, then Bayes’ Theorem can be used for prediction. Take X for categorical values, the maximum probability of P(Y|X_i)P(X_i) is chosen as the predicted value.
Prediction is kind of inverse reasoning (from evidence to event), which is often much more difficult than forward reasoning (from event to evidence). 事后诸葛亮. 20/20 hindsight.
Naive Bayes model is naive because it simply assume the independence between features. This greatly reduces the difficulty of computation. The maximum mechanism make it robust to noise.

7 Error-based learning

The value chosen for the learning rate and initial weights can have a significant impact on how the (batch) gradient descent algorithm proceeds. However, how to choose is more an art gathered through experience, rather than a well-defined science.
The gradient descent algorithm requires the results to be differentiable, but the simple linear regression with sign function fails to that, so the logistic regression with the logistic function cuts in and do the job:
logistic(x)=\frac{1}{1+e^{-x}} where x is the weighted sum.
Support vector machine took another approach, where the margins are defined by the support vectors. The negative target feature is set to -1 and the positive target feature is set to +1. Kernel trick is played on the descriptive features to moves the data into a higher-dimensional space.

11 The art of ML for predictive data analytics

Sherlock Holmes
It is a captial mistake to theorize before one has data. Insensibly one begins to twist facts to suit theories, instead of theories to suit facts.
Predictive data analytics projects use machine learning to build models that capture the relationships in large datasets between descriptive features and a target feature. Machine learning is a type of inductive learning, so they share some properties:
  1. the general rule induced from a sample may not be true for all instances in a population
  2. learning cannot occur unless the learning process is biased in some way, which means we need to tell the learning process what types of patterns to look for in the data. This bias is referred to as inductive bias.
  3. the outcome is also intentionally biased to suit our need.
An analytics project is often iterative, with different stages of the project feeding back into later cycle. It is also important to remember that the purpose of an analytics project is to solve a real-world problem and to keep focus on this, rather than being distracted by the admittedly sometimes fascinating, technical challenges of model building. The best way to keep an analytics project focused and to improve the likelihood of a successful conclusion, isto adopt a structured project lifecycle like CRISP_DM.

choosing a machine learning approach

No free lunch theorem.
A simple example shown in figure 11.2 reveals that each ml algorithm has its edge. The decision boundaries learned by each algorithm are characteristic of that algorithm
For small dataset, generative models are preferred than discriminative models because the prior structural information is encoded into the generative models, which can be used to generate data.