
R語言與函數估計學習筆記(核方法與局部多項式)
非參數方法
用于函數估計的非參數方法大致上有三種:核方法、局部多項式方法、樣條方法。
非參的函數估計的優點在于穩健,對模型沒有什么特定的假設,只是認為函數光滑,避免了模型選擇帶來的風險;但是,表達式復雜,難以解釋,計算量大是非參的一個很大的毛病。所以說使用非參有風險,選擇需謹慎。
非參的想法很簡單:函數在觀測到的點取觀測值的概率較大,用x附近的值通過加權平均的辦法估計函數f(x)的值。
核方法
當加權的權重是某一函數的核(關于“核”的說法可參見之前的博文《R語言與非參數統計(核密度估計)》),這種方法就是核方法,常見的有Nadaraya-Watson核估計與Gasser-Muller核估計方法,也就是很多教材里談到的NW核估計與GM核估計,這里我們還是不談核的選擇,將一切的核估計都默認用Gauss核處理。
NW核估計形式為:
GM核估計形式為:
式中
x <- seq(-1, 1, length = 20)
y <- 5 * x * cos(5 * pi * x)
h <- 0.088
fx.hat <- function(z, h) {
dnorm((z - x)/h)/h
}
KSMOOTH <- function(h, y, x) {
n <- length(y)
s.hat <- rep(0, n)
for (i in 1:n) {
a <- fx.hat(x[i], h)
s.hat[i] <- sum(y * a/sum(a))
}
return(s.hat)
}
ksmooth.val <- KSMOOTH(h, y, x)
plot(x, y, xlab = "Predictor", ylab = "Response")
f <- function(x) 5 * x * cos(5 * pi * x)
curve(f, -1, 1, ylim = c(-15.5, 15.5), lty = 2, add = T)
lines(x, ksmooth.val, type = "l")
可以看出,核方法基本估計出了函數的形狀,但是效果不太好,這個是由于樣本點過少導致的,我們可以將樣本容量擴大一倍,看看效果:
x <- seq(-1, 1, length = 40)
y <- 5 * x * cos(5 * pi * x)
h <- 0.055
fx.hat <- function(z, h) {
dnorm((z - x)/h)/h
}
NWSMOOTH <- function(h, y, x) {
n <- length(y)
s.hat <- rep(0, n)
for (i in 1:n) {
a <- fx.hat(x[i], h)
s.hat[i] <- sum(y * a/sum(a))
}
return(s.hat)
}
NWsmooth.val <- NWSMOOTH(h, y, x)
plot(x, y, xlab = "Predictor", ylab = "Response", col = 1)
f <- function(x) 5 * x * cos(5 * pi * x)
curve(f, -1, 1, ylim = c(-15.5, 15.5), lty = 1, add = T, col = 1)
lines(x, NWsmooth.val, lty = 2, col = 2)
A <- data.frame(x = seq(-1, 1, length = 1000))
model.linear <- lm(y ~ poly(x, 9))
lines(seq(-1, 1, length = 1000), predict(model.linear, A), lty = 3, col = 3)
letters <- c("NW method", "orignal model", "9 order poly-reg")
legend("bottomright", legend = letters, lty = c(2, 1, 3), col = c(2, 1, 3),
cex = 0.5)
可以看到估計效果還是很好的,至少比基函數的辦法要好一些。那么我們來看看GM核方法:
x <- seq(-1, 1, length = 40)
y <- 5 * x * cos(5 * pi * x)
h <- 0.055
GMSMOOTH <- function(y, x, h) {
n <- length(y)
s <- c(-Inf, 0.5 * (x[-n] + x[-1]), Inf)
s.hat <- rep(0, n)
for (i in 1:n) {
fx.hat <- function(z, h, x) {
dnorm((x - z)/h)/h
}
a <- y[i] * integrate(fx.hat, s[i], s[i + 1], h = h, x = x[i])$value
s.hat[i] <- sum(a)
}
return(s.hat)
}
GMsmooth.val <- GMSMOOTH(y, x, h)
plot(x, y, xlab = "Predictor", ylab = "Response", col = 1)
f <- function(x) 5 * x * cos(5 * pi * x)
curve(f, -1, 1, ylim = c(-15.5, 15.5), lty = 1, add = T, col = 1)
lines(x, GMsmooth.val, lty = 2, col = 2)
A <- data.frame(x = seq(-1, 1, length = 1000))
model.linear <- lm(y ~ poly(x, 9))
lines(seq(-1, 1, length = 1000), predict(model.linear, A), lty = 3, col = 3)
letters <- c("GM method", "orignal model", "9 order poly-reg")
legend("bottomright", legend = letters, lty = c(2, 1, 3), col = c(2, 1, 3),
cex = 0.5)
我們來看看兩個核估計辦法的差異:
x <- seq(-1, 1, length = 40)
y <- 5 * x * cos(5 * pi * x)
h <- 0.055
fx.hat <- function(z, h) {
dnorm((z - x)/h)/h
}
NWSMOOTH <- function(h, y, x) {
n <- length(y)
s.hat <- rep(0, n)
for (i in 1:n) {
a <- fx.hat(x[i], h)
s.hat[i] <- sum(y * a/sum(a))
}
return(s.hat)
}
NWsmooth.val <- NWSMOOTH(h, y, x)
GMSMOOTH <- function(y, x, h) {
n <- length(y)
s <- c(-Inf, 0.5 * (x[-n] + x[-1]), Inf)
s.hat <- rep(0, n)
for (i in 1:n) {
fx.hat <- function(z, h, x) {
dnorm((x - z)/h)/h
}
a <- y[i] * integrate(fx.hat, s[i], s[i + 1], h = h, x = x[i])$value
s.hat[i] <- sum(a)
}
return(s.hat)
}
GMsmooth.val <- GMSMOOTH(y, x, h)
plot(x, y, xlab = "Predictor", ylab = "Response", col = 1)
f <- function(x) 5 * x * cos(5 * pi * x)
curve(f, -1, 1, ylim = c(-15.5, 15.5), lty = 1, add = T, col = 1)
lines(x, NWsmooth.val, lty = 2, col = 2)
lines(x, GMsmooth.val, lty = 3, col = 3)
letters <- c("orignal model", "NW method", "GM method")
legend("bottomright", legend = letters, lty = 1:3, col = 1:3, cex = 0.5)
從圖中可以看到NW估計的方差似乎小些,事實也確實如此,GM估計的漸進方差約為NW估計的1.5倍。但是GM估計解決了一些計算的難題。
我們最后還是來展示不同窗寬的選擇對估計的影響(這里以NW估計為例):
x <- seq(-1, 1, length = 40)
y <- 5 * x * cos(5 * pi * x)
fx.hat <- function(z, h) {
dnorm((z - x)/h)/h
}
NWSMOOTH <- function(h, y, x) {
n <- length(y)
s.hat <- rep(0, n)
for (i in 1:n) {
a <- fx.hat(x[i], h)
s.hat[i] <- sum(y * a/sum(a))
}
return(s.hat)
}
h <- 0.025
NWsmooth.val0 <- NWSMOOTH(h, y, x)
h <- 0.05
NWsmooth.val1 <- NWSMOOTH(h, y, x)
h <- 0.1
NWsmooth.val2 <- NWSMOOTH(h, y, x)
h <- 0.2
NWsmooth.val3 <- NWSMOOTH(h, y, x)
h <- 0.3
NWsmooth.val4 <- NWSMOOTH(h, y, x)
plot(x, y, xlab = "Predictor", ylab = "Response", col = 1)
f <- function(x) 5 * x * cos(5 * pi * x)
curve(f, -1, 1, ylim = c(-15.5, 15.5), lty = 1, add = T, col = 1)
lines(x, NWsmooth.val0, lty = 2, col = 2)
lines(x, NWsmooth.val1, lty = 3, col = 3)
lines(x, NWsmooth.val2, lty = 4, col = 4)
lines(x, NWsmooth.val3, lty = 5, col = 5)
lines(x, NWsmooth.val4, lty = 6, col = 6)
letters <- c("orignal model", "h=0.025", "h=0.05", "h=0.1", "h=0.2", "h=0.3")
legend("bottom", legend = letters, lty = 1:6, col = 1:6, cex = 0.5)
可以看到窗寬越大,估計越光滑,誤差越大,窗寬越小,估計越不光滑,但擬合優度有提高,卻也容易過擬合。
窗寬怎么選,一個可行的辦法就是CV,通俗的講就是取一個觀測做測試集,剩下的做訓練集,看NMSE。R代碼如下:
x <- seq(-1, 1, length = 40)
y <- 5 * x * cos(5 * pi * x)
# h<-0.055
NWSMOOTH <- function(h, y, x, z) {
n <- length(y)
s.hat <- rep(0, n)
s.hat1 <- rep(0, n)
for (i in 1:n) {
s.hat[i] <- dnorm((x[i] - z)/h)/h * y[i]
s.hat1[i] <- dnorm((x[i] - z)/h)/h
}
z.hat <- sum(s.hat)/sum(s.hat1)
return(z.hat)
}
CVRSS <- function(h, y, x) {
cv <- NULL
for (i in seq(x)) {
cv[i] <- (y[i] - NWSMOOTH(h, y[-i], x[-i], x[i]))^2
}
mean(cv)
}
h <- seq(0.01, 0.2, by = 0.005)
cvrss.val <- rep(0, length(h))
for (i in seq(h)) {
cvrss.val[i] <- CVRSS(h[i], y, x)
}
plot(h, cvrss.val, type = "b")
從圖中我們可以見到CV值在0.01到0.05的變化都不大,這時,我們應該選擇較大的h,使得函數較為光滑,但是0.05后,cv變化較大,說明我們選擇窗寬也不能過大,否則也會出毛病的。那么是不是h越小越好呢?雖然上面一個例子給了我們這樣一個錯覺,我們下面這個例子就可以打破它,數據來自《computational statistics》一書的essay data一例。
easy <- read.table("D:/R/data/easysmooth.dat", header = T)
x <- easy$X
y <- easy$Y
NWSMOOTH <- function(h, y, x, z) {
n <- length(y)
s.hat <- rep(0, n)
s.hat1 <- rep(0, n)
for (i in 1:n) {
s.hat[i] <- dnorm((x[i] - z)/h)/h * y[i]
s.hat1[i] <- dnorm((x[i] - z)/h)/h
}
z.hat <- sum(s.hat)/sum(s.hat1)
return(z.hat)
}
CVRSS <- function(h, y, x) {
cv <- NULL
for (i in seq(x)) {
cv[i] <- (y[i] - NWSMOOTH(h, y[-i], x[-i], x[i]))^2
}
mean(cv)
}
h <- seq(0.01, 0.3, by = 0.02)
cvrss.val <- rep(0, length(h))
for (i in seq(h)) {
cvrss.val[i] <- CVRSS(h[i], y, x)
}
plot(h, cvrss.val, type = "b")
從上圖就可以看到,最佳窗寬約為0.15,而不是0.01.
和樹回歸類似,我們的核方法就是提供了一個常數來漸進這個函數,我們這里仍然可以考慮模型樹的想法,用一階或者高階多項式來作加權估計,這就有了局部多項式估計。
局部多項式
估計的想法是認為未知函數f(x)在近鄰鄰域內可由某一多項式近似(這是Taylor公式的結果),在x0的鄰域內最小化:
具體做法為:
(1)對于每個xi,以該點為中心,計算出對應點處的權重Kh(xi?x);
(2)采用加權最小二乘法(WLS)估計其參數,并用得到的模型估計該結點對應的x值對應y值,作為y|xi的估計值(只要這一個點的估計值);
(3)估計下一個點xj;
(4)將每個y|xi的估計值連接起來。
我們這里以《computational statistics》一書的essay data為例來說明局部多項式估計
easy <- read.table("D:/R/data/easysmooth.dat", header = T)
x <- easy$X
y <- easy$Y
h <- 0.16
## FUNCTIONS USES HAT MATRIX
LPRSMOOTH <- function(y, x, h) {
n <- length(y)
s.hat <- rep(0, n)
for (i in 1:n) {
weight <- dnorm((x - x[i])/h)
mod <- lm(y ~ x, weights = weight)
s.hat[i] <- as.numeric(predict(mod, data.frame(x = x[i])))
}
return(s.hat)
}
lprsmooth.val <- LPRSMOOTH(y, x, h)
s <- function(x) {
(x^3) * sin((x + 3.4)/2)
}
x.plot <- seq(min(x), max(x), length.out = 1000)
y.plot <- s(x.plot)
plot(x, y, xlab = "Predictor", ylab = "Response")
lines(x.plot, y.plot, lty = 1, col = 1)
lines(x, lprsmooth.val, lty = 2, col = 2)
我們回到最開始我們提到的三角函數的例子,我們可以看到:
x <- seq(-1, 1, length = 40)
y <- 5 * x * cos(5 * pi * x)
## FUNCTIONS
LPRSMOOTH <- function(y, x, h) {
n <- length(y)
s.hat <- rep(0, n)
for (i in 1:n) {
weight <- dnorm((x - x[i])/h)
mod <- lm(y ~ x, weights = weight)
s.hat[i] <- as.numeric(predict(mod, data.frame(x = x[i])))
}
return(s.hat)
}
h <- 0.15
lprsmooth.val1 <- LPRSMOOTH(y, x, h)
h <- 0.066
lprsmooth.val2 <- LPRSMOOTH(y, x, h)
plot(x, y, xlab = "Predictor", ylab = "Response")
f <- function(x) 5 * x * cos(5 * pi * x)
curve(f, -1, 1, ylim = c(-15.5, 15.5), lty = 1, add = T, col = 1)
lines(x, lprsmooth.val1, lty = 2, col = 2)
lines(x, lprsmooth.val2, lty = 3, col = 3)
letters <- c("orignal model", "h=0.15", "h=0.66")
legend("bottom", legend = letters, lty = 1:3, col = 1:3, cex = 0.5
R中提供了很多的函數包來做非參數回歸,常用的有:KernSmooth包的函數locpoly(),locpol的locpol(),locCteSmootherC()以及locfit的locfit().具體的參數設置較為簡單,這里就不多說了。我們以開篇的三角函數模型的例子為例來看看如何使用它們:
library(KernSmooth) #函數locpoly()
library(locpol) #locpol(); locCteSmootherC()
library(locfit) #locfit()
x <- seq(-1, 1, length = 40)
y <- 5 * x * cos(5 * pi * x)
f <- function(x) 5 * x * cos(5 * pi * x)
curve(f, -1, 1)
points(x, y)
fit <- locpoly(x, y, bandwidth = 0.066)
lines(fit, lty = 2, col = 2)
d <- data.frame(x = x, y = y)
r <- locfit(y ~ x, d) #一般來說,locfit函數自動選的窗寬偏大,函數較光滑
lines(r, lty = 3, col = 3)
xeval <- seq(-1, 1, length = 10)
cuest <- locCuadSmootherC(d$x, d$y, xeval, 0.066, gaussK)
cuest
## x beta0 beta1 beta2 den
## 1 -1.0000 5.0858 -35.152 -222.58 0.07571
## 2 -0.7778 -3.3233 11.966 514.42 4.22454
## 3 -0.5556 1.9804 -16.219 -279.47 4.26349
## 4 -0.3333 -0.8416 13.137 83.37 4.26349
## 5 -0.1111 0.1924 -4.983 27.90 4.26349
## 6 0.1111 -0.1924 -4.983 -27.90 4.26349
## 7 0.3333 0.8416 13.137 -83.37 4.26349
## 8 0.5556 -1.9804 -16.219 279.47 4.26349
## 9 0.7778 3.3233 11.966 -514.42 4.22454
## 10 1.0000 -5.0858 -35.152 222.58 0.07571
關于局部多項式估計的想法還有很多,比如我們只考慮近鄰的數據作最小二乘估計,再比如我們可以修改權重,使得我們的窗寬與近鄰點的距離有關,再比如,我們可以考慮不采用最小二乘做優化,而是對最小二乘加上一點點的懲罰……我們將第一個想法稱之為running line,第二個想法稱之為loess,第三個想法依據你的懲罰方式不同有不同的說法。我們將running line的R程序給出如下:
RLSMOOTH <- function(k, y, x) {
n <- length(y)
s.hat <- rep(0, n)
b <- (k - 1)/2
if (k > 1) {
for (i in 1:(b + 1)) {
xi <- x[1:(b + i)]
xi <- cbind(rep(1, length(xi)), xi)
hi <- xi %*% solve(t(xi) %*% xi) %*% t(xi)
s.hat[i] <- y[1:(b + i)] %*% hi[i, ]
xi <- x[(n - b - i + 1):n]
xi <- cbind(rep(1, length(xi)), xi)
hi <- xi %*% solve(t(xi) %*% xi) %*% t(xi)
s.hat[n - i + 1] <- y[(n - b - i + 1):n] %*% hi[nrow(hi) - i + 1,
]
}
for (i in (b + 2):(n - b - 1)) {
xi <- x[(i - b):(i + b)]
xi <- cbind(rep(1, length(xi)), xi)
hi <- xi %*% solve(t(xi) %*% xi) %*% t(xi)
s.hat[i] <- y[(i - b):(i + b)] %*% hi[b + 1, ]
}
}
if (k == 1) {
s.hat <- y
}
return(s.hat)
}
我們也一樣可以對running line做局部多項式回歸,代碼如下:
WRLSMOOTH <- function(k, y, x, h) {
n <- length(y)
s.hat <- rep(0, n)
b <- (k - 1)/2
if (k > 1) {
for (i in 1:(b + 1)) {
xi <- x[1:(b + i)]
xi <- cbind(rep(1, length(xi)), xi)
hi <- xi %*% solve(t(xi) %*% xi) %*% t(xi)
s.hat[i] <- y[1:(b + i)] %*% hi[i, ]
xi <- x[(n - b - i + 1):n]
xi <- cbind(rep(1, length(xi)), xi)
hi <- xi %*% solve(t(xi) %*% xi) %*% t(xi)
s.hat[n - i + 1] <- y[(n - b - i + 1):n] %*% hi[nrow(hi) - i + 1,
]
}
for (i in (b + 2):(n - b - 1)) {
xi <- x[(i - b):(i + b)]
weight <- dnorm((xi - x[i])/h)
mod <- lm(y[(i - b):(i + b)] ~ xi, weights = weight)
s.hat[i] <- as.numeric(predict(mod, data.frame(xi = x[i])))
}
}
if (k == 1) {
s.hat <- y
}
return(s.hat)
}
R中也提供了函數lowess()來做loess回歸。我們這里不妨以essay data為例,看看這三個估計有多大的差別:
數據分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
CDA數據分析師證書考試體系(更新于2025年05月22日)
2025-05-26解碼數據基因:從數字敏感度到邏輯思維 每當看到超市貨架上商品的排列變化,你是否會聯想到背后的銷售數據波動?三年前在零售行 ...
2025-05-23在本文中,我們將探討 AI 為何能夠加速數據分析、如何在每個步驟中實現數據分析自動化以及使用哪些工具。 數據分析中的AI是什么 ...
2025-05-20當數據遇見人生:我的第一個分析項目 記得三年前接手第一個數據分析項目時,我面對Excel里密密麻麻的銷售數據手足無措。那些跳動 ...
2025-05-20在數字化運營的時代,企業每天都在產生海量數據:用戶點擊行為、商品銷售記錄、廣告投放反饋…… 這些數據就像散落的拼圖,而相 ...
2025-05-19在當今數字化營銷時代,小紅書作為國內領先的社交電商平臺,其銷售數據蘊含著巨大的商業價值。通過對小紅書銷售數據的深入分析, ...
2025-05-16Excel作為最常用的數據分析工具,有沒有什么工具可以幫助我們快速地使用excel表格,只要輕松幾步甚至輸入幾項指令就能搞定呢? ...
2025-05-15數據,如同無形的燃料,驅動著現代社會的運轉。從全球互聯網用戶每天產生的2.5億TB數據,到制造業的傳感器、金融交易 ...
2025-05-15大數據是什么_數據分析師培訓 其實,現在的大數據指的并不僅僅是海量數據,更準確而言是對大數據分析的方法。傳統的數 ...
2025-05-14CDA持證人簡介: 萬木,CDA L1持證人,某電商中廠BI工程師 ,5年數據經驗1年BI內訓師,高級數據分析師,擁有豐富的行業經驗。 ...
2025-05-13CDA持證人簡介: 王明月 ,CDA 數據分析師二級持證人,2年數據產品工作經驗,管理學博士在讀。 學習入口:https://edu.cda.cn/g ...
2025-05-12CDA持證人簡介: 楊貞璽 ,CDA一級持證人,鄭州大學情報學碩士研究生,某上市公司數據分析師。 學習入口:https://edu.cda.cn/g ...
2025-05-09CDA持證人簡介 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度、美團、阿里等 ...
2025-05-07相信很多做數據分析的小伙伴,都接到過一些高階的數據分析需求,實現的過程需要用到一些數據獲取,數據清洗轉換,建模方法等,這 ...
2025-05-06以下的文章內容來源于劉靜老師的專欄,如果您想閱讀專欄《10大業務分析模型突破業務瓶頸》,點擊下方鏈接 https://edu.cda.cn/g ...
2025-04-30CDA持證人簡介: 邱立峰 CDA 數據分析師二級持證人,數字化轉型專家,數據治理專家,高級數據分析師,擁有豐富的行業經驗。 ...
2025-04-29CDA持證人簡介: 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度,美團,阿里等 ...
2025-04-28CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-27數據分析在當今信息時代發揮著重要作用。單因素方差分析(One-Way ANOVA)是一種關鍵的統計方法,用于比較三個或更多獨立樣本組 ...
2025-04-25CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-25