无法在for循环中获取返回变量

时间:2019-06-24 10:20:59

标签: python jupyter-notebook graph-algorithm

我在Python 3.7中创建了以下函数:

def spectralClustering(nClusters, dataset):
    adjMatrix = createAdjacencyMatrix(dataset)
    dataset_time_per_iter = []
    labels = []
    for i in range(iterations):
        print('------ Executing Iteration', i+1, '------')
        time_start = time.perf_counter()
        sc = SpectralClustering(affinity='precomputed', n_clusters=nClusters, n_init=10,
          n_neighbors=5, random_state=0)
        sc.fit(adjMatrix)
        labels.append(sc.labels_)
        print(labels)
    dataset_time_per_iter.append(time.perf_counter() - time_start)
    round(np.mean(dataset_time_per_iter),2), "sec (based on", len(range(iterations)), "rounds)"
    print("Minimum execution time:", 
    round(np.min(dataset_time_per_iter),2), "sec \nMaximum execution time:", round(np.max(dataset_time_per_iter),2), "sec\n")
    return labels

for循环中的sc.labels_对象是一个numpy数组。当我在i=2步骤用print(labels)执行函数时,我在输出中看到的标签值为:

[array([0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32), array([0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)]

当我尝试执行print(labels)或在另一个函数中重用该变量时,出现错误:

name 'labels' is not defined

函数中的错误在哪里?我使用了错误的return语句吗?

0 个答案:

没有答案