成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

漲知識!用邏輯規(guī)則進(jìn)行機(jī)器學(xué)習(xí)

人工智能 機(jī)器學(xué)習(xí)
在準(zhǔn)確率-召回率曲線上,同樣的點是用不同的坐標(biāo)軸繪制的。警告:左邊的第一個紅點(0%召回率,100%精度)對應(yīng)于0條規(guī)則。左邊的第二個點是第一個規(guī)則,等等。

Skope-rules使用樹模型生成規(guī)則候選項。首先建立一些決策樹,并將從根節(jié)點到內(nèi)部節(jié)點或葉子節(jié)點的路徑視為規(guī)則候選項。然后通過一些預(yù)定義的標(biāo)準(zhǔn)(如精確度和召回率)對這些候選規(guī)則進(jìn)行過濾。只有那些精確度和召回率高于其閾值的才會被保留。最后,應(yīng)用相似性過濾來選擇具有足夠多樣性的規(guī)則。一般情況下,應(yīng)用Skope-rules來學(xué)習(xí)每個根本原因的潛在規(guī)則。

圖片

項目地址:https://github.com/scikit-learn-contrib/skope-rules

  • Skope-rules是一個建立在scikit-learn之上的Python機(jī)器學(xué)習(xí)模塊,在3條款BSD許可下發(fā)布。
  • Skope-rules旨在學(xué)習(xí)邏輯的、可解釋的規(guī)則,用于 "界定 "目標(biāo)類別,即高精度地檢測該類別的實例。
  • Skope-rules是決策樹的可解釋性和隨機(jī)森林的建模能力之間的一種權(quán)衡。

圖片

schema

安裝

可以使用 pip 獲取最新資源:

pip install skope-rules

快速開始

SkopeRules 可用于描述具有邏輯規(guī)則的類:

from sklearn.datasets import load_iris
from skrules import SkopeRules

dataset = load_iris()
feature_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
clf = SkopeRules(max_depth_duplicatinotallow=2,
n_estimators=30,
precision_min=0.3,
recall_min=0.1,
feature_names=feature_names)

for idx, species in enumerate(dataset.target_names):
X, y = dataset.data, dataset.target
clf.fit(X, y == idx)
rules = clf.rules_[0:3]
print("Rules for iris", species)
for rule in rules:
print(rule)
print()
print(20*'=')
print()

圖片

注意:

如果出現(xiàn)如下錯誤:

圖片

解決方案:

關(guān)于 Python 導(dǎo)入錯誤 : cannot import name 'six' from 'sklearn.externals' ,云朵君在Stack Overflow上找到一個類似的問題:https://stackoverflow.com/questions/61867945/

解決方案如下

import six
import sys
sys.modules['sklearn.externals.six'] = six
import mlrose

親測有效!

如果使用“score_top_rules”方法,SkopeRules 也可以用作預(yù)測器:

from sklearn.datasets import load_boston
from sklearn.metrics import precision_recall_curve
from matplotlib import pyplot as plt
from skrules import SkopeRules

dataset = load_boston()
clf = SkopeRules(max_depth_duplicatinotallow=None,
n_estimators=30,
precision_min=0.2,
recall_min=0.01,
feature_names=dataset.feature_names)

X, y = dataset.data, dataset.target > 25
X_train, y_train = X[:len(y)//2], y[:len(y)//2]
X_test, y_test = X[len(y)//2:], y[len(y)//2:]
clf.fit(X_train, y_train)
y_score = clf.score_top_rules(X_test) # Get a risk score for each test example
precision, recall, _ = precision_recall_curve(y_test, y_score)
plt.plot(recall, precision)
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision Recall curve')
plt.show()

圖片

實戰(zhàn)案例

本案例展示了在著名的泰坦尼克號數(shù)據(jù)集上使用skope-rules。

skope-rules適用情況:

  • 解決二分類問題
  • 提取可解釋的決策規(guī)則

本案例分為5個部分

  • 導(dǎo)入相關(guān)庫
  • 數(shù)據(jù)準(zhǔn)備
  • 模型訓(xùn)練(使用ScopeRules().score_top_rules()方法)
  • 解釋 "生存規(guī)則"(使用SkopeRules().rules_屬性)。
  • 性能分析(使用SkopeRules.predict_top_rules()方法)。

導(dǎo)入相關(guān)庫

# Import skope-rules
from skrules import SkopeRules

# Import librairies
import pandas as pd
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, precision_recall_curve
from matplotlib import cm
import numpy as np
from sklearn.metrics import confusion_matrix
from IPython.display import display

# Import Titanic data
data = pd.read_csv('../data/titanic-train.csv')

數(shù)據(jù)準(zhǔn)備

# 刪除年齡缺失的行
data = data.query('Age == Age')
# 為變量Sex創(chuàng)建編碼值
data['isFemale'] = (data['Sex'] == 'female') * 1
# 未變量Embarked創(chuàng)建編碼值
data = pd.concat(
[data,
pd.get_dummies(data.loc[:,'Embarked'],
dummy_na=False,
prefix='Embarked',
prefix_sep='_')],
axis=1
)
# 刪除沒有使用的變量
data = data.drop(['Name', 'Ticket', 'Cabin',
'PassengerId', 'Sex', 'Embarked'],
axis = 1)
# 創(chuàng)建訓(xùn)練及測試集
X_train, X_test, y_train, y_test = train_test_split(
data.drop(['Survived'], axis=1),
data['Survived'],
test_size=0.25, random_state=42)
feature_names = X_train.columns

print('Column names are: ' + ' '.join(feature_names.tolist())+'.')
print('Shape of training set is: ' + str(X_train.shape) + '.')
Column names are: Pclass Age SibSp Parch Fare
isFemale Embarked_C Embarked_Q Embarked_S.
Shape of training set is: (535, 9).

模型訓(xùn)練

# 訓(xùn)練一個梯度提升分類器,用于基準(zhǔn)測試
gradient_boost_clf = GradientBoostingClassifier(random_state=42, n_estimators=30, max_depth = 5)
gradient_boost_clf.fit(X_train, y_train)

# 訓(xùn)練一個隨機(jī)森林分類器,用于基準(zhǔn)測試
random_forest_clf = RandomForestClassifier(random_state=42, n_estimators=30, max_depth = 5)
random_forest_clf.fit(X_train, y_train)

# 訓(xùn)練一個決策樹分類器,用于基準(zhǔn)測試
decision_tree_clf = DecisionTreeClassifier(random_state=42, max_depth = 5)
decision_tree_clf.fit(X_train, y_train)

# 訓(xùn)練一個 skope-rules-boosting 分類器
skope_rules_clf = SkopeRules(feature_names=feature_names, random_state=42, n_estimators=30,
recall_min=0.05, precision_min=0.9,
max_samples=0.7,
max_depth_duplicatinotallow= 4, max_depth = 5)
skope_rules_clf.fit(X_train, y_train)


# 計算預(yù)測分?jǐn)?shù)
gradient_boost_scoring = gradient_boost_clf.predict_proba(X_test)[:, 1]
random_forest_scoring = random_forest_clf.predict_proba(X_test)[:, 1]
decision_tree_scoring = decision_tree_clf.predict_proba(X_test)[:, 1]

skope_rules_scoring = skope_rules_clf.score_top_rules(X_test)

"生存規(guī)則" 的提取

# 獲得創(chuàng)建的生存規(guī)則的數(shù)量
print("用SkopeRules建立了" + str(len(skope_rules_clf.rules_)) + "條規(guī)則\n")

# 打印這些規(guī)則
rules_explanations = [
"3歲以下和37歲以下,在頭等艙或二等艙的女性。"
"3歲以上乘坐頭等艙或二等艙,支付超過26歐元的女性。"
"坐一等艙或二等艙,支付超過29歐元的女性。"
"年齡在39歲以上,在頭等艙或二等艙的女性。"
]
print('其中表現(xiàn)最好的4條 "泰坦尼克號生存規(guī)則" 如下所示:/n')
for i_rule, rule in enumerate(skope_rules_clf.rules_[:4])
print(rule[0])
print('->'+rules_explanations[i_rule]+ '\n')
用SkopeRules建立了9條規(guī)則。

其中表現(xiàn)最好的4條 "泰坦尼克號生存規(guī)則" 如下所示:

Age <= 37.0 and Age > 2.5
and Pclass <= 2.5 and isFemale > 0.5
-> 3歲以下和37歲以下,在頭等艙或二等艙的女性。

Age > 2.5 and Fare > 26.125
and Pclass <= 2.5 and isFemale > 0.5
-> 3歲以上乘坐頭等艙或二等艙,支付超過26歐元的女性。

Fare > 29.356250762939453
and Pclass <= 2.5 and isFemale > 0.5
-> 坐一等艙或二等艙,支付超過29歐元的女性。

Age > 38.5 and Pclass <= 2.5
and isFemale > 0.5
-> 年齡在39歲以上,在頭等艙或二等艙的女性。
def compute_y_pred_from_query(X, rule):
score = np.zeros(X.shape[0])
X = X.reset_index(drop=True)
score[list(X.query(rule).index)] = 1
return(score)

def compute_performances_from_y_pred(y_true, y_pred, index_name='default_index'):
df = pd.DataFrame(data=
{
'precision':[sum(y_true * y_pred)/sum(y_pred)],
'recall':[sum(y_true * y_pred)/sum(y_true)]
},
index=[index_name],
columns=['precision', 'recall']
)
return(df)

def compute_train_test_query_performances(X_train, y_train, X_test, y_test, rule):

y_train_pred = compute_y_pred_from_query(X_train, rule)
y_test_pred = compute_y_pred_from_query(X_test, rule)

performances = None
performances = pd.concat([
performances,
compute_performances_from_y_pred(y_train, y_train_pred, 'train_set')],
axis=0)
performances = pd.concat([
performances,
compute_performances_from_y_pred(y_test, y_test_pred, 'test_set')],
axis=0)

return(performances)


print('Precision = 0.96 表示規(guī)則確定的96%的人是幸存者。')
print('Recall = 0.12 表示規(guī)則識別的幸存者占幸存者總數(shù)的12%\n')

for i in range(4):
print('Rule '+str(i+1)+':')
display(compute_train_test_query_performances(X_train, y_train,
X_test, y_test,
skope_rules_clf.rules_[i][0])
)

Precision = 0.96 表示規(guī)則確定的96%的人是幸存者。
Recall = 0.12 表示規(guī)則識別的幸存者占幸存者總數(shù)的12%。

圖片

模型性能檢測

def plot_titanic_scores(y_true, scores_with_line=[], scores_with_points=[],
labels_with_line=['Gradient Boosting', 'Random Forest', 'Decision Tree'],
labels_with_points=['skope-rules']):
gradient = np.linspace(0, 1, 10)
color_list = [ cm.tab10(x) for x in gradient ]

fig, axes = plt.subplots(1, 2, figsize=(12, 5),
sharex=True, sharey=True)
ax = axes[0]
n_line = 0
for i_score, score in enumerate(scores_with_line):
n_line = n_line + 1
fpr, tpr, _ = roc_curve(y_true, score)
ax.plot(fpr, tpr, linestyle='-.', c=color_list[i_score], lw=1, label=labels_with_line[i_score])
for i_score, score in enumerate(scores_with_points):
fpr, tpr, _ = roc_curve(y_true, score)
ax.scatter(fpr[:-1], tpr[:-1], c=color_list[n_line + i_score], s=10, label=labels_with_points[i_score])
ax.set_title("ROC", fnotallow=20)
ax.set_xlabel('False Positive Rate', fnotallow=18)
ax.set_ylabel('True Positive Rate (Recall)', fnotallow=18)
ax.legend(loc='lower center', fnotallow=8)

ax = axes[1]
n_line = 0
for i_score, score in enumerate(scores_with_line):
n_line = n_line + 1
precision, recall, _ = precision_recall_curve(y_true, score)
ax.step(recall, precision, linestyle='-.', c=color_list[i_score], lw=1, where='post', label=labels_with_line[i_score])
for i_score, score in enumerate(scores_with_points):
precision, recall, _ = precision_recall_curve(y_true, score)
ax.scatter(recall, precision, c=color_list[n_line + i_score], s=10, label=labels_with_points[i_score])
ax.set_title("Precision-Recall", fnotallow=20)
ax.set_xlabel('Recall (True Positive Rate)', fnotallow=18)
ax.set_ylabel('Precision', fnotallow=18)
ax.legend(loc='lower center', fnotallow=8)
plt.show()

plot_titanic_scores(y_test,
scores_with_line=[gradient_boost_scoring, random_forest_scoring, decision_tree_scoring],
scores_with_points=[skope_rules_scoring]
)

圖片

在ROC曲線上,每個紅點對應(yīng)于激活的規(guī)則(來自skope-rules)的數(shù)量。例如,最低點是1個規(guī)則(最好的)的結(jié)果點。第二低點是2條規(guī)則結(jié)果點,等等。

在準(zhǔn)確率-召回率曲線上,同樣的點是用不同的坐標(biāo)軸繪制的。警告:左邊的第一個紅點(0%召回率,100%精度)對應(yīng)于0條規(guī)則。左邊的第二個點是第一個規(guī)則,等等。

從這個例子可以得出一些結(jié)論。

  • skope-rules的表現(xiàn)比決策樹好。
  • skope-rules的性能與隨機(jī)森林/梯度提升相似(在這個例子中)。
  • 使用4個規(guī)則可以獲得很好的性能(61%的召回率,94%的精確度)(在這個例子中)。
n_rule_chosen = 4
y_pred = skope_rules_clf.predict_top_rules(X_test, n_rule_chosen)

print('The performances reached with '+str(n_rule_chosen)+' discovered rules are the following:')
compute_performances_from_y_pred(y_test, y_pred, 'test_set')

圖片

predict_top_rules(new_data, n_r)方法用來計算對new_data的預(yù)測,其中有前n_r條skope-rules規(guī)則。

責(zé)任編輯:武曉燕 來源: 數(shù)據(jù)STUDIO
相關(guān)推薦

2024-07-10 11:26:18

2020-10-10 12:53:57

邏輯回歸機(jī)器學(xué)習(xí)分析

2018-01-22 10:52:43

前端CSS追蹤用戶

2014-06-17 09:55:24

機(jī)器學(xué)習(xí)

2022-06-05 21:16:08

機(jī)器學(xué)習(xí)Python

2022-06-09 09:14:31

機(jī)器學(xué)習(xí)PythonJava

2017-02-14 21:00:33

大數(shù)據(jù)機(jī)器學(xué)習(xí)廣告檢測

2021-04-21 10:47:48

機(jī)器學(xué)習(xí)邏輯回歸

2017-11-24 10:43:43

Madlib機(jī)器學(xué)習(xí)

2021-03-10 14:21:33

人工智能機(jī)器學(xué)習(xí)算法

2016-01-11 10:44:38

惡意軟件惡意軟件分析

2022-08-15 15:16:20

機(jī)器學(xué)習(xí)圖片深度學(xué)習(xí)

2020-12-25 15:24:24

人工智能

2019-09-30 10:12:21

機(jī)器學(xué)習(xí)數(shù)據(jù)映射

2021-06-17 10:27:03

人工智能AI機(jī)器學(xué)習(xí)

2024-04-17 08:00:00

2015-04-27 10:51:09

2021-07-29 13:06:29

Python機(jī)器學(xué)習(xí)編程語言

2020-12-23 07:54:56

Python機(jī)器學(xué)習(xí)邏輯回歸算法

2022-11-18 07:34:12

Docker項目目錄
點贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 国产成人福利 | 午夜av在线| 黄色一级免费 | 天天躁天天操 | 天天久| 精品久久国产 | 日韩在线不卡 | 中文字幕在线第二页 | 久久久久久久久久久久久久国产 | 男人的天堂久久 | 91精品在线播放 | 理论片午午伦夜理片影院 | 国产精品特级毛片一区二区三区 | 日韩精品免费一区二区在线观看 | 美女久久| 欧美综合久久 | 久久精品国产亚洲一区二区 | 在线免费观看成人 | 涩涩视频在线观看免费 | 国产精品一区三区 | 日韩字幕| a级黄色片视频 | 国产一级视频在线 | 久久精品—区二区三区 | 怡红院免费的全部视频 | 日韩精品一区二 | 中文字幕亚洲一区二区三区 | 一级片子 | av中文在线播放 | 2019天天干夜夜操 | 色又黄又爽网站www久久 | 久久久久综合 | 精品国产一区二区三区免费 | 先锋av资源网 | 天天色图 | 99久久久无码国产精品 | 久久久久久av | 午夜视频在线 | 一级黄在线观看 | 欧美色欧美亚洲另类七区 | 日韩一区在线播放 |