Monday, October 10, 2016

Reinforcement Learning

Reinforcement learning

  • the trade-off between exploration and exploitation. The agent has to exploit what it already knows, but it has to explore to make better action selection in the future.
  • it explicitly considers the whole problem of a goal-seeking agent interacting with an uncertain environment. In contrast, another machine learning approach considers subproblems without addressing how they might fit into a larger picture.
  • A large trend is that it has greater contact between AI, control theory and statistics.
Markov property: only present matters
One never learns anything from history.
Your current state remembers everything you need to remember from the past.

Markov Decision Process

states,
model,
actions,
reward: makes reinforcement learning different from supervised/un learning.
The solution is called policy.
  • The optimal policy is that maximize your long-term expected reward.
  • A concrete plan of what to do vs what’s the best next thing I can do
  • A plan tells you what sequence of actions you should take in a particular state
  • A policy tells you what action to take in a particular state.
  • reinforcement learning way is robust to the underlying stochastic of the world.
  • by having a small negative reward everywhere, it encourages you to end the game.
infinity horizon
the utility of sequence

Bellman equation

U(s)=R(s)+ \gamma*max\sum{T(s,a,s')U(s')}
value iteration: choose arbitrary value as the starting point for U
U_{t+1}(s)=R(s)+ \gamma*max\sum{T(s,a,s')U_t(s')}

BURLAP

BURLAP documentation: http://burlap.cs.brown.edu/doc/
GraphDefinedDomain

Reinforcement learning basics

evaluate a policy
  1. state transition to immediate rewards
  2. truncate according to horizon
  3. summarize sequence
  4. summarize over sequence
RL context:
  1. model-based.
  2. value-function-based
  3. policy search
more direct learning, less direct supervised

Temporal difference

learning rate properties:
\sum_T\alpha_T= \inf
\sum_T\alpha^2_T< \inf
TD(1), TD(0), TD(lambda)
eligibility, k-step estimator
convergence, generalized MDP

Advanced Algorithmic Analysis

  • Value iteration
  • linear programming
  • policy iteration

Reward shaping

(example of dolphin jumping through a hoop) Not only at grad school, but in life. We don’t get the big reward after we’ve inadvertently done the desired behavior. We get hints along the way.
potential function

Partially Observable MDP

You don’t really know the state

Why RL hard?

  • delay reward
it’s only told how it’s doing and not necessarily what it should be doing.
  • boot strapping, need exploration
  • number of states and actions

Game Theory

  • mathematics of conflict (of interest)
  • single agent -> multiple agents
  • ways of thinking about what happens when you’re not the only thing with intention in the world, and how do you incorporate other goals from other people who might or might not have your best interest at heart. How do you make that work.

outroduction

What RL different from supervised learning is not just input and output, you have to see states and rewards you take actions. All these things require interaction.
Just capture a big static set of data and presenting that to the learner isn’t really the RL process.

Friday, October 7, 2016

Intro to machine learning

Update on 2017-2-9

4 month later after this initial post, I almost finish Machine Learning Engineer NanoDegree. It is a perfect time for me to compare their difference.
The pros of “Intro“ course are that it’s free, fun to watch Sebastian’s self-driving car, and the videos are completely produced by him and a nice female Kattie. The cons are:
  1. no project feedback
  2. course materials seem not well organized. The sequence of their teaching is Naive Bayes, SVM, decision Trees, Regression, clustering, Feature scaling and selection, PCA, Evaluation Metrics. Are you kidding me? I think the correct approach should be exactly the reverse order! We should have a big picture first, then narrow down to a specific topic, so we don’t get used to the narrow-minded. The trick here is that a more specific thing is more easy and fun to teach!
  3. For Naive Bayes, Sebatian explained Bayes is a Christian trying to use evidence to infer the existence of God, and Naive is that it doesn’t consider the order of words. In my understanding, it can more explicitly that Naive is due to the assumption of independence of individual evidence. And NB algorithm is “probability-based“.
  4. sklearn 0.15 on 2014-11-11, then code updated on 2015-10
  5. the biggest problem is that it does too much preprocessing about the data and visualization, the student writes a few “magic code” to get a “good feeling” about himself. But actually he doesn’t earn as much because it’s a fake feeling and he lose the big picture.
  6. For a beginner course, it is better to use more simple, tansparant dataset. Enron email dataset is too overwhelming for a beginner. see my analysis at https://github.com/jychstar/datasets
