Sunday, January 15, 2017

Elon Musk's Quote

  • The problem is that at a lot of big companies, process becomes a substitute for thinking. You’re encouraged to behave like a little gear in a complex machine. Frankly, it allows you to keep people who aren’t that smart, who aren’t that creative.
  • I think that’s the single best piece of advice: constantly think about how you could be doing things better and questioning yourself.
  • I think it’s very important to have a feedback loop, where you’re constantly thinking about what you’ve done and how you could be doing it better.
  • When something is important enough, you do it even if the odds are not in your favor.
  • If you go back back a few hundred years, what we take for granted today would seem like magic - being able to talk to people over long distances, to transmit images, flying, accessing vast amounts of data like an oracle. These are all things that would have been considered magic a few hundred years ago.
  • I’ve actually made a prediction that within 30 years a majority of new cars made in the United States will be electric. And I don’t mean hybrid, I mean fully electric.
  • When I was in college, I wanted to be involved in things that would change the world.
  • There have only been about a half dozen genuinely important events in the four-billion-year saga of life on Earth: single-celled life, multicelled life, differentiation into plants and animals, movement of animals from water to land, and the advent of mammals and consciousness.
  • The reality is gas prices should be much more expensive then they are because we’re not incorporating the true damage to the environment and the hidden costs of mining oil and transporting it to the U.S. Whenever you have an unpriced externality, you have a bit of a market failure, to the degree that externality remains unpriced.
  • I don’t spend my time pontificating about high-concept things; I spend my time solving engineering and manufacturing problems.
  • Patience is a virtue, and I’m learning patience. It’s a tough lesson.
  • Life is too short for long-term grudges.
  • I’ve actually not read any books on time management.
  • I do think there is a lot of potential if you have a compelling product and people are willing to pay a premium for that. I think that is what Apple has shown. You can buy a much cheaper cell phone or laptop, but Apple’s product is so much better than the alternative, and people are willing to pay that premium.
  • There are some important differences between me and Tony Stark, like I have five kids, so I spend more time going to Disneyland than parties.
  • I tend to approach things from a physics framework. And physics teaches you to reason from first principles rather than by analogy.
  • If humanity doesn’t land on Mars in my lifetime, I would be very disappointed.
  • I would like to fly in space. Absolutely. That would be cool. I used to just do personally risky things, but now I’ve got kids and responsibilities, so I can’t be my own test pilot. That wouldn’t be a good idea. But I definitely want to fly as soon as it’s a sensible thing to do.
  • People work better when they know what the goal is and why. It is important that people look forward to coming to work in the morning and enjoy working.
  • I wouldn’t say I have a lack of fear. In fact, I’d like my fear emotion to be less because it’s very distracting and fries my nervous system.
  • I always invest my own money in the companies that I create. I don’t believe in the whole thing of just using other people’s money. I don’t think that’s right. I’m not going to ask other people to invest in something if I’m not prepared to do so myself.
  • The United States is definitely ahead in culture of innovation. If someone wants to accomplish great things, there is no better place than the U.S.
  • Physics is really figuring out how to discover new things that are counterintuitive, like quantum mechanics. It’s really counterintuitive.

Saturday, January 14, 2017

Theano with GPU, setup and trouble shooting

Environment setup is always a headache for me. The only way to fight back is documenting every step I did before as detail as possible.
I will find time to finish this udacity course on Linux Comand line
I am now using MacBook Pro (2013) with OS X El Capitan, 10.11.6.
cpu: 2.4 GHz i7;
memory: 8G
graphics : NVIDIA GeForce GT 650M 1024 MB.
[TOC]

Background knowledge refresh

To have effect after making some changes, you need to restart terminal.Alternatively. you could execute source ~/.bash_profile to reload your settings.

Bash file

There may or may be not a default file in home directory named .bash_profile.
I configure the git workspace by this udacity video about tab completion, prompt color and git editor. Because I ran git config --global core.editor "atom —wait", so each time if I git commit and open a new file to documment the changes, I have to close the file before I continue.

Set path

to check your working directory: pwd
to check path: echo $PATH
The paths shown are actually written in two files:
/etc/paths
~/.bash_profile
in the first file, you can direct write the path; in the second file, you write your path in the format
export PATH="xxx:$PATH"
xxx represent your actual path.
The nice thing about bash_profile is you can use alias mlnd=" cd Desktop/Udacity/MLND/course_material/projects/" to save a long path for your frequent use.

Theano

Theano is a machine learning library, http://deeplearning.net/software/theano/
  • easy to implement backpropagation for convolutional neural networks
  • can run code on either a CPU or a GPU.
Basically, there are 3 steps to use Theano with GPU enabled:
  1. sudo pip install Theano
  2. download and install CUDA toolkit,which includes a compiler for NVIDIA GPUs. https://developer.nvidia.com/cuda-toolkit.
  3. configure Theano and CUDA

enable GPU

after nosetests theano, I found something is missing, then pip install nose_parameterized
write these into .bash_profile
# Theano and CUDA
export PATH="/Developer/NVIDIA/CUDA-8.0/bin/:$PATH"
export LD_LIBRARY_PATH=/Developer/NVIDIA/CUDA-8.0/lib/
export CUDA_ROOT=/Developer/NVIDIA/CUDA-8.0/
export THEANO_FLAGS='mode=FAST_RUN,device=gpu,floatX=float32'
test GPU or cpu
from theano import function, config, shared, sandbox
import theano.tensor as T
import numpy
import time

vlen = 10 * 30 * 768  # 10 x #cores x # threads per core
iters = 1000

rng = numpy.random.RandomState(22)
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))
f = function([], T.exp(x))
print(f.maker.fgraph.toposort())
t0 = time.time()
for i in range(iters):
    r = f()
t1 = time.time()
print("Looping %d times took %f seconds" % (iters, t1 - t0))
print("Result is %s" % (r,))
if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):
    print('Used the cpu')
else:
    print('Used the gpu')
used the cpu took 2 .06 seconds; used the gpu took 1.22 seconds

Another guide

http://daoyuan.li/installing-theano-and-cuda-on-mac-os-x/ provides detailed guidance and 2 comparison examples of GPU/CPU
write a python file, check.py
from theano import function, config, shared, sandbox
import theano.tensor as T
import numpy
import time

vlen = 10 * 30 * 768  # 10 x #cores x # threads per core
iters = 1000

rng = numpy.random.RandomState(22)
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))
f = function([], T.exp(x))
print(f.maker.fgraph.toposort())
t0 = time.time()
for i in xrange(iters):
    r = f()
t1 = time.time()
print("Looping %d times took %f seconds" % (iters, t1 - t0))
print("Result is %s" % (r,))
if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):
    print('Used the cpu')
else:
    print('Used the gpu')
in command line:
THEANO_FLAGS=mode=FAST_RUN,device=cpu,floatX=float32 time python check.py 
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 time python check.py
The results is 8.44 vs 6.3
But another test file, lr.py shows the opposite.
I also try example codes of chapter 6 from “Neural networks and deep learning” by Michael Nielsen. I get 60% reduction of running time. However, my excitement didn’t last long. I soon get “Initialisation of device gpu failed! Reason=CNMEM_STATUS_OUT_OF_MEMORY”. I tried to set cnmem= 1.0 or 0.9, but no help.
At last, I resort to https://github.com/phvu/cuda-smi to check my gpu. Still no idea.
I had to close everything and restart. still failed! Then I change cnmem =0.1 and succeed. What a joke~ I realize my poor GPU is not meant for such deep learning computing. The memory management is far from optimization. Remember: theano is at 0.8 version, CUDA is also at 0.8 version. They are still at very early stage. Note that nvidia just built first AI supercomputer, which cost $129 k!

life is better with cloud service

