tolord

Untitled

Sep 27th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. class Matrix:
  2.     @classmethod
  3.     def zeros(cls, n_rows, n_cols):
  4.         return cls([[0.0] * n_cols for _ in range(n_rows)])
  5.  
  6.     def __init__(self, data):
  7.         self.data = data
  8.         self.n_rows = len(self.data)
  9.         self.n_cols = len(self.data[0])
  10.  
  11.     def __getitem__(self, ij):
  12.         i, j = ij
  13.         return self.data[i][j]
  14.  
  15.     def __setitem__(self, ij, value):
  16.         i = ij[0]
  17.         j = ij[1]
  18.  
  19.         self.data[i][j] = value
  20.  
  21.     def __eq__(self, other):
  22.         return isinstance(other, Matrix) and self.data == other.data
  23.  
  24.     def __str__(self):
  25.         return str(self.data)
  26.  
  27.     def __repr__(self):
  28.         return repr(self.data)
  29.  
  30.     # ---
  31.  
  32.     def __matmul__(self, other):
  33.         result = Matrix.zeros(self.n_rows, other.n_cols)
  34.         for i in range (self.n_rows):
  35.             for j in range (other.n_cols):
  36.                 for k in range (self.n_cols):
  37.                     result[i][j] = result[i][j] + self.__getitem__([i, k]) * other.__getitem__([[k], [j]])
  38.         return Matrix(result)
  39.  
  40.     def transpose(self):
  41.         result = Matrix.zeros(self.n_cols, self.n_rows)
  42.         for i in range (self.n_cols):
  43.             for j in range (self.n_rows):
  44.                 print ([i, j])
  45.                 result[i][j] = self.__getitem__([i, j])
  46.         return Matrix(result)
  47.  
  48.     def inverse(self):
  49.         pass
  50.  
  51. class LinearRegression:
  52.     def __init__(self):
  53.         self.beta = None
  54.         self.beta0 = None
  55.  
  56.     def fit(self, X, y):
  57.         # N.B. здесь и далее y -- вектор-столбец, то есть экземпляр
  58.         #      класса Matrix.
  59.         return self
  60.  
  61.     def predict(self, X):
  62.         y = Matrix.zeros(X.n_row, 1)
  63.         return y
  64.  
  65. def rmse(y_true, y_pred):
  66.     return 0.0
  67.  
  68. def learn_test_split(X, y):
  69.     X_learn = 0
  70.     X_test = 0
  71.     y_learn = 0
  72.     y_test = 0
  73.     return X_learn, X_test, y_learn, y_test
  74.  
  75. def cv_linear_regression(X, y, *, n_iter=1000):
  76.     return 0.0
  77.  
  78. a = [[1, 2, 3], [4, 5, 6]]
  79. b = Matrix(a)
  80. print (b.transpose())
Advertisement
Add Comment
Please, Sign In to add comment