Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

STAD80 Analysis of Big Data

Assignment: 4

Logistic Regression

You will have to submit ‘.rmd’ R Markdown, ‘.tex’ latex file (can be generated from R markdown) and ‘.pdf’ file (can be generated from R Markdown). I should knit the ‘.rmd’ file and compile ‘.tex’ file without troubles. The supporting documents should be zipped to ’.zip’ file. 

Question 1 (Upright Human Detection in Photos (25 points)). In this section, we are going to create a human detector that tells us whether there is a upright human in a given photo.  We treat this as a classification problem with two classes: having humans or not. You are provided with two datasets1 POS and NEG that have photos with and without upright humans respectively.

Part I: Preprocessing

(a) Randomly pick out one image in NEG and one in POS. For each of the two images, implement each step below to vectorize and extract useful information.  We provide functions that will be used in the following steps in a R-script functions.r. Please CAREFULLY read the appendixfor the detailed introductions of thesefunctions.

1. Download and install the package png, and use thefunction readPNG to load photos.

2.  Use thefunction rgb2gray3 to transform original photos to the black and white version.

3. Since photos in NEG have bigger sizes than those in POS, we need to crop them to keep consistency in dimen- sions. So for all photos NEG, use the function crop.r to randomly crop a 160 x 96 picture4 from the original one.

4.  Use thefunction grad to obtain the gradient field of the center 128 x 64 part of the grayscale matrix.

5.  Use the function hog (Histograms of Oriented Gradient) to extract a feature vector from the gradient field obtained in the previous step. Partition the height and width into 4 partitions each. Partition the angles into

intervals. (Your feature vector should then have 4 x 4 x 6 = 96 components.) Please see the appendix for parameter configuration of thisfunction.

For each of the two images, provide a picture showing each step above, i.e., the original picture 与 the black and white picture 与 the cropped picture (for NEG only) 与 the gradient field 与 the feature vector. An example of the procedure is illustrated in Fig.1. For thefeature vector, report its first six components.

(Hint: You can use writePNG(X,  target  =  ’filename.png’) to write some image array X to a png le. For exporting the plot generated by grad, you can use thefollowing code:

setEPS()

postscript( " test .eps " )

g=grad(X,  128,  64,  T)

dev.off ()


 

 

 

 

 

=÷

=÷   

 

 

 =÷

Logistic Regression

 

=÷ Feature Vector

 

=÷ Feature Vector


Figure 1: Illustration of feature extraction. The first row corresponds to a positive example from POS, while the second row corresponds to a negative one from NEG.

 

The code above puts the 128x64 gradientfield in the object g, and also saves the plot in a new image file test.eps. )

(b) Now, apply the above procedure to obtain feature vectors for each image in the dataset. Concatenate the feature vectors together into the rows of a dataframe. Add an additional column indicating whether each row is in POS or NEG. This will be the dataset you usefor Part II.

(Hint: Use the dir()function to get the names of all the les in a directory. Thefunctions rbind() and cbind() combine vectors together row-wise and column-wise, respectively.)

Part II:

We will apply Logistic regression to train the model and investigate its performance. Download the package glmnet. Use the function glmnet to train the model and plot out the regularization path.  In addition, use the function cv.glmnet to do the cross validation with the option type.measure="class". Plot the cross validation errors versus the tuning parameter A.

Question 2 (Sentiment Analysis on Amazon Product Reviews (30 points)). Sentiment analysis (also known as opinion mining) refers to the use of natural language processing, text analysis and computational linguistics to identify and extract subjective information in source materials. Sentiment analysis is widely applied to reviews and social media for a variety of applications, ranging from marketing to customer service. In this homework, we’ll explore product reviews and ratingsfrom Amazon and build a sentiment analysis classifier based on regularized logistic regression.

(a) First, load in the data Amazon SML.RData. Answer thefollowing basic questions. What are the column names? How many reviews are there? How many unique products are shown? Which product has the most ‘5’ ratings (and how many 5 ratings are there for this product)? Which product has the most ‘1’ ratings (and how many 1 ratings are therefor this product)? We suggest to use the dlplyfunction in the plyr R packagefor this.