The MLND course has a slightly better structure due to its available length. However, many materials are still scrambled together. For example, in supervised learning, SVM section is put after Neural Network. And SVM section begins with “GaTech” version, then Sebatian’s intro version. What a shame!
Anyway, if you are interested in the MLND, its sequence is:
  • Model Evaluation and Validation (project: predicting Boston Housing prices)
  • Supervised Learning (project: Finding Donors for Charity ML)
  • UnSupervised Learning (project: Creating Customer Segments)
  • Reinforcement Learning (project: Train a Smartcab to Drive)
  • Deep Learning (project: build a digit recognition program)
  • Capstone Project

Supervised learning

naive bayes

probabilistic classifier, apply Bayes’ theorem with strong independence assumption between features
from sklearn.naive_bayes import GaussianNB

accuracy

from sklearn.metrics import accuracy_score,fbeta_score
y_pred=clf.predict(features_test)
print accuracy_score(y_true, y_pred)
print fbeta_score(y_true, y_pred, beta)

support vector machine

non-probabilistic binary linear classifier, separate categories by a clear gap as wide as possible
parameters: kernel(linear, rbf), C, Gamma
from sklearn.svm import SVC

decision tree

from sklearn.tree import DecisionTreeClassifier
algorithm: max(information gain)=max(entropy(parent)-average*entropy(children))

k nearest neighbors

An object is classified by a majority vote of its k neighbors. instance-based learning, lazy-learning.
from sklearn.eighbors import KNeighborsClassifier()

adaboost

Adaptive Boosting, enhance individual weak learners (decision tree) by harder-to-classify examples. Sensitive to noisy data and outliers.
from sklearn.ensemble import AdaBoostClassifier

random forest

construct a multitude of decision trees and correct dt’s overfitting problems.
from sklearn.ensemble import RandomForestClassifier()

comparison

training data: makeTerrainData()
algorithm parameter No. of training time accuracy
k nearest neigh default=5 750 0.389 0.92
k nearest neigh neighbors=15 750 0.545 0.928
k nearest neigh neighbors=3 750 0.267 0.936
Ada boost est. 100 750 0.686 0.924
Ada boost est. 10 750 0.379 0.916
random 750 0.389 0.924

Accuracy vs Training set size

More Data > Fine-tuned Algorithm

regression

from sklearn import linear_model
reg=linear_model.LinearRegression()
reg.fit(features_train, labels_train)
pre=reg.predict([[27]])[0][0]
print "slope:",reg.coef_
print "intercept:", reg.intercept_
print "r-squared socre:"
test_score = reg.score(ages_test,net_worths_test)
training_score = reg.score(ages_train,net_worths_train)
classification vs regression
property supervised classification regression
output type discrete(class labels) continuous (ordered numbers)
goal decision boundary best fit line
evaluation accuracy r^2

remove outliers

data is a list of tuple, in which the 2nd element is used for sorting.
data.sort(key=lambda tup: tup[2])

unsupervised learning

cluster

k-means

feature scaling

from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler()
import numpy
data=numpy.array([[1.],[2.],[3.]])
re_data=scaler.fit_transform(data)

Text learning

countVectorizer

from sklearn.feature_extraction.text import CountVectorizer
clf=CountVectorizer()
bag_of_words=clf.fit(email_list)
bag_of_words=clf.transform(email_list)
print clf.vocabulary_.get('great')
Not all words are equal. Some words contain more information than others.

stopwords

(low-information, highly frequent word):
and, the, I, you, have,be, in, will

NTTK ( natural language tool kit)

import nltk
nltk.download()
from nltk.corpus import stopwords
sw = stopwords.words("english")
Stemmer
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer("english")
stemmer.stem("responsivity")
TF-IDF
term-frequency * inverse document-frequency
from sklearn.feature_extraction.text import TfidfVectorizer
clf=TfidfVectorizer(stop_words="english")
tfidf=clf.fit_transform(word_data)
print clf.get_feature_names()

feature selection