http://www.pyimagesearch.com/2014/10/06/experience-cudamat-deep-belief-networks-python/ didn’t get an improvement after using GPU, and suggested using cloud service:

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.

Wednesday, December 28, 2016

Machine learning ND 3, reinforcement learning

Reinforcement learning

This project is easier than I expect. It only use very simplied version of Bellman equation. Use a dictionary to implement the Q-learning greatly reduces the complexity.

Smartcab

cd Desktop/Udacity/MLND/course_material/projects/smartcab/

pygame

pip install pygame
python smartcab/agent.py
warning: don’t use conda install! It wasted me 2 hours to realize what’s the problem.
With GUI open, a single trial has about 120 steps and takes about 4.5 minutes.

code structure

agent.py{
  class LearningAgent(env.Agent):{
    __int__(env,learning,epsilon,alpha)
    reset()
    build_state()
    get_maxQ(state)
    createQ(state)
    choose_action(state)
    learn(state,action,reward)
    update()
  }
  run()
}

simulator.py{
  class Simulator(){
      __init__(env,size,update_delay,
      display,log_metrics,optimiazed){
      / line 90-110 write header
      }
      run(tolerance,n_test){
      /line 133 "total_trials>20"for training number control
      /line 229-245 write data to csv file
      }
      render_text(trial,testing){}
      render(trial,testing){}
      pause(){}

  }
}

environment.py{
  class TrafficLight(){}
  class Environment(){
    __init__(verbose,num_dummies,grid_size){}
    create_agent(agent_class,*args,**kwargs){}
    set_primary_agent(agent,enforce_deadline){}
    reset(testing){}
    step(){}
    sense(agent){}
    get_deadline(agent){}
    act(agent,action){}
    compute_dist(a,b){}
   class Agent(){}
   class DummyAgent(Agent){}
  }
}

key implementation:

with GUI off, this runs super fast.
revise run() by:
env = Environment(verbose = False, num_dummies = 100, grid_size = (8, 6))
agent = env.create_agent(LearningAgent, learning = True, epsilon = 1,  alpha = 0.3)
env.set_primary_agent(agent, enforce_deadline = True)
sim = Simulator(env, size = None, update_delay = 0.01, display = False, log_metrics = True, optimized = True)
sim.run(tolerance = 0.05, n_test = 10)
implement function by:
def reset(self, destination=None, testing=False):
    self.planner.route_to(destination)
    #self.epsilon -= 0.05  # decaying function for question 6
    self.epsilon *= 0.95 # for question 7
    if testing:
        self.epsilon, self.alpha = 0, 0
    return None

def build_state(self):
    waypoint = self.planner.next_waypoint() 
    inputs = self.env.sense(self)          
    deadline = self.env.get_deadline(self) 
    state = (waypoint,tuple([inputs[item] for item in inputs]))
    return state

def get_maxQ(self, state):
    maxQ = float('-inf')
    for key,value in self.Q[state].iteritems():
        maxQ = max(maxQ, value)
    return maxQ

def createQ(self, state):
    if not self.Q or state not in self.Q:
        self.Q[state] ={None:0.01,   'left':0.0, 'right':0.0,    'forward':0.0}  # give idle a slightly priority
    return

def choose_action(self, state):
    self.state = state
    self.next_waypoint = self.planner.next_waypoint()
    # action = None
    waypoint = self.next_waypoint
    import random
    actions = [None, 'left','right', 'forward']  

    if not self.learning:
        action = random.choice(actions)
    else:
        highest = self.get_maxQ(state)
        action_dict = self.Q[state]

        coin = random.random()
        if coin <= self.epsilon:
            if action_dict[waypoint] == 0.0:
                action = waypoint
            else:
                action = random.choice(actions)
        else:
            for key,value in action_dict.iteritems():
                if value == highest:
                    return key
    return action

def learn(self, state, action, reward):
    if self.learning:
        self.Q[state][action] += self.alpha*reward   
    return