(b) How many reviews of each rating value are there in the entire dataset? Our goal is to build a classifier that reads the review and classifies whether the review was ”good” (rating = 5) or ”bad” (rating = 1). What is the best performance of a ”constant classifier”, a classifier that ignores the review and blindly assigns a constant classification?

Now let’s build the term-document matrix dtm.mat using the script tdMat.R. This will help build a matrix where each row represents one document and each column represents a different word.  Element (i,j) of the matrix then represents how many times wordj appeared in document i (the ith review).

(c) Now we’ll run regularized logistic regression on our dataset. We’re going to split the dtm.mat into two parts: the training set and testing set using the script splitData.R. Fit a regularized logistic regression model by glmnet. The regularization parameter should be chosen as the lambda.1se (1 standard error above the minimizing lambda) calculated by cv.glmnet. Please use the random seed and lambda sequence as specified here so that we can check your results.

set.seed(10)

lambda<-exp(seq(-20,  -1,  length.out  =  99))

cvfit<-cv.glmnet(x,y,family="binomial",type.measure="class",lambda=lambda)

How many covariates have non-zero coefficients in the model selected by lambda.1se? List the twenty words with the most positive coefficients and twenty words with most negative coefficients.

(d) We would like to investigate some of the words that our model selected. We will focus on the words with the most positive and most negative weights that appeared in more than 10 documents. What are these two words? How many documents using either of these two words had a rating of 1 or 5? Print out the first document (according to train.tag) that used this most positive word and the first document that used this most negative word.

(e) Now run the fitted logisitic model on our testing data and report the misclassification rate. How does this compare with the “constant classifier” we originally discussed before (i.e., is it better or worse)?

Question 3 (Poisson Regression (15 points)).  In logistic regression, the conditional distribution of a binary output X is Bernoulli:

X IX ~ Bernoulli(9(X)),

where the Bernoulli parameter is related to βX by the logit transformation:

logit(9(X)) = log /βX .

Now consider the case where the output X is a ”count” that can take any non-negative integer value 0, 1, 2, ... (for example, the number of daily hits on a web server).  Then the standard model for X is the Poisson. Recall that the probability massfunction of the Poisson distribution with parameter A > 0 is

P (X = kIA) = e −λ .

In Poisson regression the conditional distribution of X given X is

X IX ~ Poisson(A(X)),

where log A(X) = βX.

