Monday, March 27, 2017

Deep Learning ND 2, sentiment analysis, image classification

Course schedule: week 3-6, lesson 10-23, project 2
Recap:

section 2

2 Sentiment Analysis with Andrew Trask

Andrew Trask is a PhD student at university of Oxford. He is currently writing a book: Grokking Deep Learning (40% Off: traskud17). It is an in-progress book and you prepay to read each chapter as he finishes.
course material is a few notebooks: Sentiment Network
Project end goal: analyze IMDB comments to infer “positive” or “negative”. The basical flow is:
  1. you have 25 k reviews with binary target features. The reviews can be decomposed to a vocabulory of 74 k words.
  2. write a home-made class called SentimentNetwork that preprocess data, construct a 10-node hiddenlayer network with sigmoid output and back propagation. The input layer has a size of the vocabulary—74k.
  3. last 1 k review is used for testing.
Dataset documentation: here.
miniproject 1
  1. use Counter() to build 3 vocabulary dictionaries to count positive, negative and total reviews
  2. Because the most common words are connecting/preposition words and appear in both positive and negative reviews, we use another counter to store the ratios of positive count to negative count. And use np.log to scale the very large ratio and very small ratio.
miniproject 2
  1. useset(total_counts.keys()) to build a vocabulary, i.e., a list of words.
  2. use a word2index dictionary to give index to each word
  3. vectorize each review based on this vocabulary.
miniproject 3
  1. construct a class named SentimentNetwork, initialize with a 10-node hidden layer.
  2. use 24 k instances of review for the training set, 1 k instances for testing set. Get 60% accuracy
miniproject 4
By setting self.layer_0[0][self.word2index[word]] = 1, the most common words such as space and preposition is restricted to value 1. The neural network is more effectively trained. A testing accuracy of 85% is obtained.
miniproject 5
Taking advantage of the sparsity of layer_0, only a few nodes that have value is used to calculate the weighted sum. This increases the training speed by 10 times.
miniproject 6
  1. use bokeh module to plot D3 style histogram.
  2. use min_count=10, polarity_cutoff = 0.1 to add the informative words to vocabulary. This further increases training speed by 4 times, although the accuracy is slightly reduced to 82%

Analysis

use the weights to see the similarity under the positive/negative context
def get_most_similar_words(focus = "horrible"):
    most_similar = Counter()
    for word in mlp_full.word2index.keys():
        weights_a = mlp_full.weights_0_1[mlp_full.word2index[word]]
        weights_b = mlp_full.weights_0_1[mlp_full.word2index[focus]]
        most_similar[word] = np.dot(weights_a,weights_b)
    return most_similar.most_common()
use sklearn.manifold.TSNE to cluster the words and visualize the results.

3 Intro to TFLearn

This lesson begins with a comparison for different activation functions:
  • sigmoid has a maximum value of dy/dx (0.25 per layer), it is difficult to train deep layers.
  • ReLu is better, but should be fine tune the learning rate to avoid local minimum at 0.
  • softmax is good for multi-class learning. Consequently, cost function is changed from sum of squared errors to cross entropy.
TFLearn does a lot of things for you such as initializing weights, running the forward pass, and performing backpropagation to update the weights. You end up just defining the architecture of the network (number and type of layers, number of units, etc.) and how it is trained.
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
reviews = pd.read_csv('reviews.txt', header=None) 
labels = pd.read_csv('labels.txt', header=None) # 25 k
from collections import Counter
total_counts = Counter()
for _, row in reviews.iterrows():
    total_counts.update(row[0].split(' ')) #have 74 k keys
vocab = sorted(total_counts, key=total_counts.get, reverse=True)[:10000] # key the 10 k most common words
word2idx = {word: i for i,word in enumerate(vocab)} # used to vectorize the word
def text_to_vector(text):
    word_vector = np.zeros(len(vocab), dtype=np.int)
    for word in text.split(' '):
        idx = word2idx.get(word,None) # get index or None
        if idx is None:    
            continue
        else:    
            word_vector[idx] += 1
    return np.array(word_vector)
