-
Notifications
You must be signed in to change notification settings - Fork 2
/
multivariate_regressor.py
48 lines (38 loc) · 1.26 KB
/
multivariate_regressor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Multivariate linear regression
Requires scipy to be installed.
Implemented by Chris Rayner (2015)
dchrisrayner AT gmail DOT com
Just simple linear regression with regularization - nothing new here
"""
import numpy as np
from scipy import sparse
def ideal_data(num, dimX, dimY, _rank=None, noise=1):
"""Full rank data"""
X = np.random.randn(num, dimX)
W = np.random.randn(dimX, dimY)
Y = np.dot(X, W) + np.random.randn(num, dimY) * noise
return X, Y
class MultivariateRegressor(object):
"""
Multivariate Linear Regressor.
- X is an n-by-d matrix of features.
- Y is an n-by-D matrix of targets.
- reg is a regularization parameter (optional).
"""
def __init__(self, X, Y, reg=None):
if np.size(np.shape(X)) == 1:
X = np.reshape(X, (-1, 1))
if np.size(np.shape(Y)) == 1:
Y = np.reshape(Y, (-1, 1))
if reg is None:
reg = 0
W1 = np.linalg.pinv(np.dot(X.T, X) + reg * sparse.eye(np.size(X, 1)))
W2 = np.dot(X, W1)
self.W = np.dot(Y.T, W2)
def __str__(self):
return 'Multivariate Linear Regression'
def predict(self, X):
if np.size(np.shape(X)) == 1:
X = np.reshape(X, (-1, 1))
return np.dot(X, self.W.T)