high bias:
  1. pays little attention to data
  2. oversimplified
  3. high error on training set
  4. few features used
high variance:
  1. pays too much attention to data
  2. overfit
  3. higher error on test set

PCA

principal component analysis
from sklearn.decomposition import PCA
pca=PCA(n_components=2)
pca.fit(data)
print pca.explained_variance_ratio_ #see which one has the largest variation
first_pc=pca.components_[0]
second_pc=pca.components_[1]

Validation and Evaluation Metrics

cross validation

To avoid overfitting by using the whole data set, it is randomly split into training and test sets.
#from sklearn.model_selection import train_test_split  # available after 0.18
from sklearn.cross_validation import train_test_split
features_train, features_test,labels_train,labels_test = train_test_split(iris.data, iris.target, test_size=0.4, random_state=0)

GridSearchCV

faces recognition

Evaluation Metrics

precision score: true positive/ all predict positive
recall score: true positive/ all real positive

Monday, September 26, 2016

Hanker Rank: order of word

Given a string, find the lexical sequence:
import math
def num(word):
    length=len(word)
    ans=math.factorial(length)
    wordset=set(word)
    for letter in wordset:
        fre=word.count(letter)
        ans=ans/fre
    return ans
def  get_ranks( words):
    if len(words)==1:
        return 0
    setwords=set(words)
    listwords=list(setwords)
    listwords.sort()
    prenumber=0
    head=words[0]
    seq=listwords.index(head)
    for i in range(seq):
        absent=listwords[i]
        k=words.index(absent)
        prenumber+=num(words[0:k]+words[k+1:])

    return prenumber+get_ranks(words[1:])

Friday, September 23, 2016

Subjective well-being

Subjective well-being (SWB) refers to how people experience the quality of their lives and includes both emotional reactions and cognitive judgments. Psychologists have defined happiness as a combination of life satisfaction and the relative frequency of positive and negative experience of feeling.
  • The study of SWB is a central concern of positive psychology.
  • Wealth. At first, SWB increases with income, but has diminishing marginal utility.
  • DNA. SWB is influenced by a combination of personality/genetics (50%), external circumstances (temporary effect) and mental/physical activities (more lasting improvement).
  • Health. SWB is highly correlated to health, which will provide positive feedback to health.
  • “The most salient characteristics shared by the 10% of students with the highest levels of happiness and the fewest signs of depression were their strong ties to friends and family and commitment to spending time with them.” (‘Very Happy People,” Psychological Science 2002)
  • Science of Happiness: Communicating, volunteer and caring, exercise, getting in the flow, spiritual engagement, strengths and virtues, positive thinking (gratitude, savoring and optimism)

Interesting websites for happiness:

why it doesn’t pay to be a people-pleaser

Live with total integrity. Be transparent, honest, and authentic. Do not ever waiver from this; white lies and false smiles quickly snowball into a life lived out of alignment. It is better to be yourself and risk having people not like you than to suffer the stress and tension that comes from pretending to be someone you’re not, or professing to like something that you don’t. I promise you: Pretending will rob you of joy.
  1. We don’t actually fool anyone
    We humans aren’t actually very good at hiding how we are feeling. We exhibit micro-expressions that the people we are with might not know they are registering but that trigger mirror neurons—so a little part of their brain thinks that they are feeling our negative feelings. So trying to suppress negative emotions when we are talking with someone—like when we don’t want to trouble someone else with our own distress—actually increases stress levels of both people more than if we had shared our distress in the first place.(It also reduces rapport and inhibits the connection between two people.)
  2. We find it harder to focus
    Pretending takes a huge conscious effort—it’s an act of self-control that drains your brain of its power to focus and do deep work. That’s because performing or pretending to be or feel something you’re not requires tremendous willpower.
    Tons of research suggests that our ability to repeatedly exert our self-control is actually quite limited. Like a muscle that tires and can no longer perform at its peak strength after a workout, our self-control is diminished by previous efforts at control, even if those efforts take place in a totally different realm.
