Guest User

Untitled

a guest
Dec 5th, 2017
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.51 KB | None | 0 0
  1. from sklearn import datasets, linear_model
  2. from sklearn.metrics import r2_score, mean_squared_error
  3. from sklearn.preprocessing import PolynomialFeatures
  4. from sklearn.linear_model import LinearRegression
  5. from sklearn.pipeline import Pipeline
  6. from sklearn.model_selection import cross_val_score
  7. import numpy as np
  8. import pandas as pd
  9. import matplotlib.pyplot as plt
  10.  
  11. ## подкл выборку
  12.  
  13. x_train = pd.read_table ("tic/ticdata2000.txt", header = None).iloc [0:4000, 0:85]
  14. x_test = x_train.iloc[0:4000, 84]
  15.  
  16.  
  17. y_train = pd.read_table ("tic/ticeval2000.txt", header = None)
  18. y_test = pd.read_table ("tic/tictgts2000.txt", header = None)
  19.  
  20.  
  21. ## обучение выборки
  22. regression = linear_model.LinearRegression()
  23. regression.fit (x_train, y_train)
  24.  
  25.  
  26. train_predict = regression.predict (x_train)
  27.  
  28. print('Коэффициенты: \n', regression.coef_)
  29. print("Cреднеквадратичная ошибка: %.2f" % mean_squared_error(y_train, train_predict))
  30. print('Оценка отклонения: %.2f' % r2_score(y_train, train_predict))
  31.  
  32. ## Проверка точности модели по тестовой выборке и запись в результирующий файл
  33. y_pr = pd.DataFrame(train_predict)
  34. y_test = y_test.reset_index(drop = True)
  35. res = pd.concat([y_pr, y_test], axis=1)
  36. res.to_csv("result.txt", index = False)
  37.  
  38. ## Построение модели с использованием полиномиальной функции (где-то тут ошибка)
  39.  
  40. degrees = [1,2,3]
  41. err = [1,2,3]
  42.  
  43. pol_index = x_test
  44. x_train_pol = x_train
  45. y_train_pol = y_train
  46. x_test_pol = x_test
  47. y_test_pol = y_test
  48.  
  49. for i in range(len(degrees)):
  50.     polynomial_features = PolynomialFeatures(degree = degrees[i],
  51.                                              include_bias = False)
  52.     linear_regression = LinearRegression()
  53.     pipeline = Pipeline([("polynomial_features", polynomial_features),
  54.                          ("linear_regression", linear_regression)])
  55.     pipeline.fit(x_train_pol, y_train_pol)
  56.     scores = cross_val_score(pipeline, x_train_pol, y_train_pol,
  57.                              scoring="neg_mean_squared_error")
  58.     pred_y = pipeline.predict(x_test_pol)
  59.     err[i] = -scores.mean()
  60.     print("\nСтепень: {}\nСреднеквадратичная ошибка = {}(+/- {})".format(degrees[i], -scores.mean(),
  61.                                                scores.std()))
  62.     print('Показатель отклонения: %.3f' % r2_score(y_test_pol, pred_y))
Advertisement
Add Comment
Please, Sign In to add comment