kdb/Q矩阵乘法(mmu)类型错误:线性回归函数执行报错
kdb/Q线性回归函数
linearReg'type错误排查 编写的linearReg函数
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};
输入获取方式
- t:
flip value flip select ", ssr[string x[1];"";"";""], " from TABLE - yCol:
flip value flip select ", (string x[0]), " from TABLE - xCols:
flip value flip select ", ssr[string x[1];"";"";""], " from TABLE
错误信息
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;
问题背景
所有输入数据类型均为0h(矩阵类型),但调用函数时触发'type错误,需排查原因。
排查分析
- 矩阵元素类型不匹配:输入虽为0h矩阵,但矩阵内元素是字符串类型(输入获取时用
ssr处理字符串,未转换为数值)。函数中9h$尝试将字符串转float会失败,得到空值0Nh,而矩阵乘法mmu要求输入为数值类型(如float、int),非数值元素直接触发'type错误。 - 输入获取逻辑缺陷:当前输入代码仅处理字符串格式,未将字符串转换为可用于计算的数值类型,导致传入函数的矩阵包含非数值元素。
- 函数内类型检查不完善:仅检查了X1的列长度一致性,未验证矩阵元素是否为有效数值类型,无法提前拦截错误。
解决方案
- 修正输入获取代码,转换为数值类型:
将xCols和yCol的获取代码中,把字符串转换为float类型(可根据实际数据类型选择"F"$或"J"$等):- xCols:
flip value flip select ", "F"$ssr[string x[1];"";"";""], " from TABLE - yCol:
flip value flip select ", "F"$(string x[0]), " from TABLE
- xCols:
- 增强函数内的类型校验:
在if[not all each count each X1; :typeX1]之后添加元素类型和空值检查:// 检查X1元素是否为float类型 if[not 9h=type first first X1; :`type`X1_non_numeric] // 检查是否存在空值 if[any null X1; :`null`X1] if[any null Y; :`null`Y] - 预验证转换结果:调用函数前,可先检查矩阵元素类型,比如用
type first first xCols确认是否为数值类型。
内容的提问来源于stack exchange,提问作者mmv456
相关产品推荐
相关产品推荐

