import torch


def transform_tensor_by_dict(tensor, map_dict, device="cpu"):
    """
    Given a tensor of any shape, map each of its value
    to map_dict[value].
    :param tensor: input tensor
    :param map_dict: value mapping dict. Both key and value are numbers
    :return: mapped tensor, type is FloatTensor
    """
    mapped_tensor = torch.FloatTensor(
        [map_dict[k] for k in tensor.reshape(-1).cpu().tolist()]
    ).reshape(tensor.shape).to(device)
    return mapped_tensor