You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让线性模型预测值与数据起点一致?附R语言实操示例

让线性回归模型预测值与x=0起点保持一致的方法

问题需求

修改现有线性回归模型,确保当x=0时,模型预测值pred_y等于实际观测值y,即预测曲线与原始数据曲线在起点处重合。

数据定义

df <- tibble(
  x = c(0:20, 0:20), 
  y = c(log(10:30 + 2), log(10:30 + 10)),
  init = c(rep(log(10 + 2), 21), rep(log(10 + 10), 21)),
  group = c(rep('A', 21), rep('B', 21))
)

原模型(无法满足起点要求)

lm_fit <- lm(y ~ log(x + 1) + init, data = df)

原拟合示例代码

newdata <- df %>%
  filter(group == 'A') %>%
  mutate(pred_y = predict(lm_fit, newdata = newdata, type = 'response')) %>%
  pivot_longer(c(y, pred_y), names_to = 'pred_type', values_to = 'value')

ggplot(newdata, aes(x, value, colour = pred_type)) +
  geom_point() +
  geom_line()

模型拟合效果对比图

解决方案

核心思路:利用x=0时y=init的特性,让模型在x=0时的预测值等于init,具体修改如下:

修改后的模型

# 拟合y与init的差值对log(x+1)的无截距回归
lm_fit <- lm(I(y - init) ~ log(x + 1) - 1, data = df)

修改后的拟合代码

newdata <- df %>%
  filter(group == 'A') %>%
  # 预测时将init加回,得到最终的pred_y
  mutate(pred_y = init + predict(lm_fit, newdata = newdata)) %>%
  pivot_longer(c(y, pred_y), names_to = 'pred_type', values_to = 'value')

ggplot(newdata, aes(x, value, colour = pred_type)) +
  geom_point() +
  geom_line()

原理说明

  • 当x=0时,log(x+1)=log(1)=0,无截距模型的预测值为0,因此pred_y = init + 0 = init,而原始数据中x=0时y=init,刚好满足起点一致的要求。
  • 对于x>0的情况,模型拟合y-init随log(x+1)的变化趋势,在保证整体拟合逻辑不变的同时实现了起点对齐。

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:10:42