SuperAPI AI 工具集

cudf-analytics

数据与分析

查看项目

更新于 10-15 09:09

技能介绍

用途

cuDF Analytics 是一个用于 GPU 加速数据分析的技能,底层使用 NVIDIA RAPIDS cuDF。cuDF 提供类似 pandas 的 API,运行于 NVIDIA GPU 上,可对大型数据集实现大幅加速。

适用场景

该技能适用于以下任务:

  • 分析 CSV 文件、数据集或表格数据
  • 计算统计摘要(均值、中位数、标准差、四分位数)
  • 执行 groupby 聚合
  • 检测数据中的异常或离群值
  • 剖析包含数百万行的数据集
  • 计算相关性矩阵

使用方式

初始化(必需)

每个脚本都应以此样板代码开头。它会测试实际的 GPU 操作,而不仅仅是导入。

import pandas as pd

try:
    import cudf
    # Smoke-test: verify GPU compute AND host transfer both work
    _test = cudf.Series([1, 2, 3])
    assert _test.sum() == 6
    assert _test.to_pandas().tolist() == [1, 2, 3]
    GPU = True
except Exception as e:
    print(f"[GPU] cudf unavailable, falling back to pandas: {e}")
    GPU = False

def read_csv(path):
    return cudf.read_csv(path) if GPU else pd.read_csv(path)

def to_pd(df):
    """Convert cuDF DataFrame/Series to pandas. Use this instead of .to_pandas() directly."""
    if not GPU:
        return df
    try:
        return df.to_pandas()
    except Exception as e:
        print(f"[GPU] .to_pandas() failed, using Arrow fallback: {e}")
        return df.to_arrow().to_pandas()

快速参考

cuDF 与 pandas API 基本对应。常见操作如下:

读取数据:

df = read_csv("data.csv")

统计摘要:

# Use to_pd() when you need pandas output
summary = to_pd(df[["value", "score"]].describe())

# Scalar values work directly with float()
mean_val = float(df["value"].mean())
q1 = float(df["value"].quantile(0.25))

# Correlation
corr = float(df["value"].corr(df["score"]))

Groupby 聚合:

result = df.groupby("category").agg({
    "revenue": ["sum", "mean", "count"],
    "quantity": ["sum", "mean"],
})
result_pd = to_pd(result)

异常检测(IQR 方法):

col = "value"
Q1 = float(df[col].quantile(0.25))
Q3 = float(df[col].quantile(0.75))
IQR = Q3 - Q1
lower = Q1 - 1.5 * IQR
upper = Q3 + 1.5 * IQR
outliers = to_pd(df[(df[col] < lower) | (df[col] > upper)])

异常检测(Z-Score 方法):

mean = float(df[col].mean())
std = float(df[col].std())
df["z_score"] = (df[col] - mean) / std
anomalies = to_pd(df[df["z_score"].abs() > 3])

筛选与选择:

# Filter rows
filtered = df[df["status"] == "active"]

# Select columns
subset = df[["name", "revenue", "date"]]

# Sort
sorted_df = df.sort_values("revenue", ascending=False)

# Convert to pandas for final output / iteration
result_pd = to_pd(sorted_df)

数据类型要求

cuDF 需要显式指定类型以获得最佳性能:

  • 数值数据使用 float32 或 float64
  • 整数数据使用 int32 或 int64
  • 字符串列自动使用 cuDF 的字符串 dtype

输出建议

报告分析结果时:

  • 包含数据集维度(行数 x 列数)
  • 以格式化表格展示关键统计量
  • 突出值得注意的模式、趋势或异常
  • 同时提供摘要统计和具体示例
  • 注明任何数据质量问题(缺失值、离群值)

限制

资料未明确列出该技能的独立限制说明。可确定的一点是:当 cuDF 不可用或 GPU 操作失败时,样板代码会回退到 pandas,此时不再具备 GPU 加速能力。其余关于性能、平台或版本的边界信息暂未提供。