korenizla

multiply matrix

Nov 21st, 2022
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. # выделим в данных признаки и целевой признак
  2. features = data.drop(['Страховые выплаты'], axis=1)
  3. target = data['Страховые выплаты']
  4.  
  5. # разделим на обучающую и тестовую выборки
  6. train_features, test_features, train_target, test_target = train_test_split(
  7.                                                             features, target, test_size = 0.25,
  8.                                                             random_state=1234)
  9.  
  10. class LinearRegression:
  11.     def fit(self, train_features, train_target):
  12.         X = np.concatenate((np.ones((train_features.shape[0], 1)), train_features), axis=1)
  13.         y = train_target
  14.         w = (np.linalg.inv(X.T.dot(X)).dot(X.T)).dot(y)
  15.         self.w = w[1:]
  16.         self.w0 = w[0]
  17.  
  18.     def predict(self, test_features):
  19.         return test_features.dot(self.w) + self.w0
  20.  
  21. model = LinearRegression()
  22. model.fit(train_features, train_target)
  23. predictions = model.predict(test_features)
  24. print(r2_score(test_target, predictions))
  25.  
  26. #Теперь сгенерируем случайную матрицу функцией numpy.random.normal()
  27.  
  28. np.random.seed(100) # фиксируем случайность
  29.  
  30. P =  np.random.normal(3, 2.5, size=(4, 4))
  31. A = X @ P
  32. A.shape
  33.  
  34. model.fit(A, train_target)
  35. predictions = model.predict(A)
  36. print(r2_score(test_target, predictions))
  37.  
  38.  
  39. ---------------------------------------------------------------------------
  40. ValueError                                Traceback (most recent call last)
  41. /tmp/ipykernel_31/3434024009.py in <module>
  42. ----> 1 model.fit(A, train_target)
  43.       2 predictions = model.predict(A)
  44.       3 print(r2_score(test_target, predictions))
  45.  
  46. /tmp/ipykernel_31/3890212866.py in fit(self, train_features, train_target)
  47.       3         X = np.concatenate((np.ones((train_features.shape[0], 1)), train_features), axis=1)
  48.       4         y = train_target
  49. ----> 5         w = (np.linalg.inv(X.T.dot(X)).dot(X.T)).dot(y)
  50.       6         self.w = w[1:]
  51.       7         self.w0 = w[0]
  52.  
  53. ValueError: shapes (5,4847) and (3635,) not aligned: 4847 (dim 1) != 3635 (dim 0)
  54.  
Add Comment
Please, Sign In to add comment