kaggle中zillow比賽中模型融合的方法及其代碼

在機器學習這個領域,尤其是做多媒體(聲音、圖像、視頻)相關的機器學習方法研究,會涉及很多特征、分類模型(分類任務)的選擇。以聲音識別為例,常見的特征有MFCC、LPCC、spectrogram-like features 等,分類模型就很多了,有傳統的分類模型SVM、KNN、Random Forest,還有現在比較火的深度模型DNN、CNN、RNN等。而往往單特征、單模型很難取得理想的性能(performance)。那么,如何高效的利用不同的特征和模型?

一個重要的方法就是進行融合(fusion)。典型的fusion方法有early fusion和late fusion。顧名思義,early fusion就是在特征上(feature-level)進行融合,進行不同特征的連接(concatenate),輸入到一個模型中進行訓練;late fusion指的是在預測分數(score-level)上進行融合,做法就是訓練多個模型,每個模型都會有一個預測評分,我們對所有模型的結果進行fusion,得到最后的預測結果。常見的late fusion方法有取分數的平均值(average)、最大值(maximum)、加權平均(weighted average),另外還有采用Logistics Regression的方法進行late fusion。總之,方法很多,可視情況采取。

Fusion是一個提高模型性能的很好的方法,在參加kaggle比賽或者平時做項目上都是一個很常用的方法,尤其是像kaggle比賽這種比賽性質的,基本每一位參賽者的結果都是進行fusion后的結果,這里,模型融合也可以叫做ensemble,理解意思就好。

#
# import libariry
#import numpy as np
import pandas as pd
# data precession
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import KFold
# model
from xgboost import XGBRegressor
from lightgbm import LGBMRegressorfrom sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor, AdaBoostRegressor
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor#
#
#version 29 -> LB:0.6446
#   add more feature
#
#version 28 -> LB:0.6445
#   model params 'n_estimators' -> 100
#
# version 26 -> LB:0.6443
#   model params 'n_estimators' -> 50
#def load_data():train_2016 = pd.read_csv('../input/train_2016_v2.csv')train_2017 = pd.read_csv('../input/train_2017.csv')train = pd.concat([train_2016, train_2017], ignore_index=True)properties = pd.read_csv('../input/properties_2017.csv')sample = pd.read_csv('../input/sample_submission.csv')print("Preprocessing...")for c, dtype in zip(properties.columns, properties.dtypes):if dtype == np.float64:properties[c] = properties[c].astype(np.float32)print("Set train/test data...")id_feature = ['heatingorsystemtypeid','propertylandusetypeid', 'storytypeid', 'airconditioningtypeid','architecturalstyletypeid', 'buildingclasstypeid', 'buildingqualitytypeid', 'typeconstructiontypeid']for c in properties.columns:properties[c]=properties[c].fillna(-1)if properties[c].dtype == 'object':lbl = LabelEncoder()lbl.fit(list(properties[c].values))properties[c] = lbl.transform(list(properties[c].values))if c in id_feature:lbl = LabelEncoder()lbl.fit(list(properties[c].values))properties[c] = lbl.transform(list(properties[c].values))dum_df = pd.get_dummies(properties[c])dum_df = dum_df.rename(columns=lambda x:c+str(x))properties = pd.concat([properties,dum_df],axis=1)properties = properties.drop([c], axis=1)#print np.get_dummies(properties[c])## Add Feature## error in calculation of the finished living area of homeproperties['N-LivingAreaError'] = properties['calculatedfinishedsquarefeet'] / properties['finishedsquarefeet12']## Make train and test dataframe#train = train.merge(properties, on='parcelid', how='left')sample['parcelid'] = sample['ParcelId']test = sample.merge(properties, on='parcelid', how='left')# drop out oulierstrain = train[train.logerror > -0.4]train = train[train.logerror < 0.419]train["transactiondate"] = pd.to_datetime(train["transactiondate"])train["Month"] = train["transactiondate"].dt.monthtrain["quarter"] = train["transactiondate"].dt.quartertest["Month"] = 10test['quarter'] = 4x_train = train.drop(['parcelid', 'logerror','transactiondate', 'propertyzoningdesc', 'propertycountylandusecode'], axis=1)y_train = train["logerror"].valuesx_test = test[x_train.columns]del test, train    print(x_train.shape, y_train.shape, x_test.shape)return x_train, y_train, x_testx_train, y_train, x_test = load_data()class Ensemble(object):def __init__(self, n_splits, stacker, base_models):self.n_splits = n_splitsself.stacker = stackerself.base_models = base_modelsdef fit_predict(self, X, y, T):X = np.array(X)y = np.array(y)T = np.array(T)folds = list(KFold(n_splits=self.n_splits, shuffle=True, random_state=2016).split(X, y))S_train = np.zeros((X.shape[0], len(self.base_models)))S_test = np.zeros((T.shape[0], len(self.base_models)))for i, clf in enumerate(self.base_models):S_test_i = np.zeros((T.shape[0], self.n_splits))for j, (train_idx, test_idx) in enumerate(folds):X_train = X[train_idx]y_train = y[train_idx]X_holdout = X[test_idx]y_holdout = y[test_idx]print ("Fit Model %d fold %d" % (i, j))clf.fit(X_train, y_train)y_pred = clf.predict(X_holdout)[:]                S_train[test_idx, i] = y_predS_test_i[:, j] = clf.predict(T)[:]S_test[:, i] = S_test_i.mean(axis=1)# results = cross_val_score(self.stacker, S_train, y, cv=5, scoring='r2')# print("Stacker score: %.4f (%.4f)" % (results.mean(), results.std()))# exit()self.stacker.fit(S_train, y)res = self.stacker.predict(S_test)[:]return res# rf params
rf_params = {}
rf_params['n_estimators'] = 50
rf_params['max_depth'] = 8
rf_params['min_samples_split'] = 100
rf_params['min_samples_leaf'] = 30# xgb params
xgb_params = {}
#xgb_params['n_estimators'] = 50
xgb_params['min_child_weight'] = 12
xgb_params['learning_rate'] = 0.37
xgb_params['max_depth'] = 6
xgb_params['subsample'] = 0.77
xgb_params['reg_lambda'] = 0.8
xgb_params['reg_alpha'] = 0.4
xgb_params['base_score'] = 0
#xgb_params['seed'] = 400
xgb_params['silent'] = 1# lgb params
lgb_params = {}
#lgb_params['n_estimators'] = 50
lgb_params['max_bin'] = 8
lgb_params['learning_rate'] = 0.37 # shrinkage_rate
lgb_params['metric'] = 'l1'          # or 'mae'
lgb_params['sub_feature'] = 0.35    
lgb_params['bagging_fraction'] = 0.85 # sub_row
lgb_params['bagging_freq'] = 40
lgb_params['num_leaves'] = 512        # num_leaf
lgb_params['min_data'] = 500         # min_data_in_leaf
lgb_params['min_hessian'] = 0.05     # min_sum_hessian_in_leaf
lgb_params['verbose'] = 0
lgb_params['feature_fraction_seed'] = 2
lgb_params['bagging_seed'] = 3# XGB model
xgb_model = XGBRegressor(**xgb_params)# lgb model
lgb_model = LGBMRegressor(**lgb_params)# RF model
rf_model = RandomForestRegressor(**rf_params)# ET model
et_model = ExtraTreesRegressor()# SVR model
# SVM is too slow in more then 10000 set
#svr_model = SVR(kernel='rbf', C=1.0, epsilon=0.05)# DecsionTree model
dt_model = DecisionTreeRegressor()# AdaBoost model
ada_model = AdaBoostRegressor()stack = Ensemble(n_splits=5,stacker=LinearRegression(),base_models=(rf_model, xgb_model, lgb_model, et_model, ada_model))y_test = stack.fit_predict(x_train, y_train, x_test)from datetime import datetime
print("submit...")
pre = y_test
sub = pd.read_csv('../input/sample_submission.csv')
for c in sub.columns[sub.columns != 'ParcelId']:sub[c] = pre
submit_file = '{}.csv'.format(datetime.now().strftime('%Y%m%d_%H_%M'))
sub.to_csv(submit_file, index=False,  float_format='%.4f')

