Advertisement
evgeniya_polyntseva

smad 3

Nov 15th, 2020
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.34 KB | None | 0 0
  1. import numpy as np
  2. from statistics import mean
  3. import pandas as pd
  4. from pandas import read_csv
  5.  
  6. data = read_csv("data_3.1.csv", sep=';', encoding="Windows-1251")
  7. x1 = data['x1']
  8. x2 = data['x2']
  9. y = data['y']
  10.  
  11.  
  12. def f(x1, x2):
  13.     return 1, 1 / x1, x1, x2 ** 2, x2, x1 * x2
  14.  
  15.  
  16. def func_u(x1, x2, theta):
  17.     return theta[0] * f(x1, x2)[0] + theta[1] * f(x1, x2)[1] + theta[2] * f(x1, x2)[2] + theta[3] * f(x1, x2)[3] + \
  18.            theta[4] * f(x1, x2)[4] + theta[5] * f(x1, x2)[5]
  19.  
  20.  
  21. def simulation(u, n, p):
  22.     omega = np.dot((u - mean(u)), (u - mean(u)).T) / (n - 1)
  23.     # omega = 6.42282
  24.     dispersion = np.math.sqrt(p * omega)
  25.     # dispersion = 0.80143
  26.     e = np.random.normal(0, dispersion, n)
  27.     y = u + e
  28.     # y = data['y']
  29.     return dispersion, y, omega
  30.  
  31.  
  32. def theta_estimate(x1, x2, y, n):
  33.     x = np.array([np.ones(n), f(x1, x2)[1], f(x1, x2)[2], f(x1, x2)[3], f(x1, x2)[4], f(x1, x2)[5]])
  34.     estimate = np.linalg.inv(x.dot(x.T)).dot(x).dot(y)
  35.     return estimate
  36.  
  37.  
  38. def sigma_estimate(x1, x2, y, n, m):
  39.     t_est = theta_estimate(x1, x2, y, n)
  40.     u_est = func_u(x1, x2, t_est)
  41.     e = y - u_est
  42.     estimate = np.dot(e, e.T) / (n - m)
  43.     return estimate, u_est, e
  44.  
  45.  
  46. # Построить доверительные интервалы для каждого параметра модели регрессии.
  47. def sigma_teta(x1, x2, y, n, m):
  48.     x = np.array([np.ones(n), f(x1, x2)[1], f(x1, x2)[2], f(x1, x2)[3], f(x1, x2)[4], f(x1, x2)[5]])
  49.     d = np.linalg.inv(x.dot(x.T))
  50.     sigma = sigma_estimate(x1, x2, y, n, m)[0]
  51.     d_jj = np.diagonal(d)
  52.     s_t = np.sqrt(sigma * d_jj)
  53.     return s_t, sigma, d_jj
  54.  
  55.  
  56. def confidence_interval(x1, x2, y, n, m, theta):
  57.     global lower_bound, upper_bound
  58.     t = 1.984
  59.     theta_hat = theta_estimate(x1, x2, y, n)
  60.     sigma = sigma_teta(x1, x2, y, n, m)[0]
  61.     print('\n', 'Доверительное оценивание для отдельного параметра:')
  62.     print('j', '\t', 'teta_j', '\t\t', 'teta_hat_j', '\t\t\t\t', 'a', '\t\t\t\t\t\t', 'b')
  63.     for j in range(len(theta)):
  64.         lower_bound = theta_hat - t * sigma
  65.         upper_bound = theta_hat + t * sigma
  66.         print(j + 1, '\t', '%.2f' % theta[j], '\t\t\t', '%.10f' % theta_hat[j], '\t\t\t', '%.10f' % lower_bound[j],
  67.               '\t\t\t', '%.10f' % upper_bound[j])
  68.     return lower_bound, upper_bound, theta_hat
  69.  
  70.  
  71. # Проверка гипотезы о незначимости для каждого параметра
  72. def hypothesis_testing(x1, x2, y, n, m, theta):
  73.     theta_hat = confidence_interval(x1, x2, y, n, m, theta)[2]
  74.     sigma = sigma_teta(x1, x2, y, n, m)[1]
  75.     d_jj = sigma_teta(x1, x2, y, n, m)[2]
  76.     f = theta_hat ** 2 / ((sigma ** 2) * d_jj)
  77.     f_critical = 3.94
  78.     print('\n', 'Проверка гипотезы о незначимости:')
  79.     print('j', '\t', 'F', '\t\t\t\t\t', 'Гипотеза о незначимости')
  80.     for j in range(len(d_jj)):
  81.         if f[j] < f_critical:
  82.             print(j + 1, '\t', '%.10f' % f[j], '\t\t', 'Не отвергается')
  83.         else:
  84.             print(j + 1, '\t', '%.10f' % f[j], '\t\t', 'Отвергается')
  85.  
  86.  
  87. # Проверка гипотезы о незначимости регрессии
  88. def regression_hypothesis_testing(x1, x2, n, m, theta):
  89.     x = np.array([np.ones(n), f(x1, x2)[1], f(x1, x2)[2], f(x1, x2)[3], f(x1, x2)[4], f(x1, x2)[5]])
  90.     theta_hat = confidence_interval(x1, x2, y, n, m, theta)[2]
  91.     rss_h = np.sum((y - np.average(y)) ** 2)
  92.     rss = np.sum((np.squeeze(np.asarray(y - np.dot(theta_hat, x)))) ** 2)
  93.     fr = ((rss_h - rss) / 5) / (rss / (n - m))
  94.     f_critical = 2.3
  95.     print('\n', 'Проверка гипотезы о незначимости регрессии:')
  96.     if fr < f_critical:
  97.         print('F=', '%.10f' % fr, '=> гипотеза о незначимости регрессии не отвергается')
  98.     else:
  99.         print('F=', '%.10f' % fr, '=> гипотеза о незначимости регрессии отвергается')
  100.  
  101.  
  102. # Прогнозирование математического ожидания функции отклика
  103. def eta(x1, x2, y, n):
  104.     global f_x
  105.     etas = np.array([])
  106.     theta_hat = theta_estimate(x1, x2, y, n)
  107.     x11 = [1, 1, 1, 1, 1]
  108.     x22 = [1, 1.5, 2, 2.5, 3]
  109.     for j in range(len(x11)):
  110.         f_x = np.array([1, 1 / x11[j], x11[j], x22[j] ** 2, x22[j], x11[j] * x22[j]])
  111.         eta = np.dot(f_x, theta_hat)
  112.         etas=np.append(eta)
  113.         print("x1 = %d, x2 = %d, f(x) = " % (x11[j], x22[j]), f_x[j], ", f(x)T*theta = ", eta)
  114.         print("theta_hat = ", theta_hat)
  115.     return f_x, etas
  116.  
  117.  
  118. # Построение доверительных интервалов для математического ожидания функции отклика
  119. def sigma_eta(x1, x2, y, n, m):
  120.     x=[]
  121.     x_1 = np.array([1, 1, 1, 1, 1])
  122.     x_2 = np.array([1, 1.5, 2, 2.5, 3])
  123.     onesss=np.ones(len(x_1))
  124.     f_x = eta(x1, x2, y, n)[0]
  125.     eta_hat = eta(x1, x2, y, n)[1]
  126.     for j in range(len(x_1)):
  127.         xx= np.array([onesss[j], f(x_1[j], x_2[j])[1], f(x_1[j], x_2[j])[2], f(x_1[j], x_2[j])[3], f(x_1[j], x_2[j])[4], f(x_1[j], x_2[j])[5]])
  128.         x.append(xx)
  129.     d = np.linalg.inv(x.dot(x.T))
  130.     sigma = sigma_estimate(x1, x2, y, n, m)[0]
  131.     d_jj = np.diagonal(d)
  132.     s_t = np.sqrt(f_x * d_jj)
  133.     return s_t, sigma, d_jj
  134.  
  135.  
  136. def main():
  137.     a = 1
  138.     b = 3
  139.     p = 0.1
  140.     n = 100
  141.     m = 6
  142.     theta = (1, 1, 0.01, 1, 0.01, 0)
  143.     # part 1
  144.     u = func_u(x1, x2, theta)
  145.     disp, y, omega = simulation(u, n, p)
  146.     print('omega =', omega)
  147.     print('dispersion =', disp)
  148.     # part 2
  149.     sigma_est = sigma_estimate(x1, x2, y, n, m)[0]
  150.     print('theta_estimate =', theta_estimate(x1, x2, y, n))
  151.     print('sigma_estimate =', sigma_estimate(x1, x2, y, n, m)[0])
  152.     result1 = pd.DataFrame({'x1': x1, 'x2': x2, 'u': u, 'y': y,
  153.                             'тета*х': sigma_estimate(x1, x2, y, n, m)[1],
  154.                             'e': sigma_estimate(x1, x2, y, n, m)[2]})
  155.     # result1.to_csv("data3.csv", sep=';', encoding="Windows-1251")
  156.     confidence_interval(x1, x2, y, n, m, theta)
  157.     # hypothesis_testing(x1, x2, y, n, m, theta)
  158.     # regression_hypothesis_testing(x1, x2, n, m, theta)
  159.     eta(x1, x2, y, n)
  160.     sigma_eta(x1, x2, y, n, m)
  161.  
  162. if __name__ == '__main__':
  163.     main()
  164.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement