kdb+ - kdbQ Matrix multplication (mmu) resulting in type error - Stack Overflow

admin2025-05-01  1

Here is my linear regression function:

linearReg:{[t; yCol; xCols]
// Convert input data to matrices
X: 9h$flip xCols; // Ensure xCols is a matrix with multiple columns
Y: 9h$enlist yCol; // Ensure Y is a column vector
appData: t;

// Add a column of ones to X for the intercept term
X1: X,'enlist each count[X]#1;

// Ensure X1 is a matrix
if[not all each count each X1; :`type`X1]

// Calculate the coefficients using the normal equation: (X'X)^-1 X'Y
XtX: X1 mmu X1;
XtY: X1 mmu Y;
coeffs: inv XtX mmu XtY;

// Extract the intercept and coefficients
intercept: first coeffs;
betas: 1 _ coeffs;

// Calculate R-squared
Yhat: X1 mmu coeffs;
ss_total: sum (Y - avg Y) * (Y - avg Y);
ss_res: sum (Y - Yhat) * (Y - Yhat);
r2: 1 - ss_res % ss_total;

// Make predictions
appData1: appData,'enlist 1;
predictions: appData1 mmu coeffs;

// Prepare the result dictionary
res:`R2`Intercept`Coeffs`predictions!();
res[`R2]: r2;
res[`Intercept]: intercept;
res[`Coeffs]: betas;
res[`predictions]: predictions;

res};

Where t is the table, yCol is the input for the dependent variable, xCols is the input for the independent variables.

I get my t using this piece of code: flip value flip select ", ssr[string x[1];";";","], " from TABLE

My yCol variable like this: flip value flip select ", (string x[0]), " from TABLE

And my xCols variable like this: flip value flip select ", ssr[string x[1];";";","], " from TABLE

However, when I plug it into my function, I get the following error:

linearReg[flip value flip select ", ssr[string x[1];";";","], " from TABLE; 
flip value flip select ", (string x[0]), " from TABLE; 
flip value flip select ", ssr[string x[1];";";","], " from TABLE]

'type
  [6]  
C:\...\runRegression.q:113: linearReg:
    // Calculate the coefficients using the normal equation: (X'X)^-1 X'Y
    XtX: X1 mmu X1;
            ^
    XtY: X1 mmu Y;

All of the input data types are 0h as they are matrices. Any help would be much appreciated.

转载请注明原文地址:http://anycun.com/QandA/1746096896a91622.html