df = data_cleaned
# Chia dữ liệu thành các đoạn nhỏ và thực hiện hồi quy tuyến tính trên từng đoạn
window_size = 50
slopes = []
for i in range(len(df) - window_size):
x = np.arange(window_size).reshape(-1, 1)
y = df["Diameter"].iloc[i:i + window_size].values.reshape(-1, 1)
model = LinearRegression().fit(x, y)
slopes.append(model.coef_[0][0])
# Tìm điểm mà tại đó hệ số góc của hồi quy tuyến tính thay đổi đáng kể
slopes = np.array(slopes)
change_point = np.argmax(np.abs(np.diff(slopes)))
# In ra điểm thay đổi
print(f"Điểm thay đổi của dữ liệu: {change_point + window_size // 2}")
# In ra điểm thay đổi
change_point_index = change_point + window_size // 2
print(f"Điểm thay đổi của dữ liệu: {change_point_index}")
# Điểm cuối cùng của dữ liệu
end_point_index = len(df) - 1
print(f"Điểm cuối cùng của dữ liệu: {end_point_index}")
# Tính khoảng cách giữa điểm thay đổi và điểm cuối cùng
distance = end_point_index - change_point_index
distance_adjusted = round(distance * 0.1, 1)
print(f"Khoảng cách giữa điểm thay đổi và điểm cuối cùng: {distance} vị trí index")
# Vẽ biểu đồ
plt.figure(figsize=(10, 5))
plt.plot(df["Diameter"].values, label="Data")
plt.axvline(x=change_point + window_size // 2, color='red', linestyle='--', label='Change Point')
plt.axvline(x=end_point_index, color='blue', linestyle='--', label='End Point')
# Vẽ mũi tên hai chiều giữa hai điểm
plt.annotate('', xy=(change_point_index, df["Diameter"].max()/2),
xytext=(end_point_index, df["Diameter"].max()/2),
arrowprops=dict(arrowstyle='<->', color='green'))
# Thêm chú thích về khoảng cách
plt.text((change_point_index + end_point_index) / 2, df["Diameter"].max()/2+10,
f'Khoảng cách: {distance_adjusted}' 'mm',
horizontalalignment='center', fontsize=8, color='green')
plt.title("Chart dữ liệu")
plt.xlabel("Index")
plt.ylabel("Diameter")
plt.legend()
plt.grid(True)
plt.show()