So that little fib at the water cooler you told in order to make yourself seem happier than you are is going to make it hard for you to focus later in the afternoon. A performance or any attempt to hide who you really are, or pretend to be something you aren’t, is going to make it harder later to control your attention and your thoughts, and to regulate your emotions. It’ll increase the odds that you react more aggressively to a provocation, eat more tempting snacks, engage in riskier behaviors, and—this one is pretty compelling to me—perform more poorly on tasks that require executive function, like managing your time, planning, or organizing
  1. You’ll become more stressed and anxious
    Let’s just call it like it is: Pretending to be or feel something that you don’t—even if it is a small thing, and even if it is relatively meaningless, and even if it is meant to protect someone else—is a lie.
And lying, even if we do it a lot, or are good at it, is very stressful to our brains and our bodies. The polygraph test depends on this: “Lie Detectors” don’t actually detect lies, but rather they detect the subconscious stress and fear that lying causes. These tests sense changes in our skin electricity, pulse rate, and breathing. They also detect when someone’s vocal pitch has changed in a nearly imperceptible way, a consequence of tension in the body that tightens vocal chords.
We don’t lie or pretend or perform all the time, of course. But when we do, it’s important to see the consequences: increased stress, decreased willpower, impaired relationships. Although we might actually be trying to feel better by putting on a happy face for others, pretending always backfires in the end. Living in authentically makes life hard and cuts us off from our sweet spot—that place where we have both ease and power.

Thursday, September 22, 2016

Maslow's motivation theory

Maslow’s need hierarchy theory, original proposed in 1943, is the most popular theory of motivation in the management and Organizational Behavior literature. He studied the healthiest 1% of the college student population, because “the study of crippled, stunted, immature, and unhealthy specimens can yield only a cripple psychology and a cripple philosophy”.

The five levels of need are:

  1. physiological needs
    air, water, food, clothing and shelter
  2. safety needs
    personal security, finacial security, health and well-being
    safety net against accidents/illness/aftermath
  3. love and belonging
    friendship, intimacy, family
    it may override safety need as witnessed in abusive family
    a sense of belonging and acceptance among social groups, like clubs, co-workers, religious groups, professional groups
4, self-esteem/self-respect
be accepted and valued by others, gain recognition
low self-esteem: seek status, attention, fame or glory, need respect from others, but these won’t help build self-esteem until they accept themselves internally
high self-esteem: seek for strength, competence,mastery, self-confidence, independence, and freedom
  1. self-actualization/self-transcendence
    accomplish everything he can, e.g.: painting, inventions
    become the most he can be, e.g.: ideal parent
    giving himself to some higher goal beyond oneself, part of “a greater good”

Comments:

  • M. A. Wahba and L. G. Bridwell (1976): little evidence for the ranking of needs. They can be equally important, depending on age, culture, society development/ stability.
  • sex is listed in 1, which neglects the emotional, famillial, and evolutionary implication
  • 1-3 are defiency needs, 4-5 are growths needs
  • a deprivation may establish a dominance within his hierarchy of needs; conversely, a gratification of need will activate.
  • A long deprivation of a given need may turn him to other needs
  • some proposed dual-level hierarchy: maintenace needs(1-2),growth needs(3-5)
Carl Rogers, who advocated client-centered therapy and student-centered learning, said,
Every human being, with no exception, for the mere fact to be it, is worthy of unconditional respect of everybody else; he deserves to esteem himself and to be esteemed

Wednesday, September 21, 2016

A failed phone interview

On the second day of my previous post, I kind of rushed into a phone interview by G. I didn’t do a good job because I wasted quite a bunch of time on the format of inputs. I should better communicate with the interviewer.
Question: given 2 rectangles, output the intersection rectangle.
def getIntersection(r1,r2):
    '''
    :type r1:list[float]
    :type r2:list[float]
    # only need 2 x-coordiantes and 2 y-coordinates to represent a rectangle. e.g.[x1,x2,y1,y2] #re max,min of x; max,min of y
    :rtype list[float]
    '''
    if r1[0]<=r2[1] or r1[1]>=r2[0] or\
        r1[2]<=r2[3] or r1[3]>=r2[2]:
        return []
    listx=r1[0:2]+r2[0:2]
    ans_x=[x for x in listx if x<max(listx) and x>min(listx)]
    listy=r1[2:]+r2[2:]
    ans_y=[x for x in listy if x<max(listy) and x>min(listy)]
    return ans_x+ans_y