试图在python中实现线性回归

时间:2014-10-31 15:56:15

标签: python regression

我在Python中实现线性回归,我认为我在将矩阵转换为numpy数组时做错了,但似乎无法弄明白。 任何帮助将不胜感激。

我正在从包含100列的csv文件加载数据。 y是最后一列。我没有使用col 1和2进行回归。

communities=np.genfromtxt("communities.csv", delimiter = ",", dtype=float)
xdata = communities[1:,2:99]
x = np.array([np.concatenate((v,[1]))for v in xdata])
y = communities[1:,99]

功能定义

def standRegress(xArr, yArr):
    xMat = mat(xArr); yMat = mat(yArr).T
    xTx = xMat.T*xMat
    if linalg.det(xTx)==0.0:
        print"singular matrix"
        return
    ws = xTx.I*(xMat.T*yMat)
    return ws

调用函数

w = standRegress(x,y)
xMat = mat(x) #shape(1994L,98L)
yMat = mat(y) #shape (1L, 1994L)
yhat = xMat*w #shape (1994L, 1L)

接下来我正在尝试计算RMSE,这就是我遇到问题的地方

yMatT = yMat.T #shape(1994L, 1L)
err = yhat - yMatT #shape(1994L, 1L)
error = np.array(err)
total_error = np.dot(error,error)
rmse = np.sqrt(total_error/len(p))

我在制作点积时出错,因此无法计算rmse。如果有人能帮助我找到我的错误,我将不胜感激。

Error: 
 ---> 11 np.dot(error,error)
 12 #test = (error)**2
 13 #test.sum()/len(y)
 ValueError: matrices are not aligned

1 个答案:

答案 0 :(得分:1)

我不太确定最后dot应该做什么。但是你可以通过这种方式多次errordot执行矩阵乘法,因此维度必须对齐。

参见例如以下示例:

import numpy as np
A = np.ones((3, 4))
B = np.ones((3, 4))
print np.dot(A, B)

这会产生错误ValueError: matrices are not aligned

然而,可能的是:

print np.dot(A.T, B)

输出:

[[ 3.  3.  3.  3.]
 [ 3.  3.  3.  3.]
 [ 3.  3.  3.  3.]
 [ 3.  3.  3.  3.]]

在您的示例中,error只是一个列向量 - 但存储为2D数组:

A = np.ones((3, 1))
B = np.ones((3, 1))
print np.dot(A, B)

同样的错误。

所以你可以转换一个参数 - 如上所示 - 或者将一列提取为一维数组:

print np.dot(A[:, 0], B[:, 0])

输出:

3.0