Một số vấn đề về hồi quy bayes và ứng dụng trong bài toán dự báo

106 72 1
Một số vấn đề về hồi quy bayes và ứng dụng trong bài toán dự báo

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

BỘ GIÁO DỤC VÀ ĐÀO TẠO TRƯỜNG ĐẠI HỌC QUY NHƠN VÕ HOÀNG VĨ MỘT SỐ VẤN ĐỀ VỀ HỒI QUY BAYES VÀ ỨNG DỤNG TRONG BÀI TOÁN DỰ BÁO LUẬN VĂN THẠC SĨ KHOA HỌC DỮ LIỆU ỨNG DỤNG Bình Định - Năm 2022 BỘ GIÁO DỤC VÀ ĐÀO TẠO TRƯỜNG ĐẠI HỌC QUY NHƠN VÕ HOÀNG VĨ MỘT SỐ VẤN ĐỀ VỀ HỒI QUY BAYES VÀ ỨNG DỤNG TRONG BÀI TOÁN DỰ BÁO Ngành : Khoa học liệu ứng dụng Mã số 8904648 : Người hướng dẫn: TS LÊ THANH BÍNH i Lời cam đoan Tơi xin cam đoan kết đề tài “Một số vấn đề hồi quy Bayes ứng dụng tốn dự báo” cơng trình nghiên cứu thực hướng dẫn TS Lê Thanh Bính, chưa cơng bố cơng trình khoa học khác thời điểm Các nội dung kết sử dụng luận văn có trích dẫn thích nguồn gốc Nếu có điều khơng trung thực, tơi xin hồn tồn chịu trách nhiệm luận văn Quy Nhơn, ngày tháng năm 2022 Học viên thực đề tài Võ Hoàng Vĩ ii Lời cảm ơn Luận văn hoàn thành hướng dẫn khoa học Thầy hướng dẫn TS Lê Thanh Bính Tác giả xin bày tỏ lịng biết ơn chân thành kính trọng sâu sắc đến Thầy hướng dẫn, Thầy tận tình giúp đỡ truyền đạt cho tác giả kiến thức quý báu kinh nghiệm trình nghiên cứu khoa học để tác giả hồn thành luận văn cách tốt Tác giả xin chân thành cảm ơn q thầy khoa Tốn Thống kê, khoa Cơng nghệ thơng tin, Phịng đào tạo sau đại học trường Đại học Quy Nhơn, quý thầy cô tham gia giảng dạy cho lớp Cao học Khoa học liệu ứng dụng khóa 23 tạo điều kiện giúp đỡ cho tác giả trình học tập nghiên cứu Tác giả xin trân trọng cảm ơn Quỹ Đổi sáng tạo Vingroup (VINIF) tài trợ học bổng cho tác giả theo mã số VINIF.2020.ThS.QN.01 Học bổng tạo động lực to lớn giúp tác giả học tập nghiên cứu suốt trình thực luận văn Bên cạnh đó, tác giả chân thành gửi lời cảm ơn sâu sắc đến bạn Nguyễn Quốc Dương (học viên Cao học lớp Khoa học liệu ứng dụng K24B) đưa nhiều góp ý quý báu cho luận văn Sau cùng, tác giả xin cảm ơn gia đình, người thân, bạn bè quan tâm, động viên giúp đỡ tác giả trình học tập hồn thành luận văn Tác giả hy vọng luận văn trở thành tài liệu tham khảo hữu ích cho bạn sinh viên, học viên cao học tìm tịi, nghiên cứu hồi quy Bayes iii Mục lục Lời mở đầu ix Kiến thức chuẩn bị 1.1 Giới thiệu 1.2 Một số phân phối thường dùng 1.3 1.4 1.2.1 Phân phối Bernoulli 1.2.2 Phân phối Beta 1.2.3 Phân phối nhị thức 1.2.4 Phân phối Dirichlet 1.2.5 Phân phối Gamma 1.2.6 Phân phối chuẩn (phân phối Gaussian) 1.2.7 Phân phối Student Suy luận Bayes cho tham số tỉ lệ phân phối nhị thức 1.3.1 Tiên nghiệm 1.3.2 Hậu nghiệm 10 1.3.3 Ước lượng điểm 13 1.3.4 Ước lượng khoảng 14 Suy luận Bayes cho kỳ vọng phân phối Gaussian 16 1.4.1 Sử dụng tiên nghiệm 16 1.4.2 Sử dụng tiên nghiệm chuẩn hậu nghiệm 17 iv 1.4.3 Ước lượng điểm 20 1.4.4 Ước lượng khoảng 21 Phương pháp hồi quy Bayes 2.1 24 Hồi quy tuyến tính đơn biến 24 2.1.1 Phương trình chuẩn đường bình phương tối thiểu 24 2.1.2 Dạng thay cho đường bình phương tối thiểu 26 2.1.3 Ước lượng phương sai xung quanh đường bình phương tối thiểu 26 2.2 2.3 2.1.4 Giả thiết hồi quy tuyến tính đơn 26 2.1.5 Định lý Bayes cho mô hình hồi quy 28 2.1.6 Phân phối dự báo cho quan sát tương lai 34 Hồi quy tuyến tính nhiều biến 36 2.2.1 Bình phương tối thiểu cho hồi quy tuyến tính nhiều biến 36 2.2.2 Giả thiết hồi quy tuyến tính nhiều biến 37 2.2.3 Định lý Bayes cho hồi quy tuyến tính nhiều biến 38 2.2.4 Phân phối dự báo cho quan sát tương lai 45 Lý thuyết tự hồi quy Bayes 45 2.3.1 Một số định nghĩa liên quan đến chuỗi thời gian 46 2.3.2 Bài toán tự hồi quy chuỗi thời gian 48 2.3.3 Giới thiệu tự hồi quy Bayes 48 Ứng dụng hồi quy Bayes vào toán dự báo 3.1 50 Dự báo lượng calo đốt cháy sau khoảng thời gian vận động 51 3.1.1 Giải theo phương pháp bình phương tối thiểu OLS 52 3.1.2 Giải theo phương pháp hồi quy tuyến tính Bayes 53 v 3.2 Bài toán dự báo nhiệt độ hàng ngày Melbourne, Australia 58 3.3 Ứng dụng hồi quy Bayes vào việc bổ khuyết liệu trống 66 Tài liệu tham khảo 77 Phụ lục 78 vi Danh sách bảng 1.1 Trọng số p 11 1.2 Khoảng tin Anna, Bart, Chris 15 3.1 Nhiệt độ dự báo so với nhiệt độ thực tế 63 3.2 Đối sánh nhiệt độ dự báo theo tự hồi quy, tự hồi quy Bayes nhiệt độ thực tế 65 3.3 Các bảng ghi liệu NHANES 67 vii Danh sách hình vẽ 1.1 Tiên nghiệm Anna, Bart, Chris 12 1.2 Hậu nghiệm Anna, Bart, Chris 12 1.3 Tiên nghiệm Arnie, Barb, Chuck 19 1.4 Hậu nghiệm Arnie, Barb, Chuck 20 2.1 Giả thiết phương sai 28 3.1 Lượng calo tiêu thụ (calo) tương ứng với thời gian tập thể dục (phút) 52 3.2 Phân phối tiên nghiệm β0 β1 54 3.3 Các thông số phân phối hậu nghiệm β0 β1 55 3.4 Biểu đồ biểu diễn phân phối xác suất hậu nghiệm β0 β1 trường hợp 500 điểm liệu 55 3.5 So sánh phương pháp OLS phương pháp hồi quy Bayes 500 điểm liệu 56 3.6 So sánh dự báo phương pháp OLS dự báo hồi quy Bayes Đường màu xanh thể hàm phân phối dự báo Đường màu đỏ thể giá trị dự báo phương pháp OLS Hai đường màu tím thể cận cận khoảng tin dự báo dùng hồi quy Bayes 56 viii 3.7 Các thông số phân phối hậu nghiệm trường hợp 15000 quan sát 57 3.8 Biểu đồ biểu diễn phân phối xác suất hậu nghiệm β0 β1 trường hợp 15000 điểm liệu 57 3.9 So sánh phương pháp OLS phương pháp hồi quy Bayes 15000 điểm liệu 58 3.10 So sánh dự báo phương pháp OLS dự báo hồi quy Bayes trường hợp 15000 điểm liệu 59 3.11 Nhiệt độ 10 năm Melbourne 60 3.12 Các giá trị tự tương quan sau độ trễ bậc p 61 3.13 Các giá trị tự tương quan theo dòng 62 3.14 Biểu đồ mô tả giá trị 63 3.15 Thông tin phân phối hậu nghiệm β0 , β1 , β2 , β3 64 3.16 Biểu đồ mô tả phân phối hậu nghiệm β0 , β1 , β2 , β3 64 3.17 Phân phối dự báo cho ngày tập test 66 3.18 Số lượng liệu thiếu bị thiếu cột liệu NHANES biểu thị màu đỏ, số lượng liệu tồn cột biểu thị màu vàng 69 3.19 Phân phối bmi 70 3.20 Phân phối chl 71 3.21 Biểu diễn phân phối hậu nghiệm bmi chl 73 3.22 Đồ thị marginal với 95% khoảng tin Bayes phân phối dự báo chl 74 3.23 Đồ thị marginal với 95% khoảng tin Bayes phân phối dự báo bmi 75 80 linear_regression.fit(np.array(X.Duration).reshape(-1,1),y) print(’Intercept from library:’, linear_regression.intercept_) print(’Slope from library:’, linear_regression.coef_[0]) # $ y = \beta_0 + \beta_1 X$ # $\beta_0 = -21.828102526050614$ # $\beta_1 = 7.16978334958784$ # In[9]: by_hand_coefs =[linear_regression.intercept_, linear_regression.coef_[0]] # In[10]: by_hand_coefs # # Bayesian Linear Regression # ### Model with 500 Observations # In[11]: y_pred_500 =np.array(linear_regression.intercept_ + linear_regression.coef_[0]*X["Duration"][:500]) # In[12]: y_true_500 =np.array(y[:500]) # In[14]: print(len(y_pred_500)) print(len(y_true_500)) # In[15]: def get_estimate_sigma(y_true, y_pred, num_data): sigma_square =np.sum((y_true -y_pred)**2)/(num_data-2) sigma = sigma_square**0.5 return sigma # In[17]: sigma_500 =get_estimate_sigma(y_true =y_true_500, y_pred =y_pred_500, num_data = len(y_true_500)) print(sigma_500) print(sigma_500**2) # #### Run the code to get the posterior distribution of $\beta_0$ and $\beta_1$ # In[19]: X_train500 =np.array(X.loc[0:499, ’Duration’]) # In[48]: with pm.Model() as linear_model_500: # Intercept 81 intercept =pm.Normal(’beta_0’, mu =0, sd =10) ## prior distribution # Slope slope = pm.Normal(’beta_1’, mu =0, sd =10) # Estimate of mean mean = intercept +slope *X_train500 # Observed values Y_obs = pm.Normal(’Y_obs’, mu =mean, sd =sigma_500, observed =y_true_500) ## likelihood # Sampler step = pm.NUTS() # Posterior distribution linear_trace_500 =pm.sample(1000, step, random_seed =0) # In[49]: ## visualize the posterior distribution of beta_0 and beta_1 az.plot_trace(linear_trace_500, figsize =(20, 10), compact =False, legend =True); # In[50]: ## show information of posterior distribution of beta_0 and beta_1 with linear_model_500: trace500_az =az.from_pymc3(linear_trace_500) az.summary(trace500_az) # In[57]: print(linear_trace_500["beta_0"].mean()) print(linear_trace_500["beta_0"].std()) # In[58]: print(linear_trace_500["beta_1"].mean()) print(linear_trace_500["beta_1"].std()) # In[113]: ## visualize the posterior distribution of beta_0 and beta_1 pm.plot_posterior(linear_trace_500, figsize =(40,10)); # In[63]: ## predict with x = 15.5 bayes_prediction500 =linear_trace_500[’beta_0’] +linear_trace_500[’beta_1’] *15.5 # In[107]: bayes_prediction500.mean() # In[114]: bayes_prediction500.std() 82 # In[119]: plt.figure(figsize =(16,10)) pm.plot_posterior_predictive_glm(linear_trace_500, samples =100, eval=np.linspace(2, 30, 100), linewidth =1, color = ’red’, alpha =0.8, label =’Bayesian Posterior Fits’, lm = lambda x, sample: sample[’beta_0’] +sample[’beta_1’] *x); plt.scatter(X[’Duration’], y.values, s =12, alpha =0.8, c =’blue’, label = ’Observations’) plt.plot(X_train500, by_hand_coefs[0] +X_train500 *by_hand_coefs[1], ’k ’, label = f’OLS Fit: y = {slope500_m:.4f}x + {Intercept500_m:.4f}’, linewidth =1.4) # plt.title(’predict ’, size = 20); plt.xlabel(’Duration (min)’, size =18); plt.ylabel(’Calories’, size =18); plt.grid() plt.legend(prop={’size’: 16}); # In[160]: print(bayes_prediction500.std()) # In[161]: # 95% credible interval for preidct for 15.5 low_500 =bayes_prediction500.mean() -1.96*bayes_prediction500.std() high_500 =bayes_prediction500.mean() +1.96*bayes_prediction500.std() # print((low_500, high_500)) print((round(low_500, 4), round(high_500, 4))) # In[126]: get_ipython().run_line_magic(’pinfo’, ’sns.kdeplot’) # In[139]: # visualize predictive distribution cho 15.5 plt.figure(figsize =(16,10)) plt.style.use(’fivethirtyeight’) sns.kdeplot(bayes_prediction500, label =’predict by Bayesian method’) plt.vlines(x =by_hand_coefs[0] +by_hand_coefs[1] *15.5, ymin = 0, ymax =0.5, label = ’predict by OLS’, colors =’red’, linestyles=’-.’) plt.vlines(x =low_500, 83 ymin = 0, ymax =0.1, label = ’Lower bound of credible interval’, colors =’purple’, linestyles=’-’) plt.vlines(x =high_500, ymin = 0, ymax =0.1, label = ’Upper bound of credible interval’, colors =’purple’, linestyles=’-’) plt.legend(); plt.xlabel(’Calo’, size =18) # plt.fill_between(bayes_prediction500, bayes_prediction500, where=(low_500 < bayes_prediction500) & (bayes_prediction500 < high_500)) # plt.ylabel(’Probability Density’, size = 18); # plt.title(’Posterior Prediction for 15.5 Minutes’, size = 20); plt.tick_params(labelleft=False, left=False) # # Model with 500 Observations # In[140]: y_pred_all =np.array(linear_regression.intercept_ + linear_regression.coef_[0]*X["Duration"]) y_true_all =np.array(y) # In[141]: print(len(y_pred_all)) print(len(y_true_all)) # In[142]: sigma_15000 =get_estimate_sigma(y_true =y_true_all, y_pred =y_pred_all, num_data = len(y_true_all)) print(sigma_15000) print(sigma_15000**2) # #### Run the code to get the posterior distribution of $\beta_0$ and $\beta_1$ # In[143]: X_train15000 =np.array(X[’Duration’]) # In[144]: with pm.Model() as linear_model: # Intercept intercept =pm.Normal(’beta_0’, mu =0, sd =10) ## prior distribution # Slope 84 slope = pm.Normal(’beta_1’, mu =0, sd =10) # Estimate of mean mean = intercept +slope *X_train15000 # Observed values Y_obs = pm.Normal(’Y_obs’, mu =mean, sd =sigma_15000, observed =y_true_all) ## likelihood # Sampler step = pm.NUTS() # Posterior distribution linear_trace =pm.sample(1000, step, random_seed =0) # In[145]: az.plot_trace(linear_trace, figsize =(20, 10), compact =False, legend =True) # In[146]: with linear_model: trace_az =az.from_pymc3(linear_trace) az.summary(trace_az) # In[147]: pm.plot_posterior(linear_trace, figsize =(40,10)); # In[149]: plt.figure(figsize =(16,10)) pm.plot_posterior_predictive_glm(linear_trace, samples =100, eval=np.linspace(2, 30, 100), linewidth =1, color = ’red’, alpha =0.8, label =’Bayesian Posterior Fits’, lm = lambda x, sample: sample[’beta_0’] +sample[’beta_1’] *x); plt.scatter(X[’Duration’], y.values, s =12, alpha =0.8, c =’blue’, label = ’Observations’) plt.plot(X[’Duration’], by_hand_coefs[0] +X[’Duration’] *by_hand_coefs[1], ’k ’, label =f’OLS Fit: y = {slope500_m:.4f}x + {Intercept500_m:.4f}’, linewidth =1.4) # plt.title(’Posterior Predictions with all Observations’, size = 20); plt.xlabel(’Duration (min)’, size = 18); plt.ylabel(’Calories’, size =18); plt.legend(prop={’size’: 16}); # In[150]: ## Predict for x = 15.5 bayes_prediction15000 =linear_trace[’beta_0’] +linear_trace[’beta_1’] *15.5 85 # In[163]: bayes_prediction15000.std() # In[164]: # 95% credible interval for preidct for 15.5 low_15000 =bayes_prediction15000.mean() -1.96*bayes_prediction15000.std() high_15000 =bayes_prediction15000.mean() +1.96*bayes_prediction15000.std() print((round(low_15000, 4), round(high_15000, 4))) # In[159]: plt.figure(figsize =(16,10)) plt.style.use(’fivethirtyeight’) sns.kdeplot(bayes_prediction15000, label =’Predict by Bayesian method’) plt.vlines(x =by_hand_coefs[0] +by_hand_coefs[1] *15.5, ymin = 0, ymax =2.5, label = ’Predict by OLS’, colors =’red’, linestyles=’-.’) plt.vlines(x =low_15000, ymin = 0, ymax =0.5, label = ’Lower bound of credible interval’, colors =’purple’, linestyles=’-’) plt.vlines(x =high_15000, ymin = 0, ymax =0.5, label = ’Upper bound of credible interval’, colors =’purple’, linestyles=’-’) plt.legend(); plt.xlabel(’Calo’, size =18), # plt.ylabel(’Probability Density’, size = 18); # plt.title(’Posterior Prediction for 15.5 Minutes’, size = 20); plt.tick_params(labelleft=False, left=False) # In[ ]: 86 Link liệu code toán dự báo nhiệt độ hàng ngày Melbourne, Australia ❼ Dữ liệu: https://github.com/Hoangvi96/example_hoangvi/tree/main /exercise_2/daily-min-temperatures.csv ❼ Code: https://github.com/Hoangvi96/example_hoangvi/tree/main/e xercise_2/code_example_2.ipynb #!/usr/bin/env python # coding: utf-8 # In[67]: # create and evaluate a static autoregressive model from pandas import read_csv from matplotlib import pyplot from statsmodels.tsa.ar_model import AutoReg from sklearn.metrics import mean_squared_error from math import sqrt import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression # Scipy for statistics import scipy import seaborn as sns import matplotlib.pyplot as plt # PyMC3 for Bayesian Inference import pymc3 as pm import arviz as az from pandas.plotting import autocorrelation_plot from statsmodels.graphics.tsaplots import plot_acf # ## by formula # In[2]: # load dataset series =read_csv(’daily-min-temperatures.csv’, header=0, index_col=0, parse_dates=True, squeeze=True) 87 # split dataset X = series.values train, test =X[1:len(X)-7], X[len(X)-7:] # In[4]: print("len(series):\t", len(series)) print("len(train):\t", len(train)) print("len(test):\t", len(test)) # In[63]: plt.figure(figsize= (30,10)) plt.plot(series) plt.grid() # In[65]: plt.figure(figsize= (16,10)) autocorrelation_plot(series) # In[68]: plt.rc("figure", figsize=(16,10)) plot_acf(series, lags=30) plt.grid() pyplot.show() # In[60]: # train autoregression model = AutoReg(train, lags=3) model_fit =model.fit() print(’Coefficients: %s’ % model_fit.params) # make predictions predictions =model_fit.predict(start=len(train), end=len(train)+len(test)-1, dynamic=False) for i in range(len(predictions)): print(’predicted=%f, expected=%f’ % (predictions[i], test[i])) rmse = sqrt(mean_squared_error(test, predictions)) print(’Test RMSE: %.3f’ % rmse) # plot results pyplot.figure(figsize =(16,5)) pyplot.plot(test, label ="ground truth value") pyplot.plot(predictions, color=’red’, label ="prediction value") pyplot.legend() 88 pyplot.grid() pyplot.show() # ## by hand # In[5]: def get_X_train(p,df_temp): #Generating the lagged p terms for i in range(1,p+1): df_temp[’Shifted_values_%d’ % i ]=df_temp[’Temp’].shift(i) df_temp =df_temp.dropna() #X contains the lagged values ,hence we skip the first column X_train =df_temp.iloc[:,1:].values.reshape(-1,p) y_train =df_temp.iloc[:,0].values.reshape(-1,1)[:,0] return X_train, y_train # In[6]: # create df_temp for processing X_train df_temp =pd.DataFrame({"Temp": train}) # In[7]: df_temp # In[8]: X_train, y_train =get_X_train(p =3,df_temp =df_temp) # lags = # In[10]: print("X_train:\t") print() print(X_train) # In[11]: print("y_train:\t") print() print(y_train) # In[12]: # get parameters of AR(3) reg = LinearRegression().fit(X_train, y_train) print(reg.intercept_) print(reg.coef_) # In[70]: def predict(timeseries, reg, times, lag): timeseries_cp =list(timeseries.copy()) 89 ls_predict =[] for i in range(times): res = np.dot(timeseries_cp[-lag:][::-1], reg.coef_) +reg.intercept_ res = round(res, 6) timeseries_cp.append(res) ls_predict.append(res) return timeseries_cp, ls_predict # ### create design matrix # In[14]: def get_X_design(X_train): vector_ones =(np.ones(len(X_train))) X_design =np.concatenate((np.expand_dims(vector_ones, 1), X_train), axis =1) return X_design # In[15]: X_design =get_X_design(X_train) print(X_design) # In[16]: def get_sigma_square(X_design, y_train, num_of_paras): H_matrix =np.matrix(X_design)*np.linalg.inv((np.matrix(X_design).T * np.matrix(X_design)))*np.matrix(X_design).T sigma_square =(np.matrix(y_train).T.T*(np.matrix(np.identity(len(H_matrix))) H_matrix)*np.matrix(y_train).T)[0,0]/(len(X_design) num_of_paras -1) return sigma_square # In[18]: sigma_square =get_sigma_square(X_design, y_train, num_of_paras =3) print("sigma_square:\t", sigma_square) # In[19]: sigma = sigma_square**0.5 # ## run model # In[28]: ls_para =["beta_0", "beta_1", "beta_2", "beta_3"] # In[29]: with pm.Model() as BAR_model: # Intercept beta_0 =pm.Normal(ls_para[0], mu =0, sd =10) 90 # Slope beta_1 =pm.Normal(ls_para[1], mu =0, sd =10) beta_2 =pm.Normal(ls_para[2], mu =0, sd =10) beta_3 =pm.Normal(ls_para[3], mu =0, sd =10) # Estimate of mean mean = beta_0 +beta_1*X_train[:,0] +beta_2*X_train[:,1] +beta_3*X_train[:,2] # Observed values Y_obs = pm.Normal(’Y_obs’, mu =mean, sd =sigma, observed =y_train) # Sampler step = pm.NUTS() # Posterior distribution BAR_trace =pm.sample(1000, step, random_seed =0) # In[30]: # plot posterior distribution az.plot_trace(BAR_trace, figsize =(20, 16), compact =False, legend =True); # In[31]: with BAR_model: trace_az =az.from_pymc3(BAR_trace) az.summary(trace_az) # In[32]: pm.plot_posterior(BAR_trace, figsize =(40,8)); # In[33]: def predict_distribution(timeseries, BAR_trace, ls_para, lags =3): ’’’ predict distribution of next observed ’’’ timeseries_cp =list(timeseries.copy()) res = BAR_trace[ls_para[0]] for p in range(1, len(ls_para)): res += BAR_trace[ls_para[p]]*timeseries_cp[-p] return res # In[35]: def predict_distribution_by_time(timeseries, BAR_trace, ls_para, lags =3, num_nextday =1): ls_res =[] timeseries_cp =list(timeseries.copy()) 91 for i in range(num_nextday): distribution_res =predict_distribution(timeseries_cp, BAR_trace, ls_para, lags) timeseries_cp.append(np.mean(distribution_res)) ls_res.append(distribution_res) return ls_res # In[34]: predict_distribution(train, BAR_trace, ls_para, lags =3) # In[36]: ls_res =predict_distribution_by_time(train, BAR_trace, ls_para, lags =3, num_nextday =7) # In[37]: ls_res # In[40]: ls_mean_of_ls_res =[res.mean() for res in ls_res] ls_std_of_ls_res =[res.std() for res in ls_res] # In[41]: ls_mean_of_ls_res # In[39]: ls_std_of_ls_res # In[56]: def get_credible_interval_of_predict_distribution(ls_res, Z_alpha_over_2): ls_credible_interval =[] for res in ls_res: low = res.mean() -Z_alpha_over_2*res.std() high = res.mean() +Z_alpha_over_2*res.std() ls_credible_interval.append((round(low, 4), round(high, 4))) return ls_credible_interval # In[57]: ls_credible_interval =get_credible_interval_of_predict_distribution(ls_res =ls_res, Z_alpha_over_2 =1.96) # In[58]: ls_credible_interval # In[77]: pyplot.figure(figsize =(16,10)) sns.kdeplot(ls_res[0], label =’Predict by Bayesian autoregressive’) pyplot.vlines(x =10.571406, 92 ymin = 0, ymax =5, label = ’Predict by autoregressive’, colors =’red’, linestyles=’-.’) plt.vlines(x =ls_credible_interval[0][0], ymin = 0, ymax =1, label = ’Lower bound of credible interval’, colors =’purple’, linestyles=’-’) plt.vlines(x =ls_credible_interval[0][1], ymin = 0, ymax =1, label = ’Upper bound of credible interval’, colors =’purple’, linestyles=’-’) pyplot.grid() pyplot.legend() pyplot.tick_params(labelleft=False, left=False) # In[ ]: Code mục Ứng dụng hồi quy Bayes vào việc bổ khuyết liệu trống ❼ Code: https://github.com/Hoangvi96/example_hoangvi/tree/main/e xercise_3 # Run block by block # -library(tidyverse) data("nhanes", package = "mice") head(nhanes)%>%knitr::kable() # -bar_missing % is.na %>% melt %>% ggplot(data = , aes(x = Var2)) + geom_bar(aes(y=( count ),fill=value),alpha=0.7,color="black")+ scale_fill_manual(values=c("gold","red3"),name = "", labels = c("Available","Missing"))+ theme_minimal()+ theme(axis.text.x = element_text(angle=45, vjust=0.5)) + labs(x = "Variables in Dataset", y = "Observations")+coord_flip() } nhanes%>%bar_missing() # -nhanes$bmi=as.numeric(nhanes$bmi) ggplot(nhanes,aes(x=bmi))+ geom_density(fill="red",alpha=0.5)+ theme_bw() # -ggplot(nhanes,aes(x=chl))+ geom_density(fill="blue",alpha=0.5)+ theme_bw() # -library(brms) bform

Ngày đăng: 31/10/2022, 21:37

Mục lục

    Kiến thức chuẩn bị

    Một số phân phối thường dùng

    Phân phối nhị thức

    Phân phối chuẩn (phân phối Gaussian)

    Suy luận Bayes cho tham số tỉ lệ của phân phối nhị thức

    Suy luận Bayes cho kỳ vọng của phân phối Gaussian

    Sử dụng tiên nghiệm đều

    Sử dụng tiên nghiệm chuẩn và hậu nghiệm

    Phương pháp hồi quy Bayes

    Hồi quy tuyến tính đơn biến

Tài liệu cùng người dùng

Tài liệu liên quan