Visual Studio Code を使用した Microsoft Fabric でのデータサイエンス
VS Code 内で Microsoft Fabric 向けのデータサイエンスおよびデータエンジニアリングソリューションを構築・開発できます。VS Code 用の Microsoft Fabric 拡張機能は、Fabric アーティファクト、レイクハウス、ノートブック、ユーザーデータ関数を操作するための統合開発環境を提供します。
Microsoft Fabric とは?
Microsoft Fabric は、エンタープライズ対応のエンドツーエンドの分析プラットフォームです。データの移動、処理、取り込み、変換、リアルタイムイベントルーティング、レポート作成を統合します。これらの機能は、データエンジニアリング、Data Factory、データサイエンス、リアルタイムインテリジェンス、データウェアハウス、データベースといった統合サービスによってサポートされています。無料でサインアップして、クレジットカード不要で 60 日間 Microsoft Fabric を体験してください。

前提条件
VS Code 用 Microsoft Fabric 拡張機能の使用を開始する前に、以下が必要です。
- Visual Studio Code: 最新の VS Code をインストールしてください。
- Microsoft Fabric アカウント: Microsoft Fabric ワークスペースへのアクセス権が必要です。開始するには、無料試用版にサインアップしてください。
- Python: VS Code で ノートブック や ユーザーデータ関数 を使用するには、Python 3.8 以降 をインストールしてください。
インストールとセットアップ
拡張機能は Visual Studio Marketplace から、または VS Code 内から直接検索してインストールできます。拡張機能ビュー (⇧⌘X (Windows, Linux Ctrl+Shift+X)) を選択し、Microsoft Fabric を検索してください。
使用する拡張機能
| 拡張機能 | 最適な用途 | 主な機能 | 以下のような場合に推奨 | ドキュメント |
|---|---|---|---|---|
| Microsoft Fabric 拡張機能 | 一般的なワークスペース管理、アイテム管理、およびアイテム定義の操作 | - Fabric アイテム(レイクハウス、ノートブック、パイプライン)の管理 - Microsoft アカウントのサインインとテナント切り替え - 統合またはグループ化されたアイテム表示 - IntelliSense を使用した Fabric ノートブックの編集 - コマンドパレット統合 ( Fabric: コマンド) |
VS Code から直接 Fabric のワークスペース、ノートブック、アイテムを管理したい場合。 | Fabric VS Code 拡張機能とは |
| Fabric ユーザーデータ関数 | カスタム変換およびワークフローを構築する開発者 | - Fabric でサーバーレス関数を作成 - ブレークポイントを使用したローカルデバッグ - データソース接続の管理 - Python ライブラリのインストール/管理 - Fabric ワークスペースへの関数の直接デプロイ |
自動化やデータ変換ロジックを構築し、VS Code からのデバッグとデプロイが必要な場合。 | VS Code でのユーザーデータ関数の開発 |
| Fabric データエンジニアリング | 大規模データと Spark を扱うデータエンジニア | - レイクハウス(テーブル、生ファイル)の探索 - Spark ノートブックの開発/デバッグ - Spark ジョブ定義の構築/テスト - ローカルの VS Code と Fabric 間でのノートブック同期 - スキーマとサンプルデータのプレビュー |
Spark、レイクハウス、または大規模データパイプラインを扱い、ローカルで探索、開発、デバッグしたい場合。 | VS Code での Fabric ノートブックの開発 |
はじめに
拡張機能をインストールしてサインインすると、Fabric ワークスペースとアイテムを操作できるようになります。コマンドパレット (⇧⌘P (Windows, Linux Ctrl+Shift+P)) で Fabric と入力すると、Microsoft Fabric 固有のコマンドが一覧表示されます。

Fabric ワークスペースとアイテムエクスプローラー
Fabric 拡張機能を使用すると、リモートおよびローカルの Fabric アイテムをシームレスに操作できます。
- Fabric 拡張機能の Fabric Workspaces セクションには、リモートワークスペース内のすべてのアイテムがタイプ別(レイクハウス、ノートブック、パイプラインなど)に分類されて表示されます。
- Fabric 拡張機能の Local folder セクションには、VS Code で開いている Fabric アイテムフォルダーが表示されます。これは VS Code で開かれている各タイプの Fabric アイテム定義構造を反映しており、ローカルで開発を行い、変更を現在または新規のワークスペースに公開できるようになります。

データサイエンスのためのユーザーデータ関数の利用
-
コマンドパレット (⇧⌘P (Windows, Linux Ctrl+Shift+P)) で、Fabric: Create Item と入力します。
-
ワークスペースを選択し、User data function を選択します。名前を入力し、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 拡張機能の Local folder で関数を選択し、ワークスペースに公開します。

関数の呼び出し方法については以下を参照してください。
データサイエンスのための Fabric ノートブックの利用
Fabric ノートブックは、Microsoft Fabric 上の対話型ワークブックで、コード、視覚化、Markdown を並べて記述・実行できます。ノートブックは複数の言語(Python、Spark、SQL、Scala など)をサポートしており、OneLake 上の既存データを使用して Fabric 内でデータ探索、変換、モデル開発を行うのに最適です。
例
以下のセルでは、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 ノートブック のドキュメントを参照してください。
Git の統合
Microsoft Fabric は Git 統合をサポートしており、データおよび分析プロジェクト全体でのバージョン管理とコラボレーションを可能にします。Fabric ワークスペースを Git リポジトリ(主に Azure DevOps または GitHub)に接続でき、サポートされているアイテムのみが同期されます。この統合は CI/CD ワークフローもサポートしており、チームが効率的にリリースを管理し、高品質な分析環境を維持できるようにします。

次のステップ
VS Code で Microsoft Fabric 拡張機能のセットアップが完了しました。知識を深めるために以下のリソースを確認してください。
コミュニティへの参加とサポートの利用