Desc: 将数据集格式化成目标变量Y和自变量X,执行简单的线性回归,得到ws Args: dataSet -- 输入数据 Returns: ws -- 执行线性回归的回归系数 X -- 格式化自变量X Y -- 格式化目标变量Y
(dataSet)
| 280 | |
| 281 | # helper function used in two places |
| 282 | def linearSolve(dataSet): |
| 283 | """ |
| 284 | Desc: |
| 285 | 将数据集格式化成目标变量Y和自变量X,执行简单的线性回归,得到ws |
| 286 | Args: |
| 287 | dataSet -- 输入数据 |
| 288 | Returns: |
| 289 | ws -- 执行线性回归的回归系数 |
| 290 | X -- 格式化自变量X |
| 291 | Y -- 格式化目标变量Y |
| 292 | """ |
| 293 | m, n = shape(dataSet) |
| 294 | # 产生一个关于1的矩阵 |
| 295 | X = mat(ones((m, n))) |
| 296 | Y = mat(ones((m, 1))) |
| 297 | # X的0列为1,常数项,用于计算平衡误差 |
| 298 | X[:, 1: n] = dataSet[:, 0: n-1] |
| 299 | Y = dataSet[:, -1] |
| 300 | |
| 301 | # 转置矩阵*矩阵 |
| 302 | xTx = X.T * X |
| 303 | # 如果矩阵的逆不存在,会造成程序异常 |
| 304 | if linalg.det(xTx) == 0.0: |
| 305 | raise NameError('This matrix is singular, cannot do inverse,\ntry increasing the second value of ops') |
| 306 | # 最小二乘法求最优解: w0*1+w1*x1=y |
| 307 | ws = xTx.I * (X.T * Y) |
| 308 | return ws, X, Y |
| 309 | |
| 310 | |
| 311 | # 回归树测试案例 |
no outgoing calls
no test coverage detected