做任務(wù)反傭金的網(wǎng)站怎樣才能上百度
B 樣條曲線擬合實(shí)例:能平滑化曲線
1. 實(shí)例1
為MASS包中mcycle數(shù)據(jù)集。它測(cè)試了一系列模擬的交通車事故中,頭部的加速度,以此來評(píng)估頭盔的性能。times為撞擊時(shí)間(ms),accel為加速度(g)。首先導(dǎo)入數(shù)據(jù),并繪制散點(diǎn)圖
(1) 關(guān)鍵函數(shù)
# bs() ====
# bs(x, df = NULL, knots = NULL, degree = 3, intercept = FALSE,
# Boundary.knots = range(x))
#參數(shù)解釋:
#x:自變量,這里為x
#df: 自由度(回歸函數(shù)中的參數(shù)個(gè)數(shù)),默認(rèn)為0,由于我們需要截距,
# 2.2 節(jié)中c中提到的公式減去1,因此自由度為4+3 = 7
#knots:節(jié)點(diǎn)的位置,這里為c(15,20,32,40)
#degree:q值,默認(rèn)為3
#其他的參數(shù)保持默認(rèn)即可
然后搭配lm 函數(shù),即可畫出樣條函數(shù)曲線
(2) 代碼
# Spline ====
x=mcycle$time
y=mcycle$accel
plot(x, y, type="p", pch=19, cex=0.5)library(splines)
#B = spline(y, n=3*length(y) )
#lines(B$x, B$y, lty=2, col="red")bspl <- lm(y~bs(x, df =7, #knots = c(15,20,32,40), degree=2))
lines(x, fitted(bspl),lwd = 2, col = 2)ref: https://blog.csdn.net/weixin_39642998/article/details/110705947
似乎不靠譜,需要自己指定錨點(diǎn)位置?去掉 knots 參數(shù)就好了。
請(qǐng)直接看2(2)
2. help 例子:更靠譜的方法
(1) 原例:不明顯
require(stats); require(graphics)
head(women)
bs(women$height, df = 5)
summary(fm1 <- lm(weight ~ bs(height, df = 5), data = women))## example of safe prediction
plot(women, xlab = "Height (in)", ylab = "Weight (lb)")
ht <- seq(57, 73, length.out = 200)
lines(ht, predict(fm1, data.frame(height = ht)))
(2) 重做例1,模仿(1)
library(MASS)
head(mcycle)
x=mcycle$times
y=mcycle$accel#plot(x, y, pch=19, cex=0.5)
library(splines)
bs(y, df = 5)
summary(fm1 <- lm(y ~ bs(x, df = 7, degree = 2), data = NULL))## example of safe prediction
plot(mcycle, xlab = "times", ylab = "accel", pch=19, cex=0.5)
x_2 <- seq(min(x), max(x), length.out = 200)
lines(x_2, predict(fm1, data.frame(x = x_2)), lwd=2, col="red")
目測(cè)效果很好!
參數(shù)解釋:
df=7,有大概7個(gè)控制點(diǎn),越多擬合越好;太多就會(huì)過擬合!
degree=3,次數(shù)。