Главная » Просмотр файлов » Regression models for data sciense

Regression models for data sciense (779323), страница 3

Файл №779323 Regression models for data sciense (Regression models for data sciense) 3 страницаRegression models for data sciense (779323) страница 32017-12-25СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 3)

~ variable)gPlotting the galton datasetFinding the middle via least squaresConsider only the children’s heights. How could one describe the “middle”? Consider one definition.Let Yi be the height of child i for i = 1, . . . , n = 928, then define the middle as the value of µ thatminimizesn∑(Yi − µ)2 .i=1This is physical center of mass of the histogram. You might have guessed that the answer µ = Ȳ .This is called the least squares estimate for µ.

It is the point that minimizes the sum of the squareddistances between the observed data and itself.Note, if there was no variation in the data, every value of Yi was the same, then there would be noerror around the mean. Otherwise, our estimate has to balance the fact that our estimate of µ isn’tgoing to predict every observation perfectly. Minimizing the average (or sum of the) squared errorsseems like a reasonable strategy, though of course there are others. We could minimize the averageIntroduction6absolute deviation between the data µ (this leads to the median as the estimate instead of the mean).However, minimizing the squared error has many nice properties, so we’ll stick with that for thisclass.ExperimentLet’s use rStudio’s manipulate to see what value of µ minimizes the sum of the squared deviations.The code below allows you to create a slider to investigate estimates and their mean squared error.Using manipulate to find the least squares estimate.library(manipulate)myHist <- function(mu){mse <- mean((galton$child - mu)^2)g <- ggplot(galton, aes(x = child)) + geom_histogram(fill = "salmon", colour\= "black", binwidth=1)g <- g + geom_vline(xintercept = mu, size = 3)g <- g + ggtitle(paste("mu = ", mu, ", MSE = ", round(mse, 2), sep = ""))g}manipulate(myHist(mu), mu = slider(62, 74, step = 0.5))The least squares estimate is the empirical mean.g <- ggplot(galton, aes(x = child)) + geom_histogram(fill = "salmon", colour = "\black", binwidth=1)g <- g + geom_vline(xintercept = mean(galton$child), size = 3)g7IntroductionThe best mean is the vertical line.The math (not required)Watch this video before beginning²¹Why is the sample average the least squares estimate for µ? It’s surprisingly easy to show.

Perhapsmore surprising is how generally these results can be extended.²¹https://www.youtube.com/watch?v=FV8D_fI5SRk&list=PLpl-gQkQivXjqHAJd2t-J_One_fYE55tC&index=38Introductionnn∑∑2(Yi − µ) =(Yi − Ȳ + Ȳ − µ)2i=1=i=1n∑(Yi − Ȳ ) + 22i=1=n∑n∑i=1(Yi − Ȳ )2 + 2(Ȳ − µ)i=1==n∑i=1n∑≥(Yi − Ȳ ) +(Yi − Ȳ )2 + 2(Ȳ − µ)(n∑(Ȳ − µ)2i=1n∑Yi − nȲ ) +i=1(Yi − Ȳ )2 +(Ȳ − µ)2i=1n∑i=1n∑i=1n∑(Yi − Ȳ )(Ȳ − µ) +n∑(Ȳ − µ)2i=1n∑(Ȳ − µ)2i=1(Yi − Ȳ )2i=1Comparing children’s heights and their parent’sheightsWatch this video before beginning²²Looking at either the parents or children on their own isn’t interesting. We’re interested in how therelate to each other.

Let’s plot the parent and child heights.ggplot(galton, aes(x = parent, y = child)) + geom_point()²²https://www.youtube.com/watch?v=b34mXkyCH0I&list=PLpl-gQkQivXjqHAJd2t-J_One_fYE55tC&index=49IntroductionPlot of parent and child heights.The overplotting is clearly hiding some data. Here you can get the code ²³ to make the size and colorof the points be the frequency.²³https://github.com/bcaffo/courses/blob/master/07_RegressionModels/01_01_introduction/index.Rmd10IntroductionRe plot of the dataRegression through the originA line requires two parameters to be specified, the intercept and the slope. Let’s first focus on theslope. We want to find the slope of the line that best fits the data.

However, we have to pick a goodintercept. Let’s subtract the mean from bot the parent and child heights so that their subsequentmeans are 0. Now let’s find the line that goes through the origin (has intercept 0) by picking the bestslope.Suppose that Xi are the parent heights with the mean subtracted.

