Data-Science-Tutorial / Linear-Regression.py
TinTinDo's picture
Upload 14 files
f144dc6 verified
# Hồi quy tuyến tính
# - Thuật ngữ hồi quy được sử dụng khi bạn cố gắng tìm mối quan hệ giữa các biến.
# - Trong Học máy và mô hình thống kê, mối quan hệ đó được sử dụng để dự đoán kết quả của các sự kiện.
'''
Trong mô-đun này, chúng ta sẽ giải quyết các câu hỏi sau:
Chúng ta có thể kết luận rằng Average_Pulse và Duration có liên quan đến Calorie_Burnage không?
Chúng ta có thể sử dụng Average_Pulse và Duration để dự đoán Calorie_Burnage không?
'''
# Phương pháp bình phương nhỏ nhất(Least Square Method)
# - Hồi quy tuyến tính sử dụng phương pháp bình phương nhỏ nhất.
# - Khái niệm này là vẽ một đường thẳng đi qua tất cả các điểm dữ liệu đã được biểu diễn. Đường thẳng này được định vị sao cho khoảng cách đến tất cả các điểm dữ liệu là nhỏ nhất.
# - Khoảng cách này được gọi là "giá trị còn lại" hoặc "lỗi".
# - Các đường nét đứt màu đỏ biểu thị khoảng cách từ các điểm dữ liệu đến hàm toán học được vẽ.
# Hồi quy tuyến tính sử dụng một biến giải thích
'''
Trong ví dụ này, chúng ta sẽ thử dự đoán Calorie_Burnage với Average_Pulse bằng cách sử dụng Hồi quy tuyến tính:
'''
# Ví dụ:
# Three lines to make our compiler able to draw:
# import sys
# import matplotlib
# matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
# Load dữ liệu
full_health_data = pd.read_csv('data.csv', header=0, sep=',')
# Chọn cột
x = full_health_data['Average_Pulse']
y = full_health_data['Calorie_Burnage']
# Hồi quy tuyến tính
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
# Tạo dự đoán theo mô hình
y_pred = slope * x + intercept
# Vẽ scatter plot + đường hồi quy tuyến tính
plt.scatter(x,y, color='blue', label='Data Points')
plt.plot(x,y_pred, color='red', label='Linear Regression Line')
plt.xlabel('Average_Pulse')
plt.ylabel('Calorie_Burnage')
plt.title('Linear Regression of Calorie Burnage and Average Pulse ')
plt.legend(loc='upper right')
plt.show()
# Two lines to make our compiler able to draw:
# plt.savefig(sys.stdout.buffer)
# sys.stdout.flush()
'''
Giải thích ví dụ:
Nhập các mô-đun bạn cần: Pandas, matplotlib và Scipy
Cô lập Average_Pulse là x. Cô lập Calorie_burnage là y
Lấy các giá trị khóa quan trọng với: slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
Tạo một hàm sử dụng giá trị độ dốc và giá trị chặn để trả về một giá trị mới. Giá trị mới này biểu thị vị trí trên trục y của giá trị x tương ứng.
Chạy từng giá trị của mảng x thông qua hàm. Điều này sẽ tạo ra một mảng mới với các giá trị mới cho trục y: mymodel = list(map(myfunc, x))
Vẽ biểu đồ phân tán ban đầu: plt.scatter(x, y)
Vẽ đường hồi quy tuyến tính: plt.plot(x, mymodel)
Xác định giá trị lớn nhất và nhỏ nhất của trục
Gắn nhãn trục: "Average_Pulse" và "Calorie_Burnage"
'''
# Vẽ Linear Regression + Confidence Interval +- 1 std_err
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
# Load dữ liệu
full_health_data = pd.read_csv('data.csv')
# Chọn cột
x = full_health_data['Average_Pulse']
y = full_health_data['Calorie_Burnage']
# Hồi quy tuyến tính
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
# Dự đoán y theo mô hình
y_pred = slope * x + intercept
# Tạo vùng confidence interval (±1 std_err)
y_upper = y_pred + std_err
y_lower = y_pred - std_err
# Vẽ scatter plot
plt.figure(figsize=(8,6))
plt.scatter(x, y, label='Data Points', color='blue')
# Vẽ đường hồi quy
plt.plot(x, y_pred, color='red', label='Regression Line')
# Công thức std_err = s / căn n ; với s là độ lệch chuẩn của mẫu (sample standard deviation), n là kích thước mẫu (sample size)
# Vẽ vùng ±1 std_err # Giá trị std_err càng nhỏ → trung bình mẫu càng đáng tin cậy (ít dao động khi lấy mẫu lặp lại).
plt.fill_between(x, y_lower, y_upper, color='red', alpha=0.2, label='±1 Std. Err.')
# Labels, title, legend
plt.xlabel('Average_Pulse')
plt.ylabel('Calorie_Burnage')
plt.title('Linear Regression with ±1 Std. Error')
plt.legend()
plt.show()
# TỔNG HỢP FULL LINEAR REGRESSION CƠ BẢN --> NÂNG CAO
# =========================
# 1️⃣ Import thư viện cần thiết
# =========================
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
# =========================
# 2️⃣ Load dữ liệu từ CSV
# =========================
# CSV phải có cột: 'Average_Pulse', 'Calorie_Burnage'
full_health_data = pd.read_csv('data.csv')
# Kiểm tra số hàng và số cột
rows = full_health_data.shape[0]
columns = full_health_data.shape[1]
print(f"Số hàng: {rows}, Số cột: {columns}")
# =========================
# 3️⃣ Chọn dữ liệu x, y
# =========================
x = full_health_data['Average_Pulse']
y = full_health_data['Calorie_Burnage']
# =========================
# 4️⃣ Hồi quy tuyến tính
# =========================
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
# Dự đoán y theo mô hình
y_pred = slope * x + intercept
# =========================
# 5️⃣ Metrics đánh giá mô hình
# =========================
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
mse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y, y_pred)
r2 = r2_score(y, y_pred)
print(f"MSE: {mse:.2f}, RMSE: {rmse:.2f}, MAE: {mae:.2f}, R²: {r2:.3f}")
# =========================
# 6️⃣ Vẽ scatter plot + regression line + confidence interval
# =========================
y_upper = y_pred + std_err
y_lower = y_pred - std_err
plt.figure(figsize=(10,6))
plt.scatter(x, y, label='Dữ liệu thực', color='blue')
plt.plot(x, y_pred, color='red', label='Đường hồi quy')
plt.fill_between(x, y_lower, y_upper, color='red', alpha=0.2, label='±1 Std. Err.')
plt.xlabel('Average_Pulse')
plt.ylabel('Calorie_Burnage')
plt.title('Linear Regression: Calorie Burnage vs Average Pulse')
plt.legend(title='Chú giải', fontsize=10, title_fontsize=12)
plt.xlim([0, x.max()*1.1])
plt.ylim([0, y.max()*1.1])
plt.grid(True)
plt.show()
# =========================
# 7️⃣ Dự đoán giá trị mới
# =========================
new_pulses = [80, 100, 120]
predicted_calories = [slope*p + intercept for p in new_pulses]
for p, c in zip(new_pulses, predicted_calories):
print(f"Average Pulse: {p} → Dự đoán Calorie Burnage: {c:.2f}")
'''
✅ Tính năng đầy đủ:
Tự động load dữ liệu và kiểm tra số hàng/cột.
Linear Regression + vector hóa dự đoán y_pred.
Metrics: MSE, RMSE, MAE, R².
Đồ thị: scatter, regression line, ±1 std_err, legend, title, grid.
Tự động scale xlim/ylim dựa trên dữ liệu.
Dự đoán giá trị mới với mô hình.
'''