Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. from sklearn import linear_model
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5.  
  6. # 元データの作成
  7. x = np.arange(start=0.,stop=1., step=0.02)
  8. y = []
  9. for xi in x:
  10. # y = 4xi+1+noize
  11. yi = 4*xi + 1 + np.random.random()
  12. y.append(yi)
  13.  
  14.  
  15. # 元データのプロット
  16. plt.xlim(0, 1)
  17. plt.scatter(x,y)
  18. plt.savefig("test_data.jpg")
  19.  
  20. # 単回帰のパラメータを求める
  21. reg = linear_model.LinearRegression()
  22. x = np.array(x).reshape(-1,1)
  23. y = np.array(y).reshape(-1,1)
  24. result = reg.fit(x,y)
  25. a = result.coef_[0][0]
  26. b = result.intercept_[0]
  27. print("a:", a)
  28. print("b:", b)
  29.  
  30. # 単回帰の結果プロット
  31. y_hat = []
  32. for xi in x:
  33. yi_hat = a*xi + b
  34. y_hat.append(yi_hat)
  35.  
  36. plt.plot(x, y_hat, c="r", label="$ax+b$")
  37. plt.legend()
  38. plt.savefig("result.jpg")
  39. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement