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

Thursday, September 8, 2016

Technical Interview

This course proivdes resources need to pull off the trick: data structures or a common pattern in the problem. Not every little details like the laws of physics, not at the level of mathematician.
In a real technical interview, you just need to show that you can successfully perform the trick and that you understand the concepts behind it.

outline

  1. Introduction and Efficiency
    Course Introduction
    Syntax
    Efficiency
    run time, storage space
    rely on you creativity and ability
    Notation of Efficiency
    big O notation
    worst case scenario ; upper bound
  2. List-Based Collections
    Lists
    append(), insert(),remove(elem), sort(), reverse() # these command don’t return new list
    pop(index)
    Arrays
    Linked Lists
    Stacks
    Queues
  3. Searching and Sorting
    Binary Search
    Recursion
    Bubble Sort
    n^2
    memory: O(1), in-position
    Merge Sort
    n log(n)
    Quick Sort
    worst case: O(n^2)
    average case: nlog(n)
  4. Maps and Hashing
    Maps
    Hashing
    Collisions
    Hashing Conventions
  5. Trees
    Trees
    Tree Traversal
    Binary Trees
    Binary Search Trees
    Heaps
    Self-Balancing Trees
  6. Graphs
    Graphs
    Graph Properties
    Graph Representation
    Graph Traversal
    Graph Paths
  7. Case Studies in Algorithms
    Shortest Path Problem
    greedy algorithm
    Knapsack Problem
    brute force solution, 2^n
    Traveling Salesman Problem
    NP hard.
    Not always have efficient solution
  8. Technical Interview Tips
    Mock Interview Breakdown
    1 clarifying the question
    prove to interviewer that you won’t dive head first into a probelm and potentially waste time writing code that doesn’t solve the initial issue.
    2 generating inputs and output
    3 generating test cases
    handle weird input
    4 brainstorming
    the interviewer is there to help you and being able to take in their feedback demonstartes your teamwork skills
    5 runtime analysis
    coding
    debugging
    Additional Tips
    Practice with Pramp
    Next Steps

Data Types

boolean = True
number = 1.1
string = "Strings can be declared with single or double quotes."
list = ["Lists can have", 1, 2, 3, 4, "or more types together!"]
tuple = ("Tuples", "can have", "more than", 2, "elements!")
dictionary = {'one': 1, 'two': 2, 'three': 3}
variable_with_zero_data = None

Conditionals

if cake == "delicious":
    return "Yes please!"
elif cake == "okay":
    return "I'll have a small piece."
else:
    return "No, thank you."

Classes

class Person(object): # inherit from object
    def __init__(self, name, age):
        self.name = name
        self.age = age 

    def birthday(self):
        self.age += 1

Friday, September 2, 2016

Product Design, how to start-up

Start ups are risky and costly business, it’s always wise to validate early on, build only what you need, and not more. And iterate as fast as you can.

Yunha Kim

  • After all, it’s not like you can choose whether to be a female CEO vs male CEO. But you can choose your attitude toward it.
  • I tend to be very aggressive. When I want to get things done, I’ll get them done. I tend to be impatient. But it helps me get stuff done.
  • We get gratification from seeing or building stuff in our hand.
  • This one idea that I have needs to be exectued perfectly and you succeed, otherwise a failure.
  • It’s my idea, my dream, I need to make it happen. If you consider as like, these are some of the ideas that we’ll try, if they fail, that’s okay, we’ll move on. At the end of the day, the worst thing happened to us is that we failed and we don’t know exactly why we fail.
  • knowing exactly why I failed is one of the learning that will help us go to the next.
  • The worst thing is to fail slowly and painfully over years.
  • failure is not the opposite of success, it’s a stepping stone to success.
  • learning and failing quickly, and never making the same mistake twice.
  • We fail? But screw your courage to the sticking post, and we’ll not fail.

Idea types

  • Simplify
  • Me too
  • Virtualize
  • Remix
  • Mission Impossible
The best problems to address are those that you have personal experiences with. Your commitment to finding a solution will be that much stronger and it will be the one thing that keeps you going through the crazy hights and the crazy lows of building a company.

Aaron Harris, founder of YCombinator

We are looking for founders who
  1. seems really great and formidable, so they can execute
  2. idea with chance of being a large business

best ideas

ideas across different industries https://www.ycombinator.com/rfs/
The very best startup ideas tend to have three things in common:
they’re something the founders themselves want,
that they themselves can build, and that
few others realize are worth doing. Microsoft, Apple, Yahoo, Google, and Facebook all began this way.
Why do so many founders build things no one wants?
Because they don’t use it themselves, they imagine other people wanting it.
it sounds plausible enough to fool you into working on them.
Paul Buchhei
Live in the future, then build what’s missing
If you’re not at the leading edge of some rapidly changing field, you can get to one. For example, anyone reasonably smart can probably get to an edge of programming (e.g. building mobile apps) in a year. Since a successful startup will consume at least 3-5 years of your life, a year’s preparation would be a reasonable investment.
Knowing how to hack also means that when you have ideas, you’ll be able to implement them. That’s not absolutely necessary (Jeff Bezos couldn’t) but it’s an advantage. It’s a big advantage, when you’re considering an idea like putting a college facebook online, if instead of merely thinking “That’s an interesting idea,” you can think instead “That’s an interesting idea. I’ll try building an initial version tonight.” It’s even better when you’re both a programmer and the target user, because then the cycle of generating new versions and testing them on users can happen inside one head.

Ted Talks

Nir Eyal: vitamin vs painkiller