Consider picking the slope β thatminimizesn∑(Yi − Xi β)2 .i=1Introduction11Each Xi β is the vertical height of a line through the origin at point Xi . Thus, Yi − Xi β is the verticaldistance between the line at each observed Xi point (parental height) and the Yi (child height).Our goal is exactly to use the origin as a pivot point and pick the line that minimizes the sum of thesquared vertical distances of the points to the line. Use R studio’s manipulate function to experimentSubtract the means so that the origin is the mean of the parent and children heights.Code for plotting the data.y <- galton$child - mean(galton$child)x <- galton$parent - mean(galton$parent)freqData <- as.data.frame(table(x, y))names(freqData) <- c("child", "parent", "freq")freqData$child <- as.numeric(as.character(freqData$child))freqData$parent <- as.numeric(as.character(freqData$parent))myPlot <- function(beta){g <- ggplot(filter(freqData, freq > 0), aes(x = parent, y = child))g <- g + scale_size(range = c(2, 20), guide = "none" )g <- g + geom_point(colour="grey50", aes(size = freq+20, show_guide = FALSE))g <- g + geom_point(aes(colour=freq, size = freq))g <- g + scale_colour_gradient(low = "lightblue", high="white")g <- g + geom_abline(intercept = 0, slope = beta, size = 3)mse <- mean( (y - beta * x) ^2 )g <- g + ggtitle(paste("beta = ", beta, "mse = ", round(mse, 3)))g}manipulate(myPlot(beta), beta = slider(0.6, 1.2, step = 0.02))The solutionIn the next few lectures we’ll talk about why this is the solution.

But, rather than leave you hanging,here it is:> lm(I(child - mean(child))~ I(parent - mean(parent)) - 1, data = galton)Call:lm(formula = I(child - mean(child)) ~ I(parent - mean(parent)) 1, data = galton)Coefficients:I(parent - mean(parent))0.64612IntroductionLet’s plot the best fitting line. In the subsequent chapter we will learn all about creating, interpretingand performing inference on such mode fits. (Note that I shifted the origin back to the means of theoriginal data.) The results suggest that to every every 1 inch increase in the parents height, weestimate a 0.646 inch increase in the child’s height.Data with the best fitting line.Exercises1.

Consider the dataset given by x=c(0.725,0.429,-0.372 ,0.863). What value of mu minimizessum((x - mu)ˆ2)? Watch a video solution.²⁴2. Reconsider the previous question. Suppose that weights were given, w = c(2, 2, 1, 1) sothat we wanted to minimize sum(w * (x - mu) ˆ 2) for mu. What value would we obtain?Watch a video solution.²⁵²⁴https://www.youtube.com/watch?v=Uhxm58rylec&list=PLpl-gQkQivXji7JK1OP1qS7zalwUBPrX0&index=1²⁵https://www.youtube.com/watch?v=DS-Wl2dRxCA&list=PLpl-gQkQivXji7JK1OP1qS7zalwUBPrX0&index=2Introduction133. Take the Galton and obtain the regression through the origin slope estimate where the centeredparental height is the outcome and the child’s height is the predictor.

Watch a video solution.²⁶²⁶https://www.youtube.com/watch?v=IGVRkmrOrww&list=PLpl-gQkQivXji7JK1OP1qS7zalwUBPrX0&index=3NotationWatch this video before beginning²⁷Some basic definitionsIn this chapter, we’ll cover some basic definitions and notation used throughout the book. We willtry to minimize the amount of mathematics required so that we can focus on the concepts.Notation for dataWe write X1 , X2 , . . . , Xn to describe n data points. As an example, consider the data set {1, 2, 5}then X1 = 1, X2 = 2, X3 = 5 and n = 3.Of course, there’s nothing in particular about the varianble X. We often use a different letter, suchas Y1 , .

. . , Yn to describe a data set. We will typically use Greek letters for things we don’t know.Such as, µ being a population mean that we’d like to estimate.The empirical meanThe empirical mean is a measure of center of our data. Under sampling assumptions, it estimates apopulation mean of interest. Define the empirical mean as1∑X̄ =Xi .n i=1nNotice if we subtract the mean from data points, we get data that has mean 0. That is, if we defineX̃i = Xi − X̄.then the mean of the X̃i is 0. This process is called centering the random variables. Recall from theprevious lecture that the empirical mean is the least squares solution for minimizingn∑(Xi − µ)2i=1²⁷https://www.youtube.com/watch?v=T5UXxVKD0sA&index=5&list=PLpl-gQkQivXjqHAJd2t-J_One_fYE55tC15NotationThe emprical standard deviation and varianceThe variance and standard deviation are measures of how spread out are data is.

Under samplingassumptions, they estimate variability in the population. We define the empirical variance asL1 ∑1S2 =(Xi − X̄)2 =n − 1 i=1n−1nThe empirical standard deviation is defined as S =( n∑)Xi2 − nX̄ 2i=1√S 2.Notice that the standard deviation has the same units as the data. The data defined by Xi /s haveempirical standard deviation 1.

This is called scaling the data.NormalizationWe can combine centering and scaling of data as follows to get normalized data. In particular, thedata defined by:Zi =Xi − X̄shave empirical mean zero and empirical standard deviation 1. The process of centering then scalingthe data is called normalizing the data. Normalized data are centered at 0 and have units equal tostandard deviations of the original data.

Характеристики

Тип файла
PDF-файл
Размер
3,77 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6508
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее