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

Monday, February 6, 2017

The ever-changing landscape

Update on 2017.2.16: TensorFlow 1.0
I started to learn machine learning in September 2016, and recently found that some python functions from the machine learning library was already deprived. I realize now machine learning is growing so fast that the API is being updated non-stop to better suit the real-world requirements.
Here are some notes to track the grammar changes that affect my projects.

Tensorflow

tf.initialize_all_variables() # 0.11
tf.global_variables_initializer() # 0.12

scikit-learn

from sklearn.model_selection import validation_curve, train_test_split, GridSearchCV, KFold, cross_val_score  # 0.18, 
from sklearn.cross_validation import train_test_split # 0.17

Note:

model_selection is a new module, which groups several functionalities together:
  • cross_val_score(svc, X, y, cv=KFold(N_splits=3, n_jobs=-1) is very convenient. You get 3 sets of data, fit, prediction and score in one line of code. So you can easily see the variation caused by data fluctuation.
  • A more fancy way is to use validation_curve, in which you get both training score and test score for a set of hyperparameters. e.g. train_scores, test_scores = validation_curve(SVC(), X, y, param_name="gamma", param_range=np.logspace(-6,-1,5), cv=10, scoring="accuracy", n_jobs=1)
  • An even more fancy way is to use learning_curve, in which you see the score change with data size. e.g. train_sizes, train_scores, valid_scores = learning_curve (SVC(kernel='linear'), X, y, train_sizes=[50, 80, 110], cv=5)
  • Don’t forget the previous GridSearchCV is still powerful.

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

Thursday, January 26, 2017

AMPL

AMPL, short for “A Mathematical Programming Language”, is an algebraic modeling language and the most powerful tool for linear programming problem and operation research. One advantage of AMPL is that its syntax is similar to the mathematical notation of optimization problems. It is the most popular input is NEOS:
market share
AMPL itself is free, but it doesn’t solve problems directly. Instead, different algorithms have been developed to solve application-oriented problems. These algorithms are packaged as so-called solvers. Hence, solvers are equivalent to toolbox of Matlab, library of R, or API of many general-purpose programming languages. Among AMPL solvers, CPLEX by IBM Corporation is most widely used. Solver performance is highly application-dependent.
To get started, AMPL IDE can be downloaded from official website http://ampl.com/. Basically, there are 4 ways to get the free lunch:
  1. demo version, problem-size limited (under 300 variables/constraints, etc)
  2. 30-day trial, full feature, requested individually
  3. courses version, requested by teacher
  4. cloud service by NEOS Server
For purchase, you will see solvers are sold annually, because solvers are the core part. Anyway, demo version is enough for personal use.

AMPL grammer

  • comment by #
  • variables are declared by var
  • parameters are declared by param
  • each line of code ends with a semi-colon; otherwise, you get ==ampl?== in console window because the computer thinks you have not finished.
  • objective format: maximize or minimize, a name, and a colon, then statement
  • constraint format: subject to, a name, and a colon, then statement.
  • keywords are in lowercase.
  • \sum_{i=1}^n is written as sum{i in 1..n}
  • output variables in the console by display. It’s a sharp contrast with Matlab, in which you can directly output anything without keyword without the semicolon. In AMPL, you must display 1+1,sqrt(2),2^3;
A typical input in console is:
reset;
model example.mod;
data exmple.dat;
solve;
display x;
The separation of model and data is the key to describing complex problems.

key concepts

  • decision variables: whose values are to maximize profits or reduce loss
  • feasible solutions: those satisfy all constraints.

the hardest tasks

  1. formulating a correct model
  2. providing accurate data

examples

A simple 2-variable example

# prod0.mod
var XB;
var XC;
maximize Profit: 25 * XB + 30 * XC;
subject to Time: (1/200) * XB + (1/140) * XC <= 40;
subject to B_limit: 0 <= XB <= 6000;
subject to C_limit: 0 <= XC <= 4000;

solve;
display XB,XC,Profit
A shortcut to execute is to save first, then right click in the script window-> AMPL command -> model. As we see in the console window, computer finds an optimal solver for you: MINOS 5.51.

multi-parameter example

# prod.mod
reset;
set P;
param a {j in P};  # tons per hour of product j
param b;           # hours available
param c {j in P};  # profit per ton of product j
param u {j in P};  # max tons of product j
var X {j in P};    # tons of product j
maximize Total_Profit: sum {j in P} c[j] * X[j];
subject to Time: sum {j in P} (1/a[j]) * X[j] <= b;
subject to Limit {j in P}: 0 <= X[j] <= u[j];

data /Users/yuchaojiang/Downloads/amplide.macosx64/models/prod.dat;
solve;
display X, Total_Profit;
# prod.dat
data;
set P := bands coils;
param:     a     c     u  :=
  bands   200   25   6000
  coils   140   30   4000 ;
param b := 40;
Actually, you can also combine the two files into one. This save the calling by data prod.dat and you have all the data in one page.

some tricks

  • prefer longer, more meaningful names
  • use cd; or display _cd; and cd path; to show directory and change directory

Wednesday, January 25, 2017

Text Analytics

Text mining, or text analytics, is to derive high-quality information from text.
  • devising patterns and trends
  • 80% of enterprise information originates and is locked in the unstructured form, rather than numerical data.
  • derive information from unstructured sources.
typical examples:
  • detect terrorist
  • find a protein in biomedical literature that may lead to a cancer.
The high quality is the first thing of text data:
  • choose the right source
  • That a source is available doesn’t mean it’s right for the job
  • source selection criteria include topicality, focus (high signal to noise ratio, currency, authority, your processing capabilities and analytics needs.
Three types of approaches:
  • co-currency based
  • rule-based
  • machine learning based

Natural Language ToolKit (NLTK)

The toolkit is powerful. However, after a few hours, I think this is a wrong direction to look at. Because disassemble the texts into words will lose the context information. Without context, the understanding is quite superficial. Machine is only good at “literal meaning”. Statistical learning is meant for numerical data, not text data.
To me, the nice thing about nltk is it has some great datasets that come from the master piece of English literature.
conda install nltk
python -m nltk.downloader all
import nltk
import IPython
from nltk.corpus import treebank
t = treebank.parsed_sents('wsj_0001.mrg')[0]
IPython.core.display.display(t)
from nltk.book import *
text1.concordance("monstrous")
text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"])
nltk.corpus.gutenberg.fileids()
from nltk.corpus import brown
brown.categories()
Statistical results may be interesting, but not as much as reading a real book from cover to cover.

Monday, January 16, 2017

TensorFlow, learning guide

[TOC]

Trailer

Predicting the long-term future is very difficult. Nobody can really do it. The greedy algorithm takes whatever’s working best now and assume the future’s going to be like that forever.
TensorFlow is an open source API for deep learning, developed by Google brain and released on 2015-11-9.
TensorFlow computation is done in a structure called graphs. The inner core of TensorFlow is actually written in C++ to speed up the calculation.
Major improvements in machine learning research result from advances in learning algorithms, computer hardware and high-quality training datasets. MNIST(Mixed National Institute of Standards and Technology) is a large database of handwritten digits for training image processing systems. It contains 60 k training images and 10 k testing images. Currently, the lowest error rate is 0.23% by a hierarchical system of convolutional neural networks.
Here is an interesting animation to illustrate the data flow in neural network: http://playground.tensorflow.org/

Basic Usage

TensorFlow is a programming system in which you represent computations as graphs. Nodes in the graph are called ops (short for operations). An op takes Tensors to performs some computation, where a Tensor is a typed multi-dimensional array.
A TensorFlow graph is a description of computations. To compute anything, a graph must be launched in a Session. A Session places the graph ops onto Devices, such as CPUs or GPUs, and provides methods to execute them. These methods return tensors produced by ops as numpy ndarray objects in Python.
TensorFlow programs are usually structured into 2 phases:
  1. construction phase, that assembles a graph,
  2. execution phase, that uses a session to execute ops in the graph.e.g. tf.Session().run()
Note: due to imcompatibility, turn on gpu will lead to painful error, so don’t do this: with tf.device("/cpu:0")

interactive session

Usually, we use Session.run() method to execute operations.
But in python, we can use InteractiveSession class, and the Tensor.eval() and Operation.run() methods. This avoids having to keep a variable holding the session.

fetch and feed

usually, we use fetch, where the value is preload. Otherwise, it is feed. we use placeholder() for creating ops, then use feed_dict to specific the values when we actually run.

Introduction

  • an example of how tensorflow solve a linear regression problem.
  • The trick is to initialize the weight and bias in a reasonable value. The network doesn’t have the magic bullet to get arbitrary things right.
  • the construction phase is actually writing symbolic math equation. Once I understand, it’s super easy to use.
# define weight,bias
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) 
b = tf.Variable(tf.zeros([1]))                     
y_pred = W * X_train + b
# define loss, optimizer
loss = tf.reduce_mean(tf.square(y_pred - y_train))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train_step = optimizer.minimize(loss)
# initialize the variables, build Session
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for step in range(101):
        sess.run(train_step)
    print(W.eval(),b.eval())
note:
  • train and init are Operations, they can only be run()
  • W and b are Variable, they can be run() or eval()

Beginners

Data extraction and preprocessing are done in input_data.py. But that file is just a transfer center. Real work is done from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets. Just in case you are interested the data source.
This is a 2-layer(784,10) neural network. Note that the loss function is tf.nn.softmax_cross_entropy_with_logits(logits=y,labels=y_).WARNING: This op expects unscaled logits, since it performs a softmax on logitsinternally for efficiency. Do not call this op with the output of softmax, as it will produce incorrect results.
batch size =100, gradient descent, learning rate = 0.5, accuracy is 92%.
Actually, I recommend beginner to learn tensorboard at the first place. see here
Smiley face

Experts

layer name size neuron type
input 784
h_pool1 32 conv+relu+max_pool
h_pool2 64 conv+relu+max_pool
h_fc1_drop 1024 relu+dropout
y_conv 10 logits
loss still use tf.nn.softmax_cross_entropy_with_logits
optimization useAdamOptimizer(1e-4)
Smiley face

Mechanics 101

The main file is fully_connected_feed.py,in which the graph is built by mnist.py.
It’s 4 layer network (784,128,32,10), the 2 hidden layers being ReLU. It seems complicated than the ‘experts’ version just because it tries to formulate every step, especially the interference() that define the graph structure.
The precision is only about 90% in 2000 steps 100 batch size, worse than the beginner version of 92% in 1000 steps 100 batch size. Why it behavior so poorly? It’s partially because the default learning rate is 0.01. I get 96% once I increase the learning rate to 0.1, and 97% when 0.2.
An useful trick learned is to print the loss, which is more directly than the precision. Although such loss is only for a small batch of data, yet this is what exactly happenning during the training process.