【问题标题】:Linear regression in kdbkdb 中的线性回归
【发布时间】:2016-10-31 19:47:19
【问题描述】:

这是我构建线性回归的方式,但是当我包含两列以上时,我的代码不起作用。

// Load relevant columns into memory
//
t:?[`data;enlist(=;`date;dat);0b;(ind,dep)!ind,dep];


X:9h$enlist[count[t]#1],t ind;
beta:inv[X mmu flip X] mmu X mmu 9h$t dep;

res:(`yInt,ind)!beta;

ind 是符号中的独立字段名称,dep 是符号中的依赖字段名称。这部分inv[X mmu flip X] 不起作用。如果我包含两个以上的 ind 字段并且我不能执行 inv,则会有一行空白。我不太确定如何为自变量包含更多列/字段。

【问题讨论】:

    标签: regression kdb


    【解决方案1】:

    稍作修改后,您的代码对我有用:

      / Generate some random data
      n:10;t:([]x1:n?1f;x2:n?1f;x3:n?1f)
      / Compute y = 1 + 2*x1 + 3*x2 + 4*x3 + small random noise 
      update y:1+(2*x1)+(3*x2)+(4*x3)+n?1e-3 from `t;
      / Define ind and dep
      ind:`x1`x2`x3
      dep:enlist`y
      / Build the design matrix
      X:enlist[count[t]#1f],t ind
      / Compute the regression parameters
      inv[X mmu flip X] mmu X mmu flip t dep
    1.00052
    1.99973
    2.999979
    4.000045
    

    唯一可能棘手的部分是记住登记和转置dep

    根据您的描述,您的数据似乎有问题。它要么包含 NaN,要么您的 ind 变量不是独立的。

    【讨论】:

      【解决方案2】:

      我发现了一个关于线性回归的 google 群组问题:
      https://groups.google.com/forum/#!topic/personal-kdbplus/CRf-kOx-v4I

      他们在这篇文章中提到了使用 lsq 命令:
      http://code.kx.com/q/ref/matrixes/#lsq

      另一个答案给出了示例代码,希望这些信息对您有所帮助。

      【讨论】:

      • 谢谢,但我也找到了这些答案。但如果是分类变量,你如何做线性回归?
      【解决方案3】:

      您能否提供您正在使用的数据的子集?一般来说, inv 失败对我来说意味着你的矩阵中有一些空值。这个问题可以通过在尝试找到矩阵的逆矩阵之前使用0f^ 来解决。 (用浮点零填充矩阵的空元素。)

      http://code.kx.com/q/ref/lists/#fill

      快速示例:

      inv 3 cut 1.1 2.2 3.1 4.5 0n 0n 1.2 7 8f 
      

      返回:

      (0n 0n 0n;0n 0n 0n;0n 0n 0n)
      

      然而……

      inv 0f^3 cut 1.1 2.2 3.1 4.5 0n 0n 1.2 7 8f
      

      返回:

      (0 0.2222222 -0;-1.9512195 0.2753388 0.7560976;1.7073171 -0.2742547 -0.5365854) 
      

      【讨论】:

      • 谢谢!您打算如何在分区表上执行此操作?
      • 您可以在执行选择后对各个列进行 0f^,或者您可以在列上使用 exec 来构建矩阵,获取字典的值,然后填充整个内容。
      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2012-10-28
      • 2018-07-31
      • 2019-10-09
      • 2017-06-17
      相关资源
      最近更新 更多