Advertisement
brandblox

numpy lab(26/02/2024) linear

Feb 25th, 2024 (edited)
903
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. def estimate_coef(x, y):
  5.     # number of observations/points
  6.     n = np.size(x)
  7.    
  8.     # mean of x and y vector
  9.     m_x = np.mean(x)
  10.     m_y = np.mean(y)
  11.    
  12.     # calculating cross-deviation and deviation about x
  13.     SS_xy = np.sum(y * x) - n * m_y * m_x
  14.     SS_xx = np.sum(x * x) - n * m_x * m_x
  15.    
  16.     # calculating regression coefficients
  17.     b_1 = SS_xy / SS_xx
  18.     b_0 = m_y - b_1 * m_x
  19.     print("b_0", b_0)
  20.     print("b_1", b_1)
  21.     return (b_0, b_1)
  22.  
  23. def plot_regression_line(x, y, b):
  24.     # plotting the actual points as scatter plot
  25.     plt.scatter(x, y, color="m", marker="o", s=30)
  26.    
  27.     # predicted response vector
  28.     y_pred = b[0] + b[1] * x
  29.    
  30.     # plotting the regression line
  31.     plt.plot(x, y_pred, color="g")
  32.    
  33.     # putting labels
  34.     plt.xlabel('x')
  35.     plt.ylabel('y')
  36.    
  37. # observations / data
  38. x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  39. y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
  40.    
  41. # estimating coefficients
  42. b = estimate_coef(x, y)
  43. plot_regression_line(x, y, b)
  44.  
  45. output:
  46. https://ibb.co/xmMGCbm
  47.  
  48. # Predict the speed of a 10-year old car.
  49. import matplotlib.pyplot as plt
  50. from scipy import stats
  51.  
  52. x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
  53. y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]
  54.  
  55. slope, intercept, r, p, std_err = stats.linregress(x, y)
  56.  
  57. def myfunc(x):
  58.     return slope * x + intercept
  59.  
  60. mymodel = list(map(myfunc, x))
  61.  
  62. plt.scatter(x, y)
  63. plt.plot(x, mymodel)
  64. plt.show()
  65.  
  66. speed = myfunc(10)
  67. print(speed)
  68.  
  69. # Example of bad-fit
  70. import matplotlib.pyplot as plt
  71. from scipy import stats
  72.  
  73. x = [89,43,36,36,95,10,66,34,38,20,26,29,48,
  74.      64,6 ,5 ,36 ,66 ,72 ,40]
  75. y = [21 ,46 ,3 ,35 ,67 ,95 ,53 ,72 ,58 ,10 ,
  76.      26 ,34 ,90 ,33 ,38 ,20 ,56 ,2 ,47 ,15]
  77.  
  78. slope, intercept,r,p,std_err = stats.linregress(x,y)
  79.  
  80. def myfunc(x):
  81.     return slope * x + intercept
  82.  
  83. mymodel = list(map(myfunc,x))
  84.  
  85. plt.scatter(x,y)
  86. plt.plot(x,mymodel)
  87. plt.show()
  88.  
  89. print(r)
  90.  
  91. output:
  92. https://ibb.co/3F6nXwZ
  93. https://ibb.co/k3jv8xM
  94.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement