Python if语句中的函数调用把我搞砸了吗?

Python if语句中的函数调用把我搞砸了吗?,python,function,numpy,k-means,Python,Function,Numpy,K Means,我一直在做一个家庭作业来实现K-Means聚类 从头开始的算法。我正在对鸢尾花数据集进行聚类。 在程序开始时,系统会提示用户输入 他们想要的质心(簇)。然后,程序创建一个范围以 选择“从”可基于文件中的数据创建质心 我遇到了“空切片平均值”错误的问题,所以我决定 尝试使用另一个while循环和条件语句来控制所有这些。 基本上防止我出错。它检查是否所有的 质心是好的,如果不是,就生成新的质心。但我看到在这个过程中,重心正在丢失。发生了什么事 Python代码: import numpy as np

我一直在做一个家庭作业来实现K-Means聚类 从头开始的算法。我正在对鸢尾花数据集进行聚类。 在程序开始时,系统会提示用户输入 他们想要的质心(簇)。然后,程序创建一个范围以 选择“从”可基于文件中的数据创建质心

我遇到了“空切片平均值”错误的问题,所以我决定 尝试使用另一个while循环和条件语句来控制所有这些。 基本上防止我出错。它检查是否所有的 质心是好的,如果不是,就生成新的质心。但我看到在这个过程中,重心正在丢失。发生了什么事

Python代码:

import numpy as np
from pprint import pprint
import random
import sys

dataPointsFromFile = np.array(np.loadtxt('iris.txt', delimiter = ','))

NoOfCentroids = input('How Many Centrouds? ')
创建质心所处的范围

dataRange = ([])
dataRange.append(round(np.amin(dataPointsFromFile),1))
dataRange.append(round(np.amax(dataPointsFromFile),1))
dataRange = np.asarray(dataRange)

dataPoints = np.array(dataPointsFromFile)

centroids = 0
函数生成质心

def CentroidMaker(number):
    global centroids
    centroids = 0
    i=0
    randomCentroids = []
    templist = []
    while i<NoOfCentroids:
        for j in range(len(dataPointsFromFile[1,:])):
            cat = round(random.uniform(np.amin(dataPointsFromFile),np.amax(dataPointsFromFile)),1)
            templist.append(cat)
        randomCentroids.append(templist)
        templist = []
        i = i+1
    centroids = np.asarray(randomCentroids)
    return centroids

@对不起:(这只是对问题的描述,我的python代码,当前不正确的输出,以及所需的正确输出。我可以按照您希望的任何方式重新格式化它。我真的很抱歉,我只是想给出一个明确的示例。您应该争取的是一个,这不仅会使人们更有可能同时花时间查看它创建这样一个示例通常可以帮助您找到自己的问题。这是:,当
np.mean
得到一个空数组时出现问题的续集。现在运行时没有错误或警告,但值是错误的。这是一个很难简化为最小情况的问题,也很难诊断和帮助。@Voo我编辑了这个问题。摆脱了但在我上面的代码中,我试图确保没有空的数组切片。我接受了你的建议,如果所有的点都不返回true,那么我试图生成新的随机质心并传递它们。如果它们都返回true,那么运行代码。我想这就是问题所在是的。我昨天在做这件事时遇到的问题是,它没有返回我要求的原始数量的群集,这就是程序的全部要点。@Voo抱歉:(这只是对问题的描述,我的python代码,当前不正确的输出,以及所需的正确输出。我可以按照您希望的任何方式重新格式化它。我真的很抱歉,我只是想给出一个明确的示例。您应该争取的是一个,这不仅会使人们更有可能同时花时间查看它创建这样一个示例通常可以帮助您找到自己的问题。这是:,当
np.mean
得到一个空数组时出现问题的续集。现在运行时没有错误或警告,但值是错误的。这是一个很难简化为最小情况的问题,也很难诊断和帮助。@Voo我编辑了这个问题。摆脱了但在我上面的代码中,我试图确保没有空的数组切片。我接受了你的建议,如果所有的点都不返回true,那么我试图生成新的随机质心并传递它们。如果它们都返回true,那么运行代码。我想这就是问题所在是的,我昨天做的时候遇到的问题是,它没有返回我所要求的原始数量的集群,这就是程序的全部要点。
    ConvergenceCounter = 1
    keepGoing = True
    StillKeepGoing = True

#Check to make sure centroids were passed into the function
    print NoOfCentroids
    CentroidMaker(NoOfCentroids)
    print centroids

    StartingCentroids = np.copy(centroids)
    #print 'Starting Centroiuds:\n {}'.format(StartingCentroids)
    while keepGoing:


 #Where I think the problem resides  


        while StillKeepGoing:
            StartingCentroids = np.copy(centroids)
            #--------------Find The new means---------#
            t0 = StartingCentroids[None, :, :] - dataPoints[:, None, :]
            t1 = np.linalg.norm(t0, axis=-1)
            t2 = np.argmin(t1, axis=-1)
            #------Push the new means to a new array for comparison---------#
            CentroidMeans = []
            for x in range(len(StartingCentroids)):
                #if they are all true, get outta the loop!
                if np.all(t2==[x]):
                    CentroidMeans.append(np.mean(dataPoints[t2 == [x]], axis=0))
                    StillKeepGoing = False
                #If they are all not true, generate new ones!
            if np.any(t2!=[x]):
                CentroidMaker(NoOfCentroids)


        #--------Convert to a numpy array--------#
        NewMeans = np.asarray(CentroidMeans)
        #------Compare the New Means with the Starting Means------#
        if np.array_equal(NewMeans,StartingCentroids):
            print ('Convergence has been reached after {} moves'.format(ConvergenceCounter))
            print ('Starting Centroids:\n{}'.format(centroids))
            print ('Final Means:\n{}'.format(NewMeans))
            print ('Final Cluster assignments: {}'.format(t2))
            for x in xrange(len(StartingCentroids)):
                print ('Cluster {}:\n'.format(x)), dataPoints[t2 == [x]]
            for x in xrange(len(StartingCentroids)):
                print ('Size of Cluster {}:'.format(x)), len(dataPoints[t2 == [x]])
            keepGoing = False
        else:
            ConvergenceCounter  = ConvergenceCounter +1
            StartingCentroids =np.copy(NewMeans)

kMeans(dataPoints)