向量化目标函数来自 Networkx Graph 的列表

问题描述

我正在尝试对当前依赖于两个 for 循环的最大加权独立集问题矢量化一个目标函数

目前,它采用networkx图,节点权重存储为'node_weight'。这是我目前的代码,它给出了我试图最小化的客观值。

 

def mwis_objective(x,G):
    '''
    Takes in networkx graph  G and a bit string  x from the Qasm output and calculates the < psi | C | psi >
    Need to take note of the order of the bit string.
    '''
    array_of_x = np.array(list(x),dtype=int) # this takes the bit string 1001 to a numpy array for faster access
    objective = 0
    print(np.array(G.edges()))
    for i,j in G.edges():  # independent set
        if array_of_x[i] == 1 and  array_of_x[j] ==1:  # interconnecting nodes are independent set
            objective += 2

    # getting the maximum weight of nodes 
    node_weights = G.nodes(data='node_weight')  # this is how the node weight is stored in my graph attributes 
    just_weights = np.array([weight[1] for weight in node_weights]) #gets just the node weight and converts it to a np array 
    scale = np.amax(just_weights) # gets the maximum weight so the node weights are 
    scaled_weights = just_weights/scale  # used as J_i,j must be greater than weight of node; all node weights are scaled to below 0 and J_ij is put as 2


    for i in np.array(G.nodes()):  
        if array_of_x[i] == 1:
            objective -= scaled_weights[i]


    return objective

print(mwis_objective('111',weighted_path_graph(3,[5,5,5])))


位串作为字符串输入,对于长度为 3 的路径图,'101' 表示节点 0 和 2 在集合中,但节点 1 不在。 第一个 for 循环检查集合中的两个节点是否连接,如果是,则对目标函数施加 2 的惩罚。第二个 for 检查节点是否在集合中,如果是,则从目标中减去其缩放权重。

我能想到的向量化第二个和的最佳方法是使用 np.where 函数。如果有一种方法可以将其配置为给出一个 1 的数组,其中节点是该集合的成员,例如 in_set = [ 1 0 1 ] 这可以是 scaled_weights 数组的时间,然后求和为一个。不过,我不确定如何执行此操作,也无法想出对第一个 for 循环进行类似加速的方法

这是我的代码,它以我的格式生成 networkx 图。


def weighted_path_graph(number_of_nodes,graph_weights):
    """
    Creates a weighted path graph of default length three with different weights
    Graph_weights is a list with the desired node weights

    """


    path = nx.path_graph(number_of_nodes)
    #graph_weights=[1,3,1]
    for i in range(0,number_of_nodes):
        path.nodes[i]["node_weight"] = graph_weights[i]

    return path

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)