【问题标题】:Returning numpy array returns NoneType返回 numpy 数组返回 NoneType
【发布时间】:2021-02-16 16:06:17
【问题描述】:

所以我有一个创建 numpy ndarray 的函数,我需要返回这个数组,但是当我这样做时,它在我调用它的另一个函数中给了我一个 NoneType,它看起来像这样:

def kMeans(dataSet, kMin, kMax):
    for k in range(kMin,kMax +1):
        centeroids = np.random.choice(dataSet, k)
        oldClusters = []
        clusters = np.array(findClosestCenteroids(dataSet, centeroids))

        finalizedClusters = kMeansAlgorithm(dataSet, centeroids, clusters, oldClusters, k)
        print(type(finalizedClusters))


def kMeansAlgorithm(dataset,centeroids, currCluster, oldCluster, k):
    idx = np.lexsort((currCluster[:, 0], currCluster[:, 1]))
    currentClusters = currCluster[idx]  
    change = np.array_equal(currentClusters, oldCluster)  
    oldClusters = np.copy(currentClusters)
    totalCount = 0
    for i in range(k): #vind het aantal items in een cluster
        count = np.count_nonzero(currentClusters == str(i)) 
        centeroids[i] = currentClusters[totalCount+ round(count/2)][0]
        totalCount = totalCount + count
    if change == True:
        print(type(currentClusters))
        return currentClusters
    print(change)
    newClusters = np.array(findClosestCenteroids(dataset, centeroids))
    kMeansAlgorithm(dataset, centeroids, newClusters, oldClusters, k)

现在打印出来了:

<class 'numpy.ndarray'>
<class 'NoneType'>
    

如何正确返回一个 numpy 数组?

【问题讨论】:

  • fun1末尾添加return array1?
  • 这没有足够的代码(并且有一个语法错误array 2)来看看有什么问题;您可以直接返回一个numpy数组,它会正常工作,所以您的代码中有一些错误!
  • 我还是想在 fun1 中使用 array1
  • 这能回答你的问题吗? return, return None, and no return at all?
  • 请显示实际代码。这里出现的内容有多个错别字;例如array1 = fun2(): 是一个语法错误。

标签: python numpy numpy-ndarray


【解决方案1】:

发现了问题,有一个递归函数,忘记了你总是需要返回函数而不是再次调用它

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 2021-12-08
    • 1970-01-01
    • 2012-03-31
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多