1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | # 2. Nhập thư viện và mô -đun Nhập khẩu Asnpnumpy asnp IMPREPPANDAS ASPDpandas aspd Fromsklearn.model_selection Nhập khẩuTrain_Test_Splitsklearn.model_selection importtrain_test_split FromskLearn Nhập trísklearn importpreprocessing Fromsklearn.Ensemble ImprTrandomforestreatoryorsklearn.ensemble importRandomForestRegressor Fromsklearn.Pipeline Nhập trí_pipelinesklearn.pipeline importmake_pipeline Fromsklearn.model_selection Nhập trí nghiên cứusklearn.model_selection import GridSearchCV Fromsklearn.Metrics nhập khẩusklearn.metrics importmean_squared_error,r2_score Nhập khẩuJOblibjoblib # 3. Tải dữ liệu rượu vang đỏ. dataset_url='//archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv'= '//archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv' data=pd.read_csv[dataset_url,sep=';']=pd.read_csv[dataset_url,sep=';'] # 4. Chia dữ liệu thành các bộ đào tạo và kiểm tra y=data.quality= data.quality X=data.drop['quality',axis=1]=data.drop['quality',axis=1] X_train,X_test,y_train,y_test=train_test_split[X,y,,X_test,y_train,y_test= train_test_split[X,y, test_size=0.2,test_size=0.2, random_state=123,random_state=123, stratify=y]stratify=y] # 5. Khai báo các bước tiền xử lý dữ liệu pipeline=make_pipeline[preprocessing.StandardScaler[],=make_pipeline[preprocessing.StandardScaler[], & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; RandomForestRestyor [n_estimators = 100,RandomForestRegressor[n_estimators=100, & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; Random_state = 123]]random_state=123]] # 6. Tuyên bố Hyperparameter để điều chỉnh hyperparameters={'randomforestregressor__max_features':['auto','sqrt','log2'],={'randomforestregressor__max_features':['auto','sqrt','log2'], 'randomforestregressor__max_depth':[None,5,3,1]}'randomforestregressor__max_depth': [None,5,3,1]} # 7. Mô hình điều chỉnh bằng đường ống xác thực chéo clf=GridSearchCV[pipeline,hyperparameters,cv=10]=GridSearchCV[pipeline,hyperparameters, cv=10] clf.fit[X_train,y_train].fit[X_train,y_train] # 8. Tái trang bị trên toàn bộ bộ đào tạo # Không cần mã bổ sung nếu clf.refit == true [mặc định là đúng] # 9. Đánh giá đường ống mô hình trên dữ liệu kiểm tra pred=clf.predict[X_test]= clf.predict[X_test] print[r2_score[y_test,pred]][r2_score[y_test,pred]] print[mean_squared_error[y_test,pred]][mean_squared_error[y_test,pred]] # 10. Lưu mô hình cho sử dụng trong tương lai joblib.dump[clf,'rf_regressor.pkl'].dump[clf,'rf_regressor.pkl'] # To Load: clf2 = joblib.load ['rf_reforyor.pkl']] |