(+84) 236.3827111 ex. 402

Ứng dụng Hồi quy tuyến tính trong dự báo


Dự đoán điểm chuyên cần dựa vào buổi học

Cho dữ liệu như sau:

buoi=np.array([1,2,3,4,5,6,7,8,9,10]).reshape(-1,1)

diem=np.array([0,0, 2,3,5,7,8,9, 10,10]).reshape(-1,1)

Viết chương trình thể hiện:

  • Dữ liệu thực tế
  • Đường thẳng hồi quy
  • Cho dữ liệu test là số buổi học của 1 bạn, in ra điểm dự đoán của bạn ấy.
  • Thể hiện điểm dự báo trên đồ thị

Code tham khảo:

import matplotlib.pyplot as plt

import numpy as np

from sklearn import linear_model

buoi=np.array([1,2,3,4,5,6,7,8,9,10]).reshape(-1,1)

diem=np.array([0,0, 2,3,5,7,8,9, 10,10]).reshape(-1,1)

lr=linear_model.LinearRegression()

lr.fit(buoi,diem)

print('He so a=', lr.coef_)

print('He so b =', lr.intercept_)

plt.xlabel('So buoi di hoc')

plt.ylabel('Diem chuyen can')

plt.grid(True)

x=np.linspace(0, 10)

y=lr.coef_[0][0]*x+lr.intercept_

plt.plot(buoi, diem,'go', label='Du lieu thuc')

plt.plot(x,y, label='duong hoi qui')

x_test=int(input('Nhap so buoi di hoc:'))

y_test=lr.coef_[0][0]*x_test+lr.intercept_[0]

print('Diem chuyen can cua ban=', format(y_test, '.2f'))

plt.plot(x_test, y_test, "ro")

plt.plot((x_test, x_test), (0, y_test), "r--")

plt.plot((0,x_test), (y_test, y_test), "r--")

plt.xlim(min(buoi),max(buoi) )

plt.ylim(min(diem),max(diem))

plt.text(x_test+0.2, min(diem)+0.3, x_test, fontsize='10', color='blue')

plt.text(min(buoi)+0.2, y_test+0.3, format(y_test, '.3f'), fontsize='10', color='blue')

plt.legend()

plt.show()

Kết quả demo