在 Visual Studio Code 中使用 Microsoft Fabric 進行資料科學
您可以在 VS Code 中建置並開發適用於 Microsoft Fabric 的資料科學與資料工程解決方案。VS Code 的 Microsoft Fabric 擴充功能提供了整合式的開發體驗,可用於處理 Fabric 成品、Lakehouse、Notebook 以及使用者資料函式。
什麼是 Microsoft Fabric?
Microsoft Fabric 是一個企業級的端對端分析平台。它統一了資料移動、資料處理、擷取、轉換、即時事件路由以及報表建置。它透過資料工程 (Data Engineering)、Data Factory、資料科學 (Data Science)、即時智慧 (Real-Time Intelligence)、資料倉儲 (Data Warehouse) 和資料庫 (Databases) 等整合服務來支援這些功能。立即免費註冊並體驗 Microsoft Fabric 60 天 — 無需信用卡。

先決條件
在開始使用適用於 VS Code 的 Microsoft Fabric 擴充功能之前,您需要:
- Visual Studio Code:安裝最新版本的 VS Code。
- Microsoft Fabric 帳戶:您需要存取 Microsoft Fabric 工作區。您可以註冊免費試用版以開始使用。
- Python:安裝 Python 3.8 或更新版本,以便在 VS Code 中使用 Notebook 和使用者資料函式。
安裝與設定
您可以從 Visual Studio Marketplace 或直接在 VS Code 中尋找並安裝擴充功能。請選取擴充功能檢視 (⇧⌘X (Windows, Linux Ctrl+Shift+X)),然後搜尋 Microsoft Fabric。
該使用哪些擴充功能
| 擴充功能 | 最適用於 | 主要功能 | 推薦給您,如果…… | 說明文件 |
|---|---|---|---|---|
| Microsoft Fabric 擴充功能 | 一般工作區管理、項目管理以及處理項目定義 | - 管理 Fabric 項目 (Lakehouse、Notebook、管線) - Microsoft 帳戶登入與租用戶切換 - 統一或分組的項目檢視 - 使用 IntelliSense 編輯 Fabric Notebook - 命令選擇區整合 ( Fabric: 命令) |
您希望透過單一擴充功能,直接在 VS Code 中管理 Fabric 的工作區、Notebook 和項目。 | 什麼是 Fabric VS Code 擴充功能 |
| Fabric 使用者資料函式 | 開發自訂轉換與工作流程的開發人員 | - 在 Fabric 中撰寫無伺服器函式 - 使用中斷點進行本機偵錯 - 管理資料來源連線 - 安裝/管理 Python 程式庫 - 將函式直接部署到 Fabric 工作區 |
您正在建置自動化或資料轉換邏輯,並需要從 VS Code 進行偵錯與部署。 | 在 VS Code 中開發使用者資料函式 |
| Fabric 資料工程 | 處理大規模資料與 Spark 的資料工程師 | - 瀏覽 Lakehouse (資料表、原始檔案) - 開發/偵錯 Spark Notebook - 建置/測試 Spark 作業定義 - 同步本機 VS Code 與 Fabric 之間的 Notebook - 預覽結構描述與範例資料 |
您正在使用 Spark、Lakehouse 或大規模資料管線,並希望在本地進行探索、開發與偵錯。 | 在 VS Code 中開發 Fabric Notebook |
入門指南
一旦安裝擴充功能並登入,您即可開始處理 Fabric 工作區與項目。在命令選擇區 (⇧⌘P (Windows, Linux Ctrl+Shift+P)) 中,輸入 Fabric 以列出 Microsoft Fabric 特有的命令。

Fabric 工作區與項目總管
Fabric 擴充功能提供了一種無縫的方式來處理遠端和本機的 Fabric 項目。
- 在 Fabric 擴充功能中,「Fabric 工作區」區段會列出遠端工作區中的所有項目,並依類型(Lakehouse、Notebook、管線等)進行組織。
- 在 Fabric 擴充功能中,「本機資料夾」區段顯示在 VS Code 中開啟的 Fabric 項目資料夾。它反映了在 VS Code 中開啟的每種類型之 Fabric 項目定義結構。這使您能夠在本地進行開發,並將變更發佈到目前或新的工作區。

針對資料科學使用使用者資料函式
-
在命令選擇區 (⇧⌘P (Windows, Linux Ctrl+Shift+P)) 中,輸入 Fabric: Create Item。
-
選擇您的工作區並選擇使用者資料函式。提供名稱並選擇 Python 語言。
-
系統會通知您設定 Python 虛擬環境,並繼續在本地進行設定。
-
使用
pip install安裝程式庫,或在 Fabric 擴充功能中選取使用者資料函式項目以新增程式庫。更新requirements.txt檔案以指定相依性。fabric-user-data-functions ~= 1.0 pandas == 2.3.1 numpy == 2.3.2 requests == 2.32.5 scikit-learn=1.2.0 joblib=1.2.0 -
開啟
functions_app.py。以下是使用 scikit-learn 進行資料科學開發使用者資料函式的範例。import datetime import fabric.functions as fn import logging # Import additional libraries import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import joblib udf = fn.UserDataFunctions() @udf.function() def train_churn_model(data: list, targetColumn: str) -> dict: ''' Description: Train a Random Forest model to predict customer churn using pandas and scikit-learn. Args: - data (list): List of dictionaries containing customer features and churn target Example: [{"Age": 25, "Income": 50000, "Churn": 0}, {"Age": 45, "Income": 75000, "Churn": 1}] - targetColumn (str): Name of the target column for churn prediction Example: "Churn" Returns: dict: Model training results including accuracy and feature information ''' # Convert data to DataFrame df = pd.DataFrame(data) # Prepare features and target numeric_features = df.select_dtypes(include=['number']).columns.tolist() numeric_features.remove(targetColumn) X = df[numeric_features] y = df[targetColumn] # Split and scale data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) # Train model model = RandomForestClassifier(n_estimators=100, random_state=42) model.fit(X_train_scaled, y_train) # Evaluate and save accuracy = accuracy_score(y_test, model.predict(X_test_scaled)) joblib.dump(model, 'churn_model.pkl') joblib.dump(scaler, 'scaler.pkl') return { 'accuracy': float(accuracy), 'features': numeric_features, 'message': f'Model trained with {len(X_train)} samples and {accuracy:.2%} accuracy' } @udf.function() def predict_churn(customer_data: list) -> list: ''' Description: Predict customer churn using trained Random Forest model. Args: - customer_data (list): List of dictionaries containing customer features for prediction Example: [{"Age": 30, "Income": 60000}, {"Age": 55, "Income": 80000}] Returns: list: Customer data with churn predictions and probability scores ''' # Load saved model and scaler model = joblib.load('churn_model.pkl') scaler = joblib.load('scaler.pkl') # Convert to DataFrame and scale features df = pd.DataFrame(customer_data) X_scaled = scaler.transform(df) # Make predictions predictions = model.predict(X_scaled) probabilities = model.predict_proba(X_scaled)[:, 1] # Add predictions to original data results = customer_data.copy() for i, (pred, prob) in enumerate(zip(predictions, probabilities)): results[i]['churn_prediction'] = int(pred) results[i]['churn_probability'] = float(prob) return results -
按 F5 在本地測試您的函式。
-
在 Fabric 擴充功能的「本機資料夾」中,選取該函式並發佈到您的工作區。

深入了解如何呼叫函式,請參考:
針對資料科學使用 Fabric Notebook
Fabric Notebook 是 Microsoft Fabric 中的互動式工作簿,用於並排撰寫與執行程式碼、視覺效果及 Markdown。Notebook 支援多種語言(Python、Spark、SQL、Scala 等),非常適合在 Fabric 中進行資料探索、轉換與模型開發,並能與您在 OneLake 中的現有資料協作。
範例
下方的儲存格使用 Spark 讀取 CSV,將其轉換為 pandas,並使用 scikit-learn 訓練邏輯迴歸模型。請將欄位名稱和路徑替換為您的資料集數值。
def train_logistic_from_spark(spark, csv_path):
# Read CSV with Spark, convert to pandas
sdf = spark.read.option("header", "true").option("inferSchema", "true").csv(csv_path)
df = sdf.toPandas().dropna()
# Adjust these to match your dataset
X = df[['feature1', 'feature2']]
y = df['label']
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
preds = model.predict(X_test)
return {'accuracy': float(accuracy_score(y_test, preds))}
# Example usage in a Fabric notebook cell
# train_logistic_from_spark(spark, '/path/to/data.csv')
請參閱 Microsoft Fabric Notebook 文件以了解詳情。
Git 整合
Microsoft Fabric 支援 Git 整合,可實現資料與分析專案的版本控制與協作。您可以將 Fabric 工作區連接到 Git 存放庫(主要是 Azure DevOps 或 GitHub),且僅同步支援的項目。此整合也支援 CI/CD 工作流程,使團隊能夠有效管理發行版本並維護高品質的分析環境。

後續步驟
現在您已在 VS Code 中設定好 Microsoft Fabric 擴充功能,請探索以下資源以加深您的知識:
參與社群並取得支援