在 Visual Studio Code 中使用 Microsoft Fabric 进行数据科学工作

你可以在 VS Code 中构建和开发适用于 Microsoft Fabric 的数据科学和数据工程解决方案。适用于 VS Code 的 Microsoft Fabric 扩展为使用 Fabric 项目、湖仓一体(Lakehouse)、笔记本和用户数据函数提供了集成的开发体验。

什么是 Microsoft Fabric?

Microsoft Fabric 是一个企业级端到端分析平台。它统一了数据移动、数据处理、摄取、转换、实时事件路由和报表构建。它通过数据工程、数据工厂、数据科学、实时智能、数据仓库和数据库等集成服务来支持这些功能。立即免费注册,体验 60 天的 Microsoft Fabric 服务——无需信用卡。

Diagram that shows what is Microsoft Fabric?

先决条件

在开始使用适用于 VS Code 的 Microsoft Fabric 扩展之前,你需要准备:

安装与设置

你可以从 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 特有的命令。

Diagram that shows all microsoft Fabric commands

Fabric 工作区和项资源管理器

Fabric 扩展为处理远程和本地 Fabric 项目提供了无缝衔接的方式。

  • 在 Fabric 扩展中,Fabric 工作区部分列出了来自远程工作区的所有项目,并按类型(湖仓一体、笔记本、流水线等)进行组织。
  • 在 Fabric 扩展中,本地文件夹部分显示了在 VS Code 中打开的 Fabric 项目文件夹。它反映了在 VS Code 中打开的每种类型项目的定义结构。这使你能够在本地进行开发,并将更改发布到当前或新的工作区。

Screenshot that shows how to view your workspaces and items?

将用户数据函数用于数据科学

  1. 在命令面板(⇧⌘P (Windows, Linux Ctrl+Shift+P))中,输入 Fabric: Create Item

  2. 选择你的工作区,然后选择 User data function(用户数据函数)。输入名称并选择 Python 语言。

  3. 系统会通知你设置 Python 虚拟环境,并继续在本地完成此设置。

  4. 使用 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
    
  5. 打开 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
    
  6. F5 在本地测试你的函数。

  7. 在 Fabric 扩展的本地文件夹中,选择该函数并发布到你的工作区。

    Screenshot that shows how to publish your user data functions item

了解有关调用函数的更多信息:

将 Fabric 笔记本用于数据科学

Fabric 笔记本是 Microsoft Fabric 中的交互式工作簿,用于并排编写和运行代码、可视化效果和 Markdown。笔记本支持多种语言(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 笔记本文档以了解更多信息。

Git 集成

Microsoft Fabric 支持 Git 集成,实现跨数据和分析项目的版本控制与协作。你可以将 Fabric 工作区连接到 Git 存储库(主要是 Azure DevOps 或 GitHub),并且仅同步受支持的项目。此集成还支持 CI/CD 工作流,使团队能够高效管理发布并维护高质量的分析环境。

GIF that shows how to use Git integration with User data functions

后续步骤

现在你已经在 VS Code 中配置好了 Microsoft Fabric 扩展,请探索以下资源以加深你的知识:

参与社区交流并获取支持:

© . This site is unofficial and not affiliated with Microsoft.