【发布时间】: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