首页 > 试题广场 >

为数据集行创建复合超向量

[编程题]为数据集行创建复合超向量
  • 热度指数:49 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
实现一个函数来生成数据集行的复合超向量(Composite Hypervector)。这是一个使用超维计算(HDC)的任务,需要通过以下步骤处理数据:

1. 为每个特征创建两个基本超向量:
- 一个表示特征名称
- 一个表示特征值
2. 使用绑定操作(bind)组合特征名称和值的超向量
3. 使用捆绑操作(bundle)将所有特征的超向量组合成一个复合超向量

输入描述:
第一行输入一个字典。
第二行输入一个整数,表示超向量的维度。
第三行输入一个字典,表示随机种子。


输出描述:
返回一个numpy数组,表示该行数据的复合超向量。
示例1

输入

{"feature1": 0.5, "feature2": -0.3}
4
{"feature1": 42, "feature2": 43}

输出

[1 1 1 1]

备注:
1.对应的输入、输出已给出,您只用实现核心功能函数即可。
2.支持numpy、scipy、pandas、scikit-learn库。
import numpy as np
import ast


def create_row_hv(row: dict, dim: int, random_seeds: dict):
    # Write your code here
    keys = row.keys()
    # 构造超向量
    vecs = np.array([gen_random_vecs(random_seeds[key], dim) for key in keys])
    # 进行 bind, 位乘操作
    binds = vecs[:, 0] * vecs[:, 1]
    # 进行 bundle, 将所有 bind 相加得到
    bundle = np.sum(binds, axis=0)
    # # 将 bundle 二值化
    return np.where(bundle >= 0, 1, -1)


def gen_random_vecs(seed: int, dim: int):
    # 通过指定种子随机生成向量
    np.random.seed(seed)
    return np.array((np.random.choice([-1, 1], dim), np.random.choice([-1, 1], dim)))


if __name__ == "__main__":
    row = ast.literal_eval(input())
    dim = int(input())
    random_seeds = ast.literal_eval(input())
    print(create_row_hv(row, dim, random_seeds))

面向 AC 编程说是……一点限定条件不给,还要用随机来构造超向量,没看题解根本搞不懂该怎么随机
发表于 2025-07-06 00:51:38 回复(0)