Python 超參數調校
Alex Scriven
Data Scientist
為何要學這門課?
你可能會對引擎蓋下的發現感到驚訝!
此資料集與信用卡違約有關。
包含臺灣部分消費者的財務歷史相關變數。共有 30,000 位使用者與 24 個屬性。
我們的建模目標是他們是否違約貸款。
資料已預先處理,有時會取較小樣本示範概念。
可在此找到更多資料集資訊:
https://archive.ics.uci.edu/ml/datasets/default+of+credit+card+clients
什麼是參數?
一個簡單的羅吉斯迴歸模型:
log_reg_clf = LogisticRegression() log_reg_clf.fit(X_train, y_train)print(log_reg_clf.coef_)
array([[-2.88651273e-06, -8.23168511e-03, 7.50857018e-04,
3.94375060e-04, 3.79423562e-04, 4.34612046e-04,
4.37561467e-04, 4.12107102e-04, -6.41089138e-06,
-4.39364494e-06, cont... ]])
整理係數:
# Get the original variable names original_variables = list(X_train.columns)# Zip together the names and coefficients zipped_together = list(zip(original_variables, log_reg_clf.coef_[0])) coefs = [list(x) for x in zipped_together]# Put into a DataFrame with column labels coefs = pd.DataFrame(coefs, columns=["Variable", "Coefficient"])
現在排序並列印前三大係數
coefs.sort_values(by=["Coefficient"], axis=0, inplace=True, ascending=False)
print(coefs.head(3))

要找出參數,我們需要:
參數會列在「Attributes」區段,非「parameters」區段!
那樹為基礎的演算法呢?
隨機森林沒有係數,只有節點決策(用哪個特徵、在哪個值切分)。
# A simple random forest estimator rf_clf = RandomForestClassifier(max_depth=2) rf_clf.fit(X_train, y_train)# Pull out one tree from the forest chosen_tree = rf_clf.estimators_[7]
為簡化,我們會直接展示決策樹的最終產物(圖片)。想更深入可自行探索所用套件(graphviz 與 pydotplus)。

我們可以擷取左側、倒數第二層節點的細節:
# Get the column it split on split_column = chosen_tree.tree_.feature[1] split_column_name = X_train.columns[split_column]# Get the level it split on split_value = chosen_tree.tree_.threshold[1]print("This node split on feature {}, at a value of {}" .format(split_column_name, split_value))
「This node split on feature PAY_0, at a value of 1.5」
Python 超參數調校