開始使用免費開始

定義 Zhang 指標

一般來說,當我們要多次執行同一項任務時,會寫成一個函式,而不是每次都重新撰寫程式碼。在本練習中,我們要定義一個計算 Zhang 指標的函式,輸入前件與後件,輸出該指標本身。當下一章要解決的問題越來越複雜時,有一個方便的方式來計算指標,會大幅簡化流程。

注意,numpy 已以 np 匯入,pandas 已以 pd 匯入。另外,回顧以 support(支援度)計算表示的 Zhang 指標公式如下:

$$Zhang(A \rightarrow B) = $$ $$\frac{Support(A \& B) - Support(A) Support(B)}{ max[Support(AB) (1-Support(A)), Support(A)(Support(B)-Support(AB))]}$$

本練習屬於課程

Python 的 Market Basket Analysis

檢視課程

練習說明

  • 個別定義前件與後件的 support 值。
  • 定義 {antecedent, consequent} 的 support。
  • 完成分子與分母的表達式。
  • 完成 Zhang 指標的表達式。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Define a function to compute Zhang's metric
def zhang(antecedent, consequent):
	# Compute the support of each book
	supportA = antecedent.____
	supportC = consequent.____

	# Compute the support of both books
	supportAC = np.____(antecedent, consequent).____

	# Complete the expressions for the numerator and denominator
	numerator = supportAC - supportA*supportC
	denominator = ___(supportAC*(1-supportA), supportA*(supportC-supportAC))

	# Return Zhang's metric
	return numerator / denominator
編輯並執行程式碼