① 求python大神解釋下這段代碼,沒接觸過python不會啊
這就是一段構造函數。
(self,
n_estimators=10,
criterion="gini",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_features="auto",
max_leaf_nodes=None,
bootstrap=True,
oob_score=False,
n_jobs=1,
random_state=None,
verbose=0,
warm_start=False,
class_weight=None):
這是構造函數的參數,有默認值。
super(RandomForestClassifier, self).__init__(
base_estimator=DecisionTreeClassifier(),
n_estimators=n_estimators,
estimator_params=("criterion", "max_depth", "min_samples_split",
"min_samples_leaf", "min_weight_fraction_leaf",
"max_features", "max_leaf_nodes",
"random_state"),
bootstrap=bootstrap,
oob_score=oob_score,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start,
class_weight=class_weight)
supper會調用基類構造函數,你可以認為這一串就是基類構造函數的參數。
self.criterion = criterion
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = max_features
self.max_leaf_nodes = max_leaf_nodes
這一串就是屬性賦值。
② 用python寫爬蟲程序怎麼調用工具包selenium
from selenium import webdriver # 用來驅動瀏覽器的
from selenium.webdriver import ActionChains # 破解滑動驗證碼的時候用的 可以拖動圖片
from selenium.webdriver.common.by import By # 按照什麼方式查找,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys # 鍵盤按鍵操作
from selenium.webdriver.support import expected_conditions as EC # 和下面WebDriverWait一起用的
from selenium.webdriver.support.wait import WebDriverWait # 等待頁面載入某些元素
③ 特徵篩選(隨機森林)
隨機森林能夠度量每個特徵的重要性,我們可以依據這個重要性指標進而選擇最重要的特徵。sklearn中已經實現了用隨機森林評估特徵重要性,在訓練好隨機森林模型後,直接調用feature_importan ces 屬性就能得到每個特徵的重要性。
一般情況下,數據集的特徵成百上千,因此有必要從中選取對結果影響較大的特徵來進行進一步建模,相關的方法有:主成分分析、lasso等,這里我們介紹的是通過隨機森林來進行篩選。
用隨機森林進行特徵重要性評估的思想比較簡單,主要是看每個特徵在隨機森林中的每棵樹上做了多大的貢獻,然後取平均值,最後比較不同特徵之間的貢獻大小。
貢獻度的衡量指標包括:基尼指數(gini)、袋外數據(OOB)錯誤率作為評價指標來衡量。
衍生知識點:權重隨機森林的應用(用於增加小樣本的識別概率,從而提高總體的分類准確率)
隨機森林/CART樹在使用時一般通過gini值作為切分節點的標准,而在加權隨機森林(WRF)中,權重的本質是賦給小類較大的權重,給大類較小的權重。也就是給小類更大的懲罰。權重的作用有2個,第1點是用於切分點選擇中加權計算gini值,表達式如下:
其中,N表示未分離的節點,N L 和N R 分別表示分離後的左側節點和右側節點,W i 為c類樣本的類權重,n i 表示節點內各類樣本的數量,Δi是不純度減少量,該值越大表明分離點的分離效果越好。
第2點是在終節點,類權重用來決定其類標簽,表達式如下:
參考文獻:隨機森林針對小樣本數據類權重設置 https://wenku..com/view/.html
這里介紹通過gini值來進行評價,我們將變數的重要性評分用VIM來表示,gini值用GI表示,假設有m個特徵X 1 ,X 2 ,...X c ,現在要計算出每個特徵X j 的gini指數評分VIM j ,即第j個特徵在隨機森林所有決策樹中節點分裂不純度的平均改變數,gini指數的計算公式如下表示:
其中,k表示有k個類別,p mk 表示節點m(將特徵m逐個對節點計算gini值變化量)中類別k所佔的比例。
特徵X j 在節點m的重要性,即節點m分枝前後的gini指數變化量為:
其中GI l 和GI r 分別表示分枝後兩個新節點的gini指數。
如果特徵X j 在決策樹i中出現的節點在集合M中,那麼X j 在第i棵樹的重要性為:
假設隨機森林共有n棵樹,那麼:
最後把所有求得的重要性評分進行歸一化處理就得到重要性的評分:
通過sklearn中的隨機森林返回特徵的重要性:
值得慶幸的是,sklearnsklearn已經幫我們封裝好了一切,我們只需要調用其中的函數即可。
我們以UCI上葡萄酒的例子為例,首先導入數據集。
然後,我們來大致看下這時一個怎麼樣的數據集
輸出為
可見共有3個類別。然後再來看下數據的信息:
輸出為
可見除去class label之外共有13個特徵,數據集的大小為178。
按照常規做法,將數據集分為訓練集和測試集。
好了,這樣一來隨機森林就訓練好了,其中已經把特徵的重要性評估也做好了,我們拿出來看下。
輸出的結果為
對的就是這么方便。
如果要篩選出重要性比較高的變數的話,這么做就可以
輸出為
瞧,這不,幫我們選好了3個重要性大於0.15的特徵了嗎~
[1] Raschka S. Python Machine Learning[M]. Packt Publishing, 2015.
[2] 楊凱, 侯艷, 李康. 隨機森林變數重要性評分及其研究進展[J]. 2015.
④ 如何在Wordpress中添加一段代碼
第一步:首先從網上下載出WordPress的插件Wp-syntax。
第二步:在編輯文章時,使用HTML的編輯方式插入以下代碼<pre lang=」LANGUAGE」 line=」0″>//「line為1時表示顯示行號」</pre>,中間插入要插入的代碼即可,LANGUAGE改為語言類型,例如php、java。line為0不顯示行號,為1時顯示。
附:支持的語言如下:abap, actionscript, actionscript3, ada, apache, applescript, apt_sources, asm, asp, autoit, avisynth, bash, bf, bibtex, blitzbasic, bnf, boo, c, c_mac, caddcl, cadlisp, cil, cfdg, cfm, cmake, cobol, cpp-qt, cpp, csharp, css, d, dcs, delphi, diff, div, dos, dot, eiffel, email, erlang, fo, fortran, freebasic, genero, gettext, glsl, gml, bnuplot, groovy, haskell, hq9plus, html4strict, idl, ini, inno, intercal, io, java, java5, javascript, kixtart, klonec, klonecpp, latex, lisp, locobasic, lolcode lotusformulas, lotusscript, lscript, lsl2, lua, m68k, make, matlab, mirc, mola3, mpasm, mxml, mysql, nsis, oberon2, objc, ocaml-brief, ocaml, oobas, oracle11, oracle8, pascal, per, pic16, pixelbender, perl, php-brief, php, plsql, povray, powershell, progress, prolog, properties, providex, python, qbasic, rails, rebol, reg, robots, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, sql, tcl, teraterm, text, thinbasic, tsql, typoscript, vb, vbnet, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, whois, winbatch, xml, xorg_conf, xpp, z80
⑤ 這段代碼是什麼意思這是python的一個腳本嗎,這裡面的call是什麼意思,求大神
看樣子是一個比較大的項目里的一個腳本。首先要明確這是一個windows的批處理腳本,並不是python腳本。
再大概看了下其內容,似乎是一個有關數據處理的軟體(BI即商業智能),這種類似軟體有可能會依賴於一些現有的數據處理庫(多半是python寫的),這個腳本的作用就是調用一些列工具把python代碼轉換成windows下的exe。
⑥ Python反斜杠小問題
原因很簡單。runoob只輸出runoob的原因是run[o]ob中的o並不是一個語法類型。
其次,ru oob中ru[ ]oob的 有一個換行的意思,所以結果是:
1-[ru
2-oob]
如果不想讓他換行,可以使用/。
類似於 (換行)的還有 (字元串制中)和 (這個還沒了解可以試驗一下)
都可以試試看看效果。
⑦ 跨考是考軟工還是cs,軟工比cs好考,補的也少,但是cs可以搞ai啊,怎麼選
其實軟工也可以搞AI的,現在人工智慧並不是只有CS出身才能搞。軟體工程的很多課程和計算機是接近的,甚至在一定程度上比計算機學的要深入。說實話,還是要看你自己在接下來的三年裡怎麼學,不管讀軟體還是CS,AI都要自己下功夫鑽研,畢竟現在國內高校的人工智慧專業都是剛剛起步。
另外,關於碼農30多歲容易被取代的問題,不要想著一個飯碗吃一輩子,有了經驗可以轉管理崗位或者自己創業搞事情,而且真的有了技術,你就是不可取代的。
⑧ Bagging(裝袋演算法)
In the previous passage, I talked about the conception of Decision Tree and its use. Although being very powerful model that can handle both regression and classification tasks, decision trees usually suffer from high variance . This means that if we split the dataset into two parts at random and fit a decision tree to the two halves, we will get quite different results. Thus we need one approach to rece variance at the expense of bias.
Bagging, which is designed for the context, is just the procere for recing the variance of weak models. In bagging , a random sample of data in the training set is selected with replacement - which means indivial data points can be chosen more than once - and then we fit a weak learner, such as a decision tree, to each of the sample data. Finally, we aggregate the predictions of base learners to get a more accurate estimate.
We build B distinct sample datasets from the train set using bootstrapped training data sets, and calculate the prediction using B separate training sets, and average them in order to obtain a low-variance statistical model:
While bagging can rece the variance for many models, it is particularly useful for decision trees. To apply bagging, we simply construct B separate bootstrapped training sets and train B indivial decision trees on these training sets. Each tree can grow very deep and not be pruned, thus they have high variance but low bias. Hence, averaging these trees can rece variance.
Bagging has three steps to complete: bootstraping, parallel training, and aggregating.
There are a number of key benefits for bagging, including:
The key disadvantages of bagging are:
Now we practice how to use bagging to improve the performance of models. The scikit-learn Python machine learning library provides easy access to the bagging method.
First, we use make_classification function to construct the classification dataset for practice of the bagging problem.
Here, we make a binary problem dataset with 1000 observations and 30 input features.
(2250, 30) (750, 30) (2250,) (750,)
To demonstrate the benefits of bagging model, we first build one decision tree and compare it to bagging model.
Now we begin construct an ensemble model using bagging technique.
Based on the result, we can easily find that the ensemble model reces both bias(higher accuracy) and variance(lower std). Bagging model's accuracy is 0.066 higher than that of one single decision tree.
Make Prediction
BaggingClasifier can make predictions for new cases using the function predict .
Then we build a bagging model for the regression model. Similarly, we use make_regression function to make a dataset about the regression problem.
As we did before, we still use repeated k-fold cross-validation to evaluate the model. But one thing is different than the case of classification. The cross-validation feature expects a utility function rather than a cost function. In other words, the function thinks being greater is better rather than being smaller.
The scikit-learn package will make the metric, such as neg_mean_squared_erro negative so that is maximized instead of minimized. This means that a larger negative MSE is better. We can add one "+" before the score.
The mean squared error for decision tree is and variance is .
On the other hand, a bagging regressor performs much better than one single decision tree. The mean squared error is and variance is . The bagging reces both bias and variance.
In this section, we explore how to tune the hyperparameters for the bagging model.
We demonstrate this by performing a classification task.
Recall that the bagging is implemented by building a number of bootstrapped samples, and then building a weak learner for each sample data. The number of models we build corresponds to the parameter n_estimators .
Generally, the number of estimators can increase constantly until the performance of the ensemble model converges. And it is worth noting that using a very large number of n_estimators will not lead to overfitting.
Now let's try a different number of trees and examine the change in performance of the ensemble model.
Number of Trees 10: 0.862 0.038
Number of Trees 50: 0.887 0.025
Number of Trees 100: 0.888 0.027
Number of Trees 200: 0.89 0.027
Number of Trees 300: 0.888 0.027
Number of Trees 500: 0.888 0.028
Number of Trees 1000: 0.892 0.027
Number of Trees 2000: 0.889 0.029
Let's look at the distribution of scores
In this case, we can see that the performance of the bagging model converges to 0.888 when we grow 100 trees. The accuracy becomes flat after 100.
Now let's explore the number of samples in bootstrapped dataset. The default is to create the same number of samples as the original train set.
Number of Trees 0.1: 0.801 0.04
Number of Trees 0.2: 0.83 0.039
Number of Trees 0.30000000000000004: 0.849 0.029
Number of Trees 0.4: 0.842 0.031
Number of Trees 0.5: 0.856 0.039
Number of Trees 0.6: 0.866 0.037
Number of Trees 0.7000000000000001: 0.856 0.033
Number of Trees 0.8: 0.868 0.036
Number of Trees 0.9: 0.866 0.025
Number of Trees 1.0: 0.865 0.035
Similarly, look at the distribution of scores
The rule of thumb is that we set the max_sample to 1, but this does not mean all training observations will be selected from the train set. Since we leverage bootstrapping technique to select data from the training set at random with replacement, only about 63% of training instances are sampled on average on each predictor, while the remaining 37% of training instances are not sampled and thus called out-of-bag instances.
Since the ensemble predictor never sees the oob samples ring training, it can be evaluated on these instances, without additional need for cross-validation after training. We can use out-of-bag evaluation in scikit-learn by setting oob_score=True .
Let's try to use the out-of-bag score to evaluate a bagging model.
According to this oob evaluation, this BaggingClassifier is likely to achieve about 87.6% accuracy on the test set. Let』s verify this:
The BaggingClassifier class supports sampling the features as well. This is controlled by two hyperparameters: max_features and bootstrap_features. They work the same way as max_samples and bootstrap, but for feature sampling instead of instance sampling. Thus, each predictor will be trained on a random subset of the input features.
The random sampling of features is particularly useful for high-dimensional inputs, such as images. Randomly sampling both features and instances is called Random Patches . On the other hand, keeping all instances( bootstrap=False,max_sample=1.0 ) and sampling features( bootstrap_features=True,max_features smaller than 1.0 ) is called Random Subspaces.
Random subspaces ensemble is an extension to bagging ensemble model. It is created by a subset of features in the training set. Very similar to Random Forest , random subspace ensemble is different from it in only two aspects:
Sampling features results in even more predictor diversity, trading a bit more bias for a lower variance.
Reference:
⑨ 數據挖掘實戰之隨機森林演算法使用
閱讀路線:
近來有同學問道,有沒有數據挖掘的案例可以來練習下,主要是來通過案例來知道演算法是如何使用的。
下面就以 港股打新 這個金融項目為例,來做個預測,先來說下什麼是打新;打新,就是用資金參與新股申購,如果中簽的話,就買到了即將上市的股票。
此次分析的目的是為了深入打新數據,找到最優演算法,挖掘出影響打新的關鍵因素,找到可能要破發的新股,從而減少新股破發的風險,提高盈利。
打新的本質,也即是在股票上市後賣出,賺取其中的差價。一般在買到的第一天就會賣掉,當然第一天上升的股票有漲有跌,為了能夠減少風險,會根據歷史數據來做個預判,這里把漲幅10%以下記為0,漲幅10%以上記為1,很明顯這也是二分類的預測問題
對於本項目而言,最終的評價標準是要求在精確度達到97%的情況下,最大化召回率。這里是要求盡可能提高召回率,自己本身對風險比較厭惡,寧可錯殺,也不會願意申購上市就要的破發的新股
對於評價標准,一般用的是PR曲線和ROC曲線。ROC曲線有一個突出優勢,就是不受樣本不均衡的影響 ROC曲線不受樣本不均衡問題的影響
1.數據總體情況
港股數據主要來自兩個方面, 利弗莫爾證券數據 和 阿思達克保薦人近兩年數據 ,處理之後是這樣的:
數據一共有17個特徵,除了目標變數is_profit,還有16個特徵。
以上的數據指標可以梳理為兩類,一類是股票相,如 關,一類是保薦人指標,
2.數據處理方面不用管
一般特徵工程主要從以下方面來進行:衍生特徵、異常值處理、缺失值處理、連續特徵離散化、分類變數one-hot-encode、標准化等,本篇文章主要講解隨機森林演算法使用,暫不對特徵工程做過多的展示了
從 使用隨機森林默認的參數 帶來的模型結果來看,auc指標是0.76,效果還可以。
為了更好的理解上述,這里有幾個知識點需要來解釋下:
返回的是一個n行k列的數組,第i行第j列上的數值是模型預測第i個預測樣本的標簽為j的概率。所以每一行的和應該等於1;本文中predict_proba(x_test)[:,1]返回的是標簽為0的概率。
(a).混淆矩陣
混淆矩陣如下圖分別用」0「和」1「代表負樣本和正樣本。FP代表實際類標簽為」0「,但預測類標簽為」1「的樣本數量。其餘,類似推理。
(b).假正率和真正率
假正率(False Positive Rate,FPR)是實際標簽為」0「的樣本中,被預測錯誤的比例。真正率(True Positive Rate,TPR)是實際標簽為」1「的樣本中,被預測正確的比例。其公式如下:
(3).ROC曲線
下圖的黑色線即為ROC曲線,ROC曲線是一系列threshold下的(FPR,TPR)數值點的連線。此時的threshold的取值分別為測試數據集中各樣本的預測概率。但,取各個概率的順序是從大到小的。然後也就是有了不同的RPR、TPR,且測試樣本中的數據點越多,曲線越平滑:
AUC(Area Under roc Cure),顧名思義,其就是ROC曲線下的面積,在此例子中AUC=0.62。AUC越大,說明分類效果越好。
下面我們來看看RF重要的Bagging框架的參數,主要有以下幾個:
(1) n_estimators:
也就是最大的弱學習器的個數。一般來說n_estimators太小,容易欠擬合,n_estimators太大,計算量會太大,並且n_estimators到一定的數量後,再增大n_estimators獲得的模型提升會很小,所以一般選擇一個適中的數值。默認是100。
(2) oob_score:
即是否採用袋外樣本來評估模型的好壞。默認識False。個人推薦設置為True,因為袋外分數反應了一個模型擬合後的泛化能力。
(3) criterion:
即CART樹做劃分時對特徵的評價標准。分類模型和回歸模型的損失函數是不一樣的。分類RF對應的CART分類樹默認是基尼系數gini,另一個可選擇的標準是信息增益。回歸RF對應的CART回歸樹默認是均方差mse,另一個可以選擇的標準是絕對值差mae。一般來說選擇默認的標准就已經很好的。
從上面可以看出,RF重要的框架參數比較少,主要需要關注的是 n_estimators ,即RF最大的決策樹個數。
下面我們再來看RF的決策樹參數,它要調參的參數如下:
(1) RF劃分時考慮的最大特徵數max_features:
(2) 決策樹最大深度max_depth:
默認可以不輸入,如果不輸入的話,決策樹在建立子樹的時候不會限制子樹的深度。一般來說,數據少或者特徵少的時候可以不管這個值。如果模型樣本量多,特徵也多的情況下,推薦限制這個最大深度,具體的取值取決於數據的分布。常用的可以取值10-100之間。
(3) 內部節點再劃分所需最小樣本數min_samples_split:
這個值限制了子樹繼續劃分的條件,如果某節點的樣本數少於min_samples_split,則不會繼續再嘗試選擇最優特徵來進行劃分。默認是2.如果樣本量不大,不需要管這個值。如果樣本量數量級非常大,則推薦增大這個值。
(4) 葉子節點最少樣本數min_samples_leaf:
這個值限制了葉子節點最少的樣本數,如果某葉子節點數目小於樣本數,則會和兄弟節點一起被剪枝。 默認是1,可以輸入最少的樣本數的整數,或者最少樣本數占樣本總數的百分比。如果樣本量不大,不需要管這個值。如果樣本量數量級非常大,則推薦增大這個值。
(5)葉子節點最小的樣本權重和min_weight_fraction_leaf:
這個值限制了葉子節點所有樣本權重和的最小值,如果小於這個值,則會和兄弟節點一起被剪枝。 默認是0,就是不考慮權重問題。一般來說,如果我們有較多樣本有缺失值,或者分類樹樣本的分布類別偏差很大,就會引入樣本權重,這時我們就要注意這個值了。
(6) 最大葉子節點數max_leaf_nodes:
通過限制最大葉子節點數,可以防止過擬合,默認是"None」,即不限制最大的葉子節點數。如果加了限制,演算法會建立在最大葉子節點數內最優的決策樹。如果特徵不多,可以不考慮這個值,但是如果特徵分成多的話,可以加以限制,具體的值可以通過交叉驗證得到。
(7) 節點劃分最小不純度min_impurity_split:
這個值限制了決策樹的增長,如果某節點的不純度(基於基尼系數,均方差)小於這個閾值,則該節點不再生成子節點。即為葉子節點 。一般不推薦改動默認值1e-7。
上面決策樹參數中最重要的包括最大特徵數 max_features , 最大深度 max_depth , 內部節點再劃分所需最小樣本數 min_samples_split 和葉子節點最少樣本數 min_samples_leaf
GridSearchCV的名字其實可以拆分為兩部分,GridSearch和CV,即網格搜索和交叉驗證。這兩個名字都非常好理解。網格搜索,搜索的是參數,即在指定的參數范圍內,按步長依次調整參數,利用調整的參數訓練學習器,從所有的參數中找到在驗證集上精度最高的參數,這其實是一個訓練和比較的過程。
GridSearchCV可以保證在指定的參數范圍內找到精度最高的參數,但是這也是網格搜索的缺陷所在,他要求遍歷所有可能參數的組合,在面對大數據集和多參數的情況下,非常耗時。
通過RF框架以及RF決策樹參數能夠了解到重點需要調節以下的參數
主要需要關注的是 n_estimators ,即RF最大的決策樹個數。
決策樹參數中最重要的包括最大特徵數 max_features , 最大深度 max_depth , 內部節點再劃分所需最小樣本數 min_samples_split 和葉子節點最少樣本數 min_samples_leaf
輸出結果為:
6.3最佳的弱學習器迭代次數,接著我們對決策樹最大深度max_depth和內部節點再劃分所需最小樣本數min_samples_split進行網格搜索
輸出結果
6.4最大特徵數max_features做調參
輸出結果:
6.5根據模型最佳參數進行測試
輸出結果:0.7805947388486466,相比沒有調參前,模型有不少的提高的,方便觀察,用圖形來看下ROC曲線圖
6.6觀察模型的重要特徵
6.7最大召回率
最後得出我們想要的結果,精準率在 0.97 下,召回率 0.046
參考文章:
1.sklearn中predict_proba的用法例子
2.Python機器學習筆記 Grid SearchCV(網格搜索)
3.scikit-learn隨機森林調參小結
4.ROC曲線和AUC值的計算