word_vectors = np.zeros((len(reviews), len(vocab)), dtype=np.int_)
for i, (_, text) in enumerate(reviews.iterrows()):
    word_vectors[i] = text_to_vector(text[0]) # vectorize all reviews
Y = (labels=='positive').astype(np.int_)
records = len(labels)
y = to_categorical(Y,2)  # change 1 label to 2 labels
from sklearn.model_selection import train_test_split
X_train, X_test,y_train,y_test = train_test_split(word_vectors,y,test_size = 0.1)
Build and train model
def build_model():
    tf.reset_default_graph()
    net = tflearn.input_data([None,10000]) # unknown instances, 10000 nodes
    net = tflearn.fully_connected(net,200, activation = "ReLU")
    net = tflearn.fully_connected(net,25 , activation = "ReLU")
    net = tflearn.fully_connected(net, 2, activation = "softmax")
    net = tflearn.regression(net, optimizer= 'sgd', learning_rate = 0.1, loss= "categorical_crossentropy")
    model = tflearn.DNN(net)
    return model
model = build_model()
model.fit(X_train, y_train, validation_set=0.1, show_metric=True, batch_size=128, n_epoch=50)
predictions = (np.array(model.predict(testX))[:,0] >= 0.5).astype(np.int_)
test_accuracy = np.mean(predictions == testY[:,0], axis=0)
print("Test accuracy: ", test_accuracy)
The tricky thing here is TFLearn does not fully support TensorFlow.

Resources

  • Christopher Olah’s blog post on RNNs and LSTMs.This is the shortest and most accessible read.
  • Deep Learning Book chapter on RNNs.This will be a very technical read and is recommended for students very comfortable with advanced mathematical notation and scientific papers.
  • Andrej Karpathy’s lecture on Recurrent Neural Networks.This is a fairly long lecture (around an hour) but covers the content quite well as always with Karpathy.

7 MiniFlow

This miniflow aims to get you practice the architecture before everything is encapsulated in Tensorflow. My implementation is in this gist. The dataset used in the quiz is sklearn.datasets.load_boston.

9,11,12 TensorFlow

These 3 lessons repackaged Vincent’s previous deep learning course by adding more illustrative animations and more quizzes. Although I watched Vincent’s previous course several times, I didn’t fully understand what he means until this time. I realize why a picture worth a thousand words.

Keras

Previous course seems to be removed to somewhere)

Project 2: classify image from CIFAR10

cifar dataset is originally hosted at http://www.cs.toronto.edu/~kriz/cifar.html.
  • 163 MB
  • 60 k instances (50 k training +10 test), each 10 k instances is pickled into a batch
  • input featues are 32*32, target feature is 10 classes, corresponding to ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
  • use tensorflow to build a neural net including 1 cnn (32,5x5)+ maxpool + flatten + fully connected layer(1024-node) + dropout(10-node) + softmax_cross_entropy_with_logits

Thursday, March 23, 2017

SAS, University version

Why SAS?

SAS is short for “Statistical Analysis System”.
Timeline:
  • 1966, prototype was developed by Barr and Goodnight, and funded by NIH
  • 1976, they moved from North Carolina State University and founded SAS Institute.
  • 1985, SAS was rewritten in C to allow it run on Unix, MS-DOS, and windows.
  • 2002, Text Miner component was introduced.
  • 2010, a free version for student was introduced.
  • 2010-12, sued world programming, but European Court of Justice ruled that “the functionality of a computer program and the programming language cannot be protected by copyright”
So SAS has a long history and its target customers are enterprise analytics.
Features:
  • It is web browser based. Although starting a local server by virtual machine seems a little complicated, it has the advantage of cross-platform
  • It can be seen as “advanced statistical version“ of Excel, which has rich GUI for people to learn quickly and provides brilliant technical support.
  • Big corporations like SAS because there’s a complete ecosystem that satisfies customers’ every need.
  • its direct competitors are Stata and SPSS (acquired by IBM).
  • You click on the front-end, the corresponding codes are automatically generated in the back-end. This means you can have the code to generate the exact same graph or make changes on that.
  • Integrate with SQL seamlessly.
