วิธีใช้ LLM สรุปเนื้อหาใน Scikit-Learn Pipelines ด้วย Scikit-LLM

Introduction
การใช้ตัวจำแนกประเภท (classifier) แบบ machine learning ดั้งเดิมที่มีน้ำหนักเบากับข้อความ มักจำเป็นต้องควบแน่นข้อความดิบที่ยาวและมี noise ให้กลายเป็นสัญญาณที่สะอาดเพื่อให้โมเดลทำงานได้แม่นยำ ดังนั้นจึงไม่ใช่เรื่องแปลกที่จะใช้ large language model (LLM) สำหรับ text summarization เพื่อเป็นขั้นตอนการเตรียมข้อมูล (preprocessing) ก่อนจะส่งข้อความไปยังโมเดลปลายทาง
จะดีแค่ไหนถ้าเราสามารถทำสิ่งนี้ได้อย่างราบรื่นในฐานะส่วนหนึ่งของ pipeline ดั้งเดิมที่ใช้ scikit-learn โดยที่การสรุปเนื้อหาด้วย LLM สามารถอยู่ร่วมกับการเตรียมข้อมูล การฝึกสอน และการอนุมานแบบดั้งเดิมได้? และที่สำคัญคือเราสามารถทำทั้งหมดนี้ได้โดยใช้เครื่องมือฟรีเท่านั้น
ในบทความนี้ เราจะเรียนรู้วิธีสร้างสถาปัตยกรรมที่ผสมผสาน Scikit-LLM estimators สำหรับสรุปเนื้อหาข้อความ เข้ากับวิธีการดั้งเดิมของ scikit-learn ให้เป็น pipeline เดียวกัน เพื่อสรุปและจำแนกประเภทข้อความดิบที่ซับซ้อน โดยนำจุดเด่นของทั้ง LLMs และโมเดล machine learning แบบคลาสสิกมารวมกัน
Integrating LLM-Driven Summarization in a Machine Learning Pipeline
ตัวอย่างนี้สามารถรันได้ทั้งหมดในโน้ตบุ๊ก Google Colab โดยใช้ LLM API ของ Groq เพื่อใช้งานโมเดลฟรี เงื่อนไขเบื้องต้นคือการเข้าไปที่ เว็บไซต์ Groq เพื่อลงทะเบียนและสร้าง API key จากนั้นให้นำไปวางเป็นตัวแปร "Secret" ใน Google Colab โดยตั้งชื่อว่า GROQ_API_KEY
หลังจากเตรียม API key เรียบร้อยแล้ว ให้เริ่มติดตั้ง Scikit-LLM ด้วยคำสั่งด้านล่าง:
!pip install scikit-llm -qขั้นตอนถัดไปใน Python คือการ กำหนดค่าสภาพแวดล้อม (configure the environment) เพื่อให้ Scikit-LLM ส่งคำขอผ่าน API ของ Groq แทนที่จะเป็น OpenAI API วิธีนี้ช่วยให้เราใช้โมเดลประสิทธิภาพสูงของ Groq ได้โดยไม่มีค่าใช้จ่ายต่อ token
from google.colab import userdata
from skllm.config import SKLLMConfig
# Retrieving API key and routing to Groq's free-tier OpenAI-compatible endpoint
groq_key = userdata.get('GROQ_API_KEY')
SKLLMConfig.set_gpt_url("https://api.groq.com/openai/v1")
SKLLMConfig.set_openai_key(groq_key)จากนั้นเราจะ นิยามข้อมูล "training" ซึ่งเป็นเอกสารขนาดเล็กพร้อมป้ายกำกับ (label) โดยตั้งใจให้ข้อความมีความยาวและมี noise เหมือนสถานการณ์จริง หากไม่มีการสรุปเนื้อหาล่วงหน้าเพื่อดึงสัญญาณสำคัญ การสร้างตัวแทนข้อมูลเชิงตัวเลขจะส่งต่อ noise ไปยังโมเดลอย่างหลีกเลี่ยงไม่ได้:
# Raw, lengthy documents and their corresponding class labels
X_long_texts = [
"The new solar panel technology efficiency has increased by 15% due to the novel perovskite layer, significantly lowering the barrier to entry for residential use and driving green energy adoption by making installations cheaper and faster than ever before.",
"Financial markets saw a sharp downturn today following the central bank's unexpected interest rate hike, leading to massive sell-offs in the tech sector and triggering volatility indices to reach their highest points in over three years.",
"The clinical trial for the new arthritis medication showed promising results, reducing joint swelling by 40% in the control group without severe side effects, awaiting FDA approval which could bring relief to millions suffering from autoimmune disorders."
]
y_labels = ["Energy", "Finance", "Healthcare"]ขั้นตอนสำคัญที่สุดคือการ นิยาม pipeline สามขั้นตอนสำหรับการจำแนกประเภท โดยใช้ GPTSummarizer เพื่อห่อหุ้มโมเดล openai/gpt-oss-20b ของ Groq จากนั้นจึงใช้ TF-IDF เพื่อสร้างตัวแทนข้อความจากสรุป และปิดท้ายด้วยการฝึกสอนโมเดล logistic regression
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from skllm.models.gpt.text2text.summarization import GPTSummarizer
# THREE-STEP MACHINE LEARNING PIPELINE FOR TEXT CLASSIFICATION, PRECEDED BY SUMMARIZATION
text_pipeline = Pipeline([
('summarizer', GPTSummarizer(
model="custom_url::openai/gpt-oss-20b",
max_words=20
)),
('vectorizer', TfidfVectorizer()),
('classifier', LogisticRegression())
])
# Fitting the entire pipeline end-to-end
text_pipeline.fit(X_long_texts, y_labels)สาเหตุที่การใช้ข้อมูลเพียงสามชุดได้ผลดี เป็นเพราะ LLM ทำหน้าที่เป็นตัวกรองที่แม่นยำ คอยควบแน่นเนื้อหาให้เหลือเพียงคำสำคัญที่ชัดเจน ทำให้งานของ vectorizer และโมเดลจำแนกประเภทกลายเป็นเพียงการจับคู่คำสำคัญที่เรียบง่าย
เราสามารถ ดูสรุปเนื้อหาที่สร้างขึ้น เพื่อตรวจสอบความถูกต้องได้ดังนี้:
# Inspecting the summaries of "training" examples, accessing the 'summarizer' object
train_summaries = text_pipeline.named_steps['summarizer'].transform(X_long_texts)
print("--- TRAINING DATA SUMMARIES ---")
for label, original, summary in zip(y_labels, X_long_texts, train_summaries):
print(f"[{label.upper()}]\nOriginal: {original}\nSummary: {summary}\n")ผลลัพธ์ (Output):
--- TRAINING DATA SUMMARIES ---
[ENERGY]
Original: The new solar panel technology efficiency has increased by 15% due to the novel perovskite layer, significantly lowering the barrier to entry for residential use and driving green energy adoption...
Summary: New perovskite solar panels boost efficiency by 15%, reducing costs and accelerating residential green energy adoption.
[FINANCE]
Original: Financial markets saw a sharp downturn today following the central bank's unexpected interest rate hike, leading to massive sell-offs in the tech sector and triggering volatility indices...
Summary: Markets plunged after unexpected rate hike, causing tech sell‑offs and high volatility.
[HEALTHCARE]
Original: The clinical trial for the new arthritis medication showed promising results, reducing joint swelling by 40% in the control group without severe side effects, awaiting FDA approval...
Summary: New arthritis drug trial reduces swelling by 40% with no severe side effects, pending FDA approval.เมื่อผลลัพธ์ออกมาเป็นที่น่าพอใจ เราจึงทดสอบด้วย ตัวอย่างสำหรับทดสอบ (test examples) เพื่อดูการทำงานของ pipeline ในการจำแนกประเภทข้อมูลใหม่ผ่านการสรุปเนื้อหาล่วงหน้า:
X_new = [
"A breakthrough mRNA vaccine targeting seasonal flu strains showed 85% efficacy across diverse patient demographics in stage 3 clinical trials, paving the way for a more robust global immune defense next winter.",
"Researchers have developed a grid-scale sodium-ion battery that promises to store surplus wind and solar power at a fraction of lithium's cost, potentially resolving the intermittency issue of renewables.",
"Stocks rallied in late trading as technology shares recovered from yesterday's losses, driven by strong earnings reports from major semiconductor manufacturers and optimistic GDP growth forecasts."
]
# The pipeline automatically summarizes, vectorizes, and classifies the unseen text
predictions = text_pipeline.predict(X_new)
# Access the intermediate summaries for the unseen data to display them
new_summaries = text_pipeline.named_steps['summarizer'].transform(X_new)
print("\n--- UNSEEN DATA PREDICTIONS ---")
for text, summary, prediction in zip(X_new, new_summaries, predictions):
print(f"Original Document: '{text}'")
print(f"Intermediate Summary: '{summary}'")
print(f"Final Predicted Category: {prediction}\n" + "-" * 70)ผลลัพธ์สุดท้ายที่ได้ถือว่าแม่นยำและมีประสิทธิภาพมาก:
--- UNSEEN DATA PREDICTIONS ---
Original Document: 'A breakthrough mRNA vaccine targeting seasonal flu strains showed 85% efficacy across diverse patient demographics in stage 3 clinical trials, paving the way for a more robust global immune defense next winter.'
Intermediate Summary: 'New mRNA flu vaccine achieved 85% efficacy in diverse patients, promising stronger global immunity next winter.'
Final Predicted Category: Healthcare
----------------------------------------------------------------------
Original Document: 'Researchers have developed a grid-scale sodium-ion battery that promises to store surplus wind and solar power at a fraction of lithium's cost, potentially resolving the intermittency issue of renewables.'
Intermediate Summary: 'New grid‑scale sodium‑ion battery can store excess wind/solar power cheaply, easing renewable intermittency.'
Final Predicted Category: Energy
----------------------------------------------------------------------
Original Document: 'Stocks rallied in late trading as technology shares recovered from yesterday's losses, driven by strong earnings reports from major semiconductor manufacturers and optimistic GDP growth forecasts.'
Intermediate Summary: 'Tech stocks rebound late, fueled by strong semiconductor earnings and hopeful GDP growth, boosting overall market rally.'
Final Predicted Category: Finance
----------------------------------------------------------------------Wrapping Up
Scikit-LLM ช่วยให้เราสามารถรวมความสามารถของ LLM เข้ากับ scikit-learn pipeline ได้โดยตรง การผสานพลังระหว่างการกลั่นกรองข้อความด้วย prompt สมัยใหม่เข้ากับโมเดลน้ำหนักเบาอย่าง TF-IDF และ Logistic Regression ทำให้ระบบโดยรวมทำงานได้อย่างรวดเร็วและประหยัดทรัพยากร
ความคิดเห็น (0)
เข้าสู่ระบบเพื่อร่วมแสดงความเห็น
สมัครสมาชิกมาเป็นคนแรกที่แสดงความเห็นกันเลยโบร