(a) For data {(x1 , y1 ), (x2 , y2 ), ..., (xn , yn )} where xi  e 皿p and yi  e N = {0, 1, 2, ...}, write down the (conditional) log-likelihoodfunction y(βunder the above Poisson regression model.

(b) For logistic regression and Poisson regression, show that at the MLE 

n                       n

yixi  =       E[X IX = xi]xi .

i=1                   i=1

 

Question 4 (Non-existence of MLE for Logistic Regression (10 points)).  We have data points {(z1 , y1 ), ..., (zn , yn )} with yi  e {0, 1}from a pair of random variables (Ⅹ, X). We assume the datafollows a logistic regression model

X I Ⅹ = z ~ Bernoulli(n(z)),

eβx     

n(z) =

Here, both 8 and Ⅹ are scalars.

(a) Write down the log-likelihoodfunctionfor 8.

(0.1) (0.2)

(b) Suppose the data turn out to be as follows.  For every zi   < 0 we have yi   =  0.  For every zi   > 0 we have yi  = 1. Show that the maximum likelihood estimator  = o. [This question shows you a strange behavior of logistic regression. When the data are perfectly separable, the MLE does not exist.]

 

 

Question 5 (Identifying Risk Factors for the Heart Disease (15 points)). The riskfactorsfor the cardiovascular disease had not been well understood until the late 1940s. When President Franklin Delano Roosevelt died on April 12, 1945, his blood pressure was 300/190 and his physician said it wasjust normalfor a man of his age. The Framingham Heart Study, which began in 1948, is the first long-term studyfor cardiovascular disease designed to identify the riskfactors for the heart disease. You can find a detailed description of the dataset framingham.csv on the website

https://biolincc.nhlbi.nih.gov/static/studies/teaching/framdoc.pdf

In this problem, we want to nd out the riskfactors that cause coronary heart disease (TenYearCHD). CHD is a disease of the blood vessels supplying the heart. This is one type of heart disease, which has been the leading cause of death worldwide since 1921. In 2008, 7.3 million people diedfrom CHD.

The dataset framingham.csv includes several demographic risk factors:  the sex of the patient, the age of the patient in years, the education level coded as either 1 for some high school, 2 for a high school diploma or GED, 3 for some college or vocational school, and 4 for a college degree. The dataset also recorded behavioral risk factors associated with smoking: whether or not the patient was a smoker and the number of cigarettes that the person smoked on average in one day. Medical history risk factors were also included.  These were whether or not the patient was on blood pressure medication, whether or not the patient had previously had a stroke, whether or not the patient was hypertensive, and whether or not the patient had diabetes. Lastly, the data set had risk factors from the first physical examination of the patient: the total cholesterol level, systolic blood pressure, diastolic blood pressure, Body Mass Index, or BMI, heart rate and glucose.

Part I. Statistical Inference. (5 points)    Load the dataset into R and run logistic regression using thefunction glm. Use the summary command to find out the p-valuefor all the variables and report the statistically significant ones (the ones with p-value smaller than 0.05).

Part II. Prediction Analysis.  (5 points)    Randomly and evenly split the entire dataset into five subsets using the function sample. Usefour subsets as the training data and the other subset as the testing data. Report the prediction error of logistic regression. Please use set.seed(100) before splitting the data so that your answers should be the same always.

(Hint: sample can be used to obtain a random permutation of the data)

Part III. Regularized or Not (5 points)     Use glmnet to apply logistic regression with LASSO penalty on the data and plot cross validation errors against tuning parameters with nfolds =  5 and type.measure="class". What is the shape of the curve? More specifically, is it a typical U-curve that first goes down and then goes up? Do

you think we need to use regularization here?

(Hint: Drop the sample if it has NA values)

 

Appendix

A. Useful Functions in Q1

1.  rgb2gray(X) transforms colored pictures to their black and white versions. X is a three dimensional array, where the first two dimensions index the position of the pixel and the last dimension denotes the four channels (R, G, B and A). Search the key word ”RGBA” if you are interested in image data representation. The output will be a grayscale matrix that corresponds to the black and white version of the original picture.

2.  crop.r(X,  h,  w) randomly crops a sub-picture that has height h and width w from X. The output is there- fore a sub-matrix of X with h rows and w columns.

3.  crop.c(X,  h,  w) crops a sub-picture that has height h and width w at the center of X. The output is therefore a sub-matrix of X with h rows and w columns. This function helps the hog(...) function. For, the cropping in your assignment, use crop.r().

4.  grad(X,  h,  w,  pic) yields the gradient field at the center part of the given grayscale matrix X. The center region it examines has height h and width w. It returns a list of two matrices xgrad and ygrad. The parameter pic is a boolean variable. If it is TRUE, the generated gradient filed will be plotted. Otherwise the plot will be omitted.

5.  hog(xgrad,  ygrad,  hn,  wn,  an) returns a feature vector in the length of hn *wn *an from the given gradient field.  (xgrad[i,j],  ygrad[i,j]) gives the grayscale gradient at the position  (i,j). hn and wn are the partition number on height and width respectively. an is the partition number on the angles (or the interval [0, 2m) equivalently).

 

B. Histogram of Oriented Gradient

Here we give a brief introduction of what hog(xgrad,  ygrad,  hn,  wn,  an) does. First of all, it uniformly    partitions the whole picture into hn *wn small parts with hn partitions on the height and wn partitions on the width. For    each small part, it counts the gradient direction whose angle falls in the intervals [0, 2m/an), [2m/an, 4m/an), ..., [2(an- 1)m/an, 2m) respectively. So hog can get an frequencies for each small picture. Applying the same procedure to all    the small parts, hog will have hn *wn *an frequencies that constitute the final feature vector for the given gradient    field.