And the usage differs by industry sectors:

University Edition

This version is free. check here. SAS University Edition includes SAS® Studio, Base SAS®, SAS/STAT®, SAS/IML®, SAS/ACCESS® and several time series forecasting procedures from SAS/ETS®.
There are 2 approaches to get SAS running:
  1. download a .ova file (2.2GB). use virtual box to start a local host and run SAS locally.
  2. use AWS AMI: SAS University Edition. You have to pay EC2 fee ranging from 0.012-0.047 /hr. It’s actually pretty cheap.
Open a new browser window with http://localhost:10080/ And you are good to go.

learn

SAS programs have a DATA step, which retrieves and manipulates data, usually creating an SAS data set, and a PROC step, which analyzes the data.
data highchol;
    set sashelp.heart;
    where Chol_Status = "High";
run;
proc print data = highchol;
run;
proc print data = sashelp.cars;    /*two-level name: library.table */
    by Make;
    var Make Model Type;
run;

create library/ import csv

libname libsas 'S:/datafiles'; /* physical location of the dataset, which can be found in file's property */
data titanic;
    infile '/folders/myfolders/train.csv' dlm=',' firstobs=2; 
    input PassengerId Survived Pclass Name Sex;
run;
use proc import is much more convenient, you don’t need to manually assign the column name. video guide which uses the snippets
/** FOR CSV Files uploaded from Unix/MacOS **/
FILENAME CSV "/folders/myfolders/train.csv" TERMSTR=LF;
/** Import the CSV file.  **/
PROC IMPORT DATAFILE=CSV
            OUT=WORK.MYCSV
            DBMS=CSV
            REPLACE;
run;
/** Print the results. **/
PROC PRINT DATA=WORK.MYCSV; RUN;
/** Unassign the file reference.  **/
FILENAME CSV;
run;
Alternatively, you can use tasks and utilities -> utilities -> import data. Then drag and drop the file from the “server files and folders”.

Graph

scatterplot

ods graphics / reset imagemap;
proc sgplot data=SASHELP.CARS;
    title "Vehicle Statistics";
    scatter x=Horsepower y=MPG_City / group=Origin 
        markerattrs=(symbol=CircleFilled size=12) transparency=0.7 name='Scatter';
    xaxis grid;
    yaxis grid;
    keylegend / location=Inside across=1;
run;
ods graphics / reset;
title;
Other plots like barplot, histogram are similar.

Certification training

The ad is for version 9.3, 2011, while the latest version is 9.4, 2013.
There are several certification packages:
  • Base programming: 3.1 k
  • Advanced programming: 3.8 k/2.45k
  • Predictive Modeling: 2.65 k
  • statistical analysis: 3.05 k

Wednesday, March 22, 2017

AWS EC2, Bitfusion

I came to realize that Bitfusion built its business on AWS marketplace.
While our computers today are often extremely fast, most applications aren’t optimized for the hardware platform they are running on. Bitfusion, which debuted in May 2015 at TechCrunch Disrupt NY, wanted to automate all of this for developers. The company was founded by three former Intel employees in Austin, with a $1.45 million seed funding.
They have 3 business model: Software, appliance (with hardware accelerators), and the accelerated RackSpace Cloud. Why aren’t you going after large-scale enterprises? Large enterprises can build their own hardware and have the skills to do this for their specialized applications.
GPUs can speed up training times, but managing both the infrastructure and software for GPUs creates huge productivity challenges. Bitfusion provides a GPU virtualization and application management platform that accelerates applications and training time with no code changes, and makes it easy to efficiently manage production GPU clusters with high availability, team multi-tenancy, and parallel job execution.

Getting Started Video

  1. create key pair
  2. use Bitfusion Ubuntu 14 TensorFlow AMI.
  3. Region: Oregon. Instance: t2.small. Security: have 8888 port open. Key pair
  4. wait for ready. use “connect” button to get required commands like chmod and ssh -i.
  5. open new browser window with public DNS, plus port :8888 for jupyter. Password is instance ID. I don’t know the difference between DNS and IP right now. It seems http://<Public IP>:8888 also works.
  6. Then you see the 6 familar tensorflow/udacity notebooks
A script version of “getting started” is here.
After ssh link:
scp -i /path/to/your/pem/file path/to/file ubuntu@public_ip_address:~/.  # transfer files from local
python ~/tensorflow/tensorflow/models/image/mnist/convolutional.py
python ~/tensorflow/tensorflow/models/image/cifar10/cifar10_multi_gpu_train.py --num_gpus=4

price schema

  • Using a t2.nano, t2.micro, or t2.small? No Bitfusion software fee. Only AWS charges: 0.023/hr
  • Using a p2.8xlarge, p2.16xlarge, m4.16xlarge, x1.16xlarge, x1.32xlarge, i2.4xlarge, i2.8xlarge, or d2.8xlarge? $0.297/hour is your new, lower Bitfusion software fee.
  • g2.2xlarge is 0.65*1.1 = 0.715/hr
AWS recently announced their next generation GPU P2 instances. This new generation provides up to 16 NVIDIA K80 GPUs, 64 vCPUs and 732 GiB of host memory. In previous releases of our Bitfusion Tensorflow AMI, we included updated NVIDIA drivers, the CUDA toolkit, and CUDNN support, allowing you to tap into these new powerful instances.
By the way, their recent blog posts did a good job smoothing you on TensorFlow.

Monday, March 20, 2017

AWS Elastic Compute Cloud


Amazon Elastic Compute Cloud (EC2) is the Amazon Web Service you use to create and run virtual machines in the cloud. Each virtual machine is called instance.
AMI (Amazon Machine Images) contains all the environment files and drivers for you to train on a GPU. It has cuDNN, TensorFlow with GPU support, Python 3, and all the other packages required for this course.

launch an instance

In other words, create a virtual machine on the cloud. AMIs are prebuilt virtual environment. Community AMIs are free. Marketplace AMIs are charged or free to try. I come to realize the target customers are power-hungry, storage-hungry users.
Steps:
  1. create AWS account
  2. EC2 Dashboard -> create instance -> launch instance -> Choose an Amazon Machine Image (AMI) -> Community AMIs -> search for “udacity-dl”
  3. filter by “GPU instances” -> g2.2xlarge -> Review and launch
  4. edit storage -> 32 GB. This is the space to hold the datasets.
  5. edit security groups -> create a new security group -> Security group name: jupyter -> Add rule: Custom TCP rule, Port Range: 8888, Anywhere: Source -> Review and launch
  6. launch -> launch without a key pair
  7. Note on the EC2 On-Demand Pricing page. For US West(Oregon), the base price for g2.2xlarge is $0.65 per hour. The running instances will be charged until you click “stop” (shutdown). The storage will be charged until you click “terminate” (delete).
  8. set AWS Billing Alarms and budget to avoid high-piling bills due to forgetting to turn off the instances.
  9. GPU EC2 limit increase request takes 2 or 3 days, which is painfully slow.
  10. Alternatively, I try to use “Free tier” instance which is specified here: Amazon Linux AMI 2016.09.1 (HVM), SSD Volume Type - ami-0b33d91d -> t2.micro (free tier eligible) -> launch -> create a new key pair -> MyKeyPair -> Download KeyPair. It is recommended that the keypair is stored in the .ssh folder by mv ~/Downloads/MyKeyPair.pem ~/.ssh/MyKeyPair.pem
  11. After launching your instance, it’s time to connect to it. Restrict permissions to your private SSH key by chmod 400 ~/.ssh/mykeypair.pem
  12. use ssh to connect: ssh -i ~/.ssh/MyKeyPair.pem ec2-user@{IPv4 Public IP}
  13. this virtual machine is too simple to do useful tasks. It only preinstalls simple things: python 2.7,pip 6.1.1. And it seems that you are not allowed to install new things or upgrade. I don’t find it particularly useful so far.
If the udacity AMI instance can be successfully created and initialized, the connection will be ssh udacity@{IPv4 Public IP}. Default password is “udacity”. Test the instance by:
git clone https://github.com/udacity/deep-learning.git
cd deep-learning/intro-to-tensorflow/
source activate dl
jupyter notebook

Launch a WordPress Website

  1. EC2 dashboard -> launch instance -> AWS marketplace, search”wordpress” -> WordPress powered by Bitnami -> continue
  2. t2.micro(free tier eligible) -> Next -> Next, Add Tag -> Key: Name, Value: WordPress -> next -> review and launch -> launch -> launch without a key pair
  3. view instance. Wait until “Instance State: running, Status Checks: checks passed. Then copy and paste “IPv4 Public IP” to a new browser window to see the magic. Permalink: http://54.89.220.149/
  4. Go back to instances. Actions-> Instance settings -> get system log. Scroll down and find the password: 6LyeomW7L1F3
  5. Go back to WordPress site and log in by username: user, and password. Customize the site as you wish.

Register a Domain name

steps:
  1. Click here to open the Elastic IP part of the EC2 console in a new window and click “Allocate New Address” 34.205.189.152
  2. Elastic IP address (EIP) will be charged for $ 0.005/hr unless it is connected to running instances.
  3. Actions-> Associate Address -> Instance: your instance
  4. buy a domain name. I already bought one at google domain, which is equivalent to Amazone Route 53.
  5. The trick is that I not only need to go to google domain to redirect my domain name to the EIP, but also go to Blogspot setting page to check all the redirecting.

Friday, March 17, 2017

The business of deep learning

The Business of Deep Learning
Understanding Deep Learning and Discovering Real World Applications
By Matt Coatney
Publisher: O’Reilly Media
Final Release Date: February 2017
Run time: 3 hours 30 minutes
Video: $64.99

course note

Overview: The first 2 lessons (~30 min)are free and give you an introduction and the 5 areas that will be covered:
  • characterize the world (36 min)
  • identify and group things together (27 min)
  • predict outcome and behavior (18 min)
  • human-machine interaction (30 min)
  • robotics and real-world interaction (22 min)
The details are charged. Then ends with implications (30 min) and conclusion(14 min).

Why now?
  1. Business need: hyper competition, knowledge economy
  2. data: natively digital, sensors, internet of things
  3. methods: large neural nets, ensemble/panel of experts
  4. compute power: exponential growth, GPU
AI:
  • more than just deep learning
  • ensemble of techniques approaching human intelligence
  • no clear definition or finish
4 possibilities for business models: (risk from high to low)
  1. platform( expensive, IBM Watson, Google tensor flow, Microsoft cntk, caffe, torch)
  2. consulting service (customized solutions, people intensive, not scalable)
  3. technique core (backbone for other specific technology)
  4. enablement (integration in application: Netflix,google, facebook, amazon)
questions:
  • which business models are most applicable to your industry?
  • what initial ideas do you have for monetizing deep learning?

characterize the world

extract features: image, audio, video, text

identifying and grouping things:

  • segmenting(clustering)
  • categorizing(classification)
dimensionality reduction: principle component analysis,
predicting outcomes/behavior
  • making recommendations
  • making prediction

building buy-in for AI projects

  • fear of change
  • identify a pressing,burning need
  • avoid pitching/building a platform
  • incrementally target new high-value needs
  • use past success as internal social proof
  • look for adjacent opportunity
  • follow the money

Driving User Acceptance

  • Teach: time, empathy, awareness, communication, help
  • If you communicate about 10 times as much as you should, you are starting to get it right.
  • create the climate for change: create urgency, form a powerful coalition, create a vision for change.