轉載于:https://blog.51cto.com/yixianwei/2156798

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/253844.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/253844.shtml
英文地址,請注明出處:http://en.pswp.cn/news/253844.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

靜態時序分析——Timing borrow

Timing Borrow技術又稱為cycle stealing技術&#xff0c;主要是利用latch的電平敏感特性&#xff0c;通過有效電平獲取數據&#xff0c;通過無效電平保持被鎖存的數據&#xff0c;主要用于解決路徑時序不滿足電路要求的情況。 通過TimingBorrow可以對電路進行加速,當路徑延遲較…

homebrew 常用命令

安裝&#xff08;需要 Ruby&#xff09;&#xff1a;ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/Go/install)" 搜索&#xff1a;brew search MySQL 查詢&#xff1a;brew info mysql 主要看具體的信息&#xff0c;比如目前的版本&#xff0c…

從Mysql某一表中隨機讀取n條數據的SQL查詢語句

若要在i ≤ R ≤ j 這個范圍得到一個隨機整數R &#xff0c;需要用到表達式 FLOOR(i RAND() * (j – i 1))。例如&#xff0c; 若要在7 到 12 的范圍&#xff08;包括7和12&#xff09;內得到一個隨機整數, 可使用以下語句&#xff1a; SELECT FLOOR(7 (RAND() * 6)); 以上摘…

基于MTD的NAND驅動開發(二)

基于MTD的NAND驅動開發(二) 基于MTD的NAND驅動開發(三) http://blog.csdn.net/leibniz_zsu/article/details/4977853 http://blog.csdn.net/leibniz_zsu/article/details/4977869 四、基于MTD的NAND 驅動架構 1 、platform_device 和platform_driver 的定義和注冊 對于我們的…

靜態時序分析——Data to data check

setup和hold的檢查也有可能發生在任意兩個數據端口&#xff0c;其中不包括時鐘端口。 我們將其中一個端口&#xff08;pin&#xff09;設置為約束端口&#xff08;constrainted pin&#xff09;&#xff0c;就像觸發器中的數據端口&#xff1b;將另一個一個端口&#xff08;pin…

開源數據庫中間件-MyCa初探與分片實踐

如今隨著互聯網的發展&#xff0c;數據的量級也是撐指數的增長&#xff0c;從GB到TB到PB。對數據的各種操作也是愈加的困難&#xff0c;傳統的關系性數據庫已經無法滿足快速查詢與插入數據的需求。這個時候NoSQL的出現暫時解決了這一危機。它通過降低數據的安全性&#xff0c;減…

【JAVA設計模式】外觀模式(Facade Pattern)

一 定義 為子系統中的一組接口提供一個一致的界面。Facade模式定義了一個高層的接口&#xff0c;這個接口使得這一子系統更加easy使用。二 案例 一個子系統中擁有3個模塊。每一個模塊中都有3個方法。當中一個為client調用方法&#xff0c;其它兩個則為各子模塊間互相調用方法…

return的用處

#include "stdio.h" main() {int a,b1,c0;for(a1;a<5;a){ cca;}printf("%d",c);return ;printf("hello word"); } 輸出結果是10并沒有hello word&#xff1b;return將不會執行下面的語句。轉載于:https://www.cnblogs.com/doublekai/p/6148…

靜態時序分析——Clock Gating check

門控時鐘是RTL級進行低功耗設計的最常用方法&#xff0c;能夠有效降低動態功耗。在實際使用中&#xff0c;一般用ICG&#xff08;集成門控時鐘單元&#xff09;來完成clock gating。ICG電路和時序如下&#xff1a; 通常來說&#xff0c;工藝庫已經集成了ICG&#xff0c;在做門控…

U-boot中TFTP 解釋

http://www.cnblogs.com/heaad/archive/2009/08/10/1542538.html

BlackHat Arsenal USA 2018 ToolsWatch黑客工具庫

原文鏈接&#xff1a;https://medium.com/hack-with-github/black-hat-arsenal-usa-2018-the-w0w-lineup-7de9b6d32796 Black Hat Arsenal USA 2018?—?The w0w lineup After the huge success of Black Hat Arsenal USA 2017, toolswatch has now announced the list of too…

SOA是什么

SOA是什么&#xff1f; SOA是面向服務的架構&#xff0c;是一個組件模型&#xff0c;它將應用程序的不同功能單元&#xff08;稱為服務&#xff09;通過這些服務之間定義良好的接口和契約聯系起來。接口是采用中立的方式進行定義的&#xff0c;它獨立于實現服務的硬件平臺、操作…

redis 優化

系統優化echo "vm.overcommit_memory1" > /etc/sysctl.conf 0&#xff0c; 表示內核將檢查是否有足夠的可用內存供應用進程使用&#xff1b;如果有足夠的可用內存&#xff0c;內存申請允許&#xff1b;否則&#xff0c;內存申請失敗&#xff0c;并把錯誤返回給應…

IC設計常見設計思想

速度與面積互換原則 所謂速度&#xff0c;是指整個工程穩定運行所能夠達到的最高時鐘頻率&#xff0c;它不僅和電路內部各個寄存器的建立時間、保持時間以及外部器件接口的各種時序要求有關&#xff0c;而且還和兩個緊鄰的寄存器間的邏輯延時&#xff0c;走線延時有關。所謂面…

DM365 u-boot啟動分析

http://www.61ic.com/Article/DaVinci/DM644X/201009/27429.html

(十三)Hibernate高級配置

配置數據庫連接池 配置C3P0連接池。先導入c3p0包。然后在hibernate.cfg.xml文件中 &#xff0c;使用下面代碼配置連接池<property name"hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>可以通過下面的…

eclipse中如何配置tomcat

1.打開eclipse上面的Windows選項&#xff0c;選擇Preferences>Server>Runtime Environments>Add 2.選擇你電腦中安裝的tomcat的版本我的是8所以我選的是Apache Tomcat v8.0 3,Next>Browse選擇Tomcat的安裝目錄&#xff0c;選擇jdk 4.Finish>OK tomcat配置完成。…

jsp調試小技巧

console.log($("#toolbar")); 打印對象可知道這個對象的參數信息轉載于:https://www.cnblogs.com/chenweida/p/6149342.html

數字IC驗證學習(一)

一、數據類型 1、logic logic類型只能有一個驅動。使用wire和reg的地方均可使用logic&#xff0c;但如雙向總線等有多個驅動的地方&#xff0c;則不可使用logic。 2、二值邏輯 對于二值邏輯變量與DUT中的四值邏輯變量連接時&#xff0c;如果DUT中產生了X和Z&#xff0c;會被…

SecureCRT 配置文件中 找密碼

打開本地電腦如下路徑 C:\Users\XXX\AppData\Roaming\VanDyke\Config\Sessions 找到配置文件。 運行命令&#xff1a;python SecureCRTDecrypt.py [配置文件名稱] 例如&#xff1a;python SecureCRTDecrypt.py 192.168.1.249.ini ssh root192.168.1.249 # 123456 即可得到密…