# NumPy 中的矩阵和向量

numpy的`ndarray`类用于表示矩阵和向量。 要在numpy中构造矩阵，我们在列表中列出矩阵的行， 并将该列表传递给numpy数组构造函数。

``````A = np.array([[1,-1,2],[3,2,0]])
``````

``````v = np.array([[2],[1],[3]])
``````

``````v = np.transpose(np.array([[2,1,3]]))
``````

numpy重载数组索引和切片符号以访问矩阵的各个部分。 例如，要打印矩阵A中的右下方条目，我们会这样做

``````print(A[1,2])
``````

``````col = A[:,1:2]
``````

``````w = np.dot(A,v)
``````

## 用numpy求解方程组

A x = b

``````A = np.array([[2,1,-2],[3,0,1],[1,1,-1]])
b = np.transpose(np.array([[-3,5,-2]]))
``````

``````x = np.linalg.solve(A,b)
``````

## 应用：多元线性回归

β = (XT X)-1 XT y

``````Xt = np.transpose(X)
XtX = np.dot(Xt,X)
Xty = np.dot(Xt,y)
beta = np.linalg.solve(XtX,Xty)
``````

β = (XT X)-1 XT y

(XT X) β = XT y

``````import csv
import numpy as np

X = []
y = []
with open('Housing.csv') as f:
next(rdr)
for line in rdr:
xline = [1.0]
for s in line[:-1]:
xline.append(float(s))
X.append(xline)
y.append(float(line[-1]))
return (X,y)

# Convert all but the last 10 rows of the raw data to numpy arrays
d = len(X0)-10
X = np.array(X0[:d])
y = np.transpose(np.array([y0[:d]]))

# Compute beta
Xt = np.transpose(X)
XtX = np.dot(Xt,X)
Xty = np.dot(Xt,y)
beta = np.linalg.solve(XtX,Xty)
print(beta)

# Make predictions for the last 10 rows in the data set
for data,actual in zip(X0[d:],y0[d:]):
x = np.array([data])
prediction = np.dot(x,beta)
print('prediction = '+str(prediction[0,0])+' actual = '+str(actual))
``````

``````[[ -4.14106096e+03]
[  3.55197583e+00]
[  1.66328263e+03]
[  1.45465644e+04]
[  6.77755381e+03]
[  6.58750520e+03]
[  4.44683380e+03]
[  5.60834856e+03]
[  1.27979572e+04]
[  1.24091640e+04]
[  4.19931185e+03]
[  9.42215457e+03]]
prediction = 97360.6550969 actual = 82500.0
prediction = 71774.1659014 actual = 83000.0
prediction = 92359.0891976 actual = 84000.0
prediction = 77748.2742379 actual = 85000.0
prediction = 91015.5903066 actual = 85000.0
prediction = 97545.1179047 actual = 91500.0
prediction = 97360.6550969 actual = 94000.0
prediction = 106006.800756 actual = 103000.0
prediction = 92451.6931269 actual = 105000.0
prediction = 73458.2949381 actual = 105000.0
``````