如何使用Cleanlab進行資料預處理?

如何使用Cleanlab進行資料預處理?

資料預處理對於機器學習的成功至關重要,但現實世界的資料集往往包含錯誤。使用 Cleanlab 進行資料預處理提供了一種高效的解決方案,它利用 Python 軟體包實現了自信學習演算法。透過自動檢測和糾正標籤錯誤,Cleanlab 簡化了機器學習中的資料預處理過程。透過使用統計方法識別有問題的資料點,Cleanlab 可以使用 Cleanlab Python 進行資料預處理,從而提高模型的可靠性。例如,Cleanlab 可簡化工作流程,以最小的投入提高機器學習的成果。

資料預處理為何重要?

資料預處理直接影響模型效能。帶有錯誤標籤、異常值和不一致性的不潔資料會導致糟糕的預測和不可靠的見解。在有缺陷的資料上訓練出來的模型會延續這些錯誤,在整個系統中產生不準確的連帶效應。高質量的預處理可以在建模開始前消除這些問題。

有效的預處理還能節省時間和資源。更乾淨的資料意味著更少的模型迭代、更快的訓練和更低的計算成本。預處理還能避免在除錯複雜模型時遇到的挫折,因為真正的問題在於資料本身。預處理將原始資料轉化為有價值的資訊,使演算法能夠有效地從中學習。

如何使用Cleanlab進行資料預處理?

Cleanlab 可以在訓練前清理和驗證資料。它能利用 ML 模型發現不良標籤、重複資料和低質量樣本。它最適用於標籤和資料質量檢查,而非基本的文字清理。

Cleanlab 的主要功能

  • 檢測錯誤標籤資料(噪聲標籤)
  • 標記重複資料和異常值
  • 檢查低質量或不一致樣本
  • 提供標籤分佈洞察
  • 與任何 ML 分類器配合使用,提高資料質量

現在,讓我們逐步介紹如何使用 Cleanlab。

第 1 步:安裝庫

在開始之前,我們需要安裝一些必要的庫。這些庫將幫助我們載入資料並順利執行 Cleanlab 工具。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
!pip install cleanlab
!pip install pandas
!pip install numpy
!pip install cleanlab !pip install pandas !pip install numpy
!pip install cleanlab
!pip install pandas
!pip install numpy
  • cleanlab:用於檢測標籤和資料質量問題。
  • pandas:用於讀取和處理 CSV 資料。
  • numpy:支援 Cleanlab 使用的快速數值計算。

第 2 步:載入資料集

現在,我們使用 Pandas 載入資料集,開始預處理。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import pandas as pd
# Load dataset
df = pd.read_csv("/content/Tweets.csv")
df.head(5)
import pandas as pd # Load dataset df = pd.read_csv("/content/Tweets.csv") df.head(5)
import pandas as pd
# Load dataset
df = pd.read_csv("/content/Tweets.csv")
df.head(5)
  • pd.read_csv():
  • df.head(5):

載入資料集

現在,一旦我們載入了資料。我們將只關注我們需要的列,並檢查是否有缺失值。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Focus on relevant columns
df_clean = df.drop(columns=['selected_text'], axis=1, errors='ignore')
df_clean.head(5)
# Focus on relevant columns df_clean = df.drop(columns=['selected_text'], axis=1, errors='ignore') df_clean.head(5)
# Focus on relevant columns
df_clean = df.drop(columns=['selected_text'], axis=1, errors='ignore')
df_clean.head(5)

如果 selected_text 列存在,則刪除該列;如果不存在,則避免出錯。有助於只保留必要的列進行分析。

檢查是否有缺失值

第 3 步:檢查標籤問題

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from cleanlab.dataset import health_summary
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import cross_val_predict
from sklearn.preprocessing import LabelEncoder
# Prepare data
df_clean = df.dropna()
y_clean = df_clean['sentiment'] # Original string labels
# Convert string labels to integers
le = LabelEncoder()
y_encoded = le.fit_transform(y_clean)
# Create model pipeline
model = make_pipeline(
TfidfVectorizer(max_features=1000),
LogisticRegression(max_iter=1000)
)
# Get cross-validated predicted probabilities
pred_probs = cross_val_predict(
model,
df_clean['text'],
y_encoded, # Use encoded labels
cv=3,
method="predict_proba"
)
# Generate health summary
report = health_summary(
labels=y_encoded, # Use encoded labels
pred_probs=pred_probs,
verbose=True
)
print("Dataset Summary:\n", report)
from cleanlab.dataset import health_summary from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import cross_val_predict from sklearn.preprocessing import LabelEncoder # Prepare data df_clean = df.dropna() y_clean = df_clean['sentiment'] # Original string labels # Convert string labels to integers le = LabelEncoder() y_encoded = le.fit_transform(y_clean) # Create model pipeline model = make_pipeline( TfidfVectorizer(max_features=1000), LogisticRegression(max_iter=1000) ) # Get cross-validated predicted probabilities pred_probs = cross_val_predict( model, df_clean['text'], y_encoded, # Use encoded labels cv=3, method="predict_proba" ) # Generate health summary report = health_summary( labels=y_encoded, # Use encoded labels pred_probs=pred_probs, verbose=True ) print("Dataset Summary:\n", report)
from cleanlab.dataset import health_summary
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import cross_val_predict
from sklearn.preprocessing import LabelEncoder
# Prepare data
df_clean = df.dropna()
y_clean = df_clean['sentiment']  # Original string labels
# Convert string labels to integers
le = LabelEncoder()
y_encoded = le.fit_transform(y_clean)
# Create model pipeline
model = make_pipeline(
TfidfVectorizer(max_features=1000),
LogisticRegression(max_iter=1000)
)
# Get cross-validated predicted probabilities
pred_probs = cross_val_predict(
model,
df_clean['text'],
y_encoded,  # Use encoded labels
cv=3,
method="predict_proba"
)
# Generate health summary
report = health_summary(
labels=y_encoded,  # Use encoded labels
pred_probs=pred_probs,
verbose=True
)
print("Dataset Summary:\n", report)
  • df.dropna():刪除有缺失值的行,確保訓練資料的乾淨。
  • LabelEncoder():將字串標籤(如“positive”、“negative”)轉換為整數標籤,以便與模型相容。
  • make_pipeline():建立帶有 TF-IDF 向量器(將文字轉換為數字特徵)和邏輯迴歸模型的管道。
  • cross_val_predict():執行 3 倍交叉驗證,並返回預測機率而非標籤。
  • health_summary():使用 Cleanlab 分析預測機率和標籤,識別潛在的標籤問題,如錯誤標籤。
  • print(report): 顯示健康摘要報告,突出顯示資料集中的任何標籤不一致或錯誤。

檢查標籤問題 檢查標籤問題

  • Label Issues:表示一個類別中有多少樣本的標籤可能不正確或含糊不清。
  • Inverse Label Issues:顯示預測標籤不正確(與真實標籤相反)的例項數量。
  • Label Noise:衡量每個類別中的噪聲(錯誤標籤或不確定性)程度。
  • Label Quality Score:反映一個類別中標籤的整體質量(分數越高表示質量越好)。
  • Class Overlap:確定不同類別之間重疊的示例數量,以及發生此類重疊的機率。
  • Overall Label Health Score:提供資料集標籤質量的總體指示(分數越高,表示標籤健康狀況越好)。

第 4 步:檢測低質量樣本

這一步涉及檢測和隔離資料集中可能存在標籤問題的樣本。Cleanlab 使用預測機率和真實標籤來識別低質量樣本,然後對其進行審查和清理。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Get low-quality sample indices
from cleanlab.filter import find_label_issues
issue_indices = find_label_issues(labels=y_encoded, pred_probs=pred_probs)
# Display problematic samples
low_quality_samples = df_clean.iloc[issue_indices]
print("Low-quality Samples:\n", low_quality_samples)
# Get low-quality sample indices from cleanlab.filter import find_label_issues issue_indices = find_label_issues(labels=y_encoded, pred_probs=pred_probs) # Display problematic samples low_quality_samples = df_clean.iloc[issue_indices] print("Low-quality Samples:\n", low_quality_samples)
# Get low-quality sample indices
from cleanlab.filter import find_label_issues
issue_indices = find_label_issues(labels=y_encoded, pred_probs=pred_probs)
# Display problematic samples
low_quality_samples = df_clean.iloc[issue_indices]
print("Low-quality Samples:\n", low_quality_samples)
  • find_label_issues():Cleanlab 中的一個函式,用於透過比較預測機率(pred_probs)和真實標籤(y_encoded),檢測存在標籤問題的樣本索引。
  • issue_indices:儲存被 Cleanlab 識別為存在潛在標籤問題(即低質量樣本)的樣本指數。
  • df_clean.iloc[issue_indices]:使用低質量樣本的索引從乾淨資料集 (df_clean) 中提取有問題的行。
  • low_quality_samples:儲存被識別為存在標籤問題的樣本,可對其進行進一步稽覈,以進行潛在的修正。

檢測低質量樣本

第 5 步:透過模型預測檢測噪聲標籤

這一步涉及使用 CleanLearning(一種 Cleanlab 方法),透過訓練模型和使用其預測來識別不一致或有噪聲標籤的樣本,從而檢測資料集中的噪聲標籤。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from cleanlab.classification import CleanLearning
from cleanlab.filter import find_label_issues
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
# Encode labels numerically
le = LabelEncoder()
df_clean['encoded_label'] = le.fit_transform(df_clean['sentiment'])
# Vectorize text data
vectorizer = TfidfVectorizer(max_features=3000)
X = vectorizer.fit_transform(df_clean['text']).toarray()
y = df_clean['encoded_label'].values
# Train classifier with CleanLearning
clf = LogisticRegression(max_iter=1000)
clean_model = CleanLearning(clf)
clean_model.fit(X, y)
# Get prediction probabilities
pred_probs = clean_model.predict_proba(X)
# Find noisy labels
noisy_label_indices = find_label_issues(labels=y, pred_probs=pred_probs)
# Show noisy label samples
noisy_label_samples = df_clean.iloc[noisy_label_indices]
print("Noisy Labels Detected:\n", noisy_label_samples.head())
from cleanlab.classification import CleanLearning from cleanlab.filter import find_label_issues from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import LabelEncoder # Encode labels numerically le = LabelEncoder() df_clean['encoded_label'] = le.fit_transform(df_clean['sentiment']) # Vectorize text data vectorizer = TfidfVectorizer(max_features=3000) X = vectorizer.fit_transform(df_clean['text']).toarray() y = df_clean['encoded_label'].values # Train classifier with CleanLearning clf = LogisticRegression(max_iter=1000) clean_model = CleanLearning(clf) clean_model.fit(X, y) # Get prediction probabilities pred_probs = clean_model.predict_proba(X) # Find noisy labels noisy_label_indices = find_label_issues(labels=y, pred_probs=pred_probs) # Show noisy label samples noisy_label_samples = df_clean.iloc[noisy_label_indices] print("Noisy Labels Detected:\n", noisy_label_samples.head())
from cleanlab.classification import CleanLearning
from cleanlab.filter import find_label_issues
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
# Encode labels numerically
le = LabelEncoder()
df_clean['encoded_label'] = le.fit_transform(df_clean['sentiment'])
# Vectorize text data
vectorizer = TfidfVectorizer(max_features=3000)
X = vectorizer.fit_transform(df_clean['text']).toarray()
y = df_clean['encoded_label'].values
# Train classifier with CleanLearning
clf = LogisticRegression(max_iter=1000)
clean_model = CleanLearning(clf)
clean_model.fit(X, y)
# Get prediction probabilities
pred_probs = clean_model.predict_proba(X)
# Find noisy labels
noisy_label_indices = find_label_issues(labels=y, pred_probs=pred_probs)
# Show noisy label samples
noisy_label_samples = df_clean.iloc[noisy_label_indices]
print("Noisy Labels Detected:\n", noisy_label_samples.head())
  • 標籤編碼(LabelEncoder()):將字串標籤(如“positive”、“negative”)轉換為數值,使其適用於機器學習模型。
  • 向量化(TfidfVectorizer()):使用 TF-IDF 將文字資料轉換為數值特徵,重點關注 “文字 ”列中最重要的 3000 個特徵。
  • 訓練分類器(LogisticRegression()):使用邏輯迴歸作為分類器,利用編碼標籤和向量化文字資料訓練模型。
  • CleanLearning (CleanLearning()):將 CleanLearning 應用於邏輯迴歸模型。該方法透過在訓練過程中考慮噪聲標籤來完善模型處理噪聲標籤的能力。
  • 預測機率 (predict_proba()):訓練完成後,模型會預測每個樣本的類機率,用於識別潛在的噪聲標籤。
  • find_label_issues():使用預測機率和真實標籤來檢測哪些樣本存在噪聲標籤(即可能的錯誤標籤)。
  • 顯示噪聲標籤:根據索引檢索並顯示帶有噪聲標籤的樣本,以便檢視並可能對其進行清理。

透過模型預測檢測噪聲標籤

觀察

輸出: 噪音標籤檢測

  • Cleanlab 會標記預測情感(來自模型)與提供標籤不匹配的樣本。
  • 舉例說明: 第 5 行被標記為中性,但模型認為可能不是。
  • 根據模型行為,這些樣本很可能被誤標或含糊不清。
  • 這有助於識別、重新標註或刪除有問題的樣本,以提高模型效能。

小結

預處理是構建可靠機器學習模型的關鍵。它能消除不一致、規範輸入並提高資料質量。但大多數工作流程都忽略了一點,那就是噪聲標籤。Cleanlab 填補了這一空白。它能自動檢測錯誤標籤資料、異常值和低質量樣本。無需人工檢查。這能讓你的資料集更乾淨,讓你的模型更智慧。

Cleanlab 預處理不僅能提高準確率,還能節省時間。透過儘早去除不良標籤,可以減少訓練負荷。更少的錯誤意味著更快的收斂。訊號更多,噪音更少。更好的模型,更少的工作量。

評論留言