简体   繁体   English

AttributeError:“函数”对象没有属性“ labels_”

[英]AttributeError: 'function' object has no attribute 'labels_'

When I execute this code I get the following error: 执行此代码时,出现以下错误:

AttributeError: 'function' object has no attribute 'labels_' AttributeError:“函数”对象没有属性“ labels_”

I understand that this message is triggered by the method: clusterWithFewestSamples 我了解此消息是由以下方法触发的:clusterWithFewestSamples

by lines like: 通过像这样的行:

minSamples = len(model.labels_) minSamples = len(model.labels_)

Any hint on what's wrong or what's lacking? 有什么提示是什么错误或缺少什么?

Many thanks in advance. 提前谢谢了。

Jordi 霍尔迪

import pandas as pd
from datetime import timedelta
import matplotlib.pyplot as plt
import matplotlib
from sklearn.cluster import KMeans

matplotlib.style.use('ggplot')


def model(self, num):
    return

def showandtell(title=None):
    if title != None: plt.savefig(title + ".png", bbox_inches='tight', dpi=300)
    plt.show()
    exit()

def clusterInfo(model):
    print "Cluster Analysis Inertia: ", model.inertia_  
    print '------------------------------------------'
    for i in range(len(model.cluster_centers_)):
      print "\n  Cluster ", i
      print "    Centroid ", model.cluster_centers_[i]
      print "    #Samples ", (model.labels_==i).sum() # NumPy Power

def clusterWithFewestSamples(model):
    minSamples = len(model.labels_)
    minCluster = 0
    for i in range(len(model.cluster_centers_)):
        if minSamples > (model.labels_==i).sum():
            minCluster = i
            minSamples = (model.labels_==i).sum()
        print "\n Cluster With Fewest Samples: ", minCluster
    return (model.labels_==minCluster)

def doKMeans(data, clusters=0):
    df_user1 = data.loc[:, ['TowerLon', 'TowerLat']]
    kmeans = KMeans(n_clusters=clusters)
    kmeans.fit(df_user1)
    labels = kmeans.predict(df_user1)
    centroids = kmeans.cluster_centers_
    ax.scatter(centroids[:,0], centroids[:,1], marker='x', c='red', alpha=0.5, linewidths=3, s=169)
    print centroids
    return model

df = pd.read_csv('Datasets/CDR.csv')
df.CallDate = pd.to_datetime(df.CallDate, errors='coerce')
df.CallTime = pd.to_timedelta(df.CallTime, errors='coerce')

PhoneList = df["In"].unique()

print "\n\nExamining person: ", 0

user1 = df[df.In == PhoneList[0]]
user1 = user1[(user1.DOW != 'Sat') & (user1.DOW != 'Sun')]
user1 = user1[(user1.CallTime > '09:00:00') | (user1.CallTime < '17:00:00')]

fig = plt.figure()

ax = fig.add_subplot(111)
ax.scatter(user1.TowerLon,user1.TowerLat, c='g', marker='o', alpha=0.2)
ax.set_title('Weekday Calls (>7:306am or <17p)')

model = doKMeans(user1, 2)

midWayClusterIndices = clusterWithFewestSamples(model)
midWaySamples = user1[midWayClusterIndices]
print " Its Waypoint Time: ", midWaySamples.CallTime.mean()

ax.scatter(model.cluster_centers_[:,1], model.cluster_centers_[:,0], s=169, c='r', marker='x', alpha=0.8, linewidths=2)

showandtell('Weekday Calls Centroids')

Where does model come from? model从哪里来?

def doKMeans(data, clusters=0):
    ...
    return model

model = doKMeans(user1, 2)

In doKMeans() nothing ever gets assigned to model , I'm surprised it doesn't throw a NameError exception. doKMeans()什么都没有分配给model ,我很惊讶它没有引发NameError异常。 Maybe it should be 也许应该

def doKMeans(data, clusters=0):
    ...
    return kmeans

An sklearn.cluster.KMeans object does have a labels_ attribute. sklearn.cluster.KMeans对象确实具有labels_属性。


You expect model to have a labels_ attribute but you have defined model as a function that returns None 您希望model具有labels_属性,但是您已将model定义为返回None的函数

def model(self, num):
    return

When doKMeans is called, it returns the function named model 调用doKMeans ,它将返回名为model的函数

def doKMeans(data, clusters=0):
    ...
    return model

So the statement model = doKMeans(user1, 2) does nothing: 因此,语句model = doKMeans(user1, 2)不执行任何操作:

>>> def f(a,b):
    return
>>> f
<function f at 0x00000000034A9840>

>>> def g(a,b):
    return f

>>> f = g(1,2)
>>> f
<function f at 0x00000000034A9840>

Neither the function, model , or its return value, None have a labels_ attribute. 函数, model或其返回值NoneNone labels_属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AttributeError: 'KMeans' object 没有属性 'labels_' pytorch - AttributeError: 'KMeans' object has no attribute 'labels_' pytorch “ KMeans”对象没有属性“ labels_” - 'KMeans' object has no attribute 'labels_' “KMeans”对象没有属性“labels_” - The 'KMeans' object has no attribute 'labels_' numpy.ndarray&#39;对象没有属性labels_ - numpy.ndarray' object has no attribute labels_ /profile/ &#39;function&#39; 对象的 AttributeError 没有属性 &#39;object - AttributeError at /profile/ 'function' object has no attribute 'object AttributeError: 'FITSFigure' object 没有属性 'set_tick_labels_font' - AttributeError: 'FITSFigure' object has no attribute 'set_tick_labels_font' AttributeError:函数&#39;对象没有属性&#39;linreg&#39; - AttributeError: function' object has no attribute 'linreg' /employee/ &#39;function&#39; 对象的 AttributeError 没有属性 &#39;delete&#39; - AttributeError at /employee/ 'function' object has no attribute 'delete' AttributeError: &#39;function&#39; 对象没有属性 &#39;ParseFromString&#39; - AttributeError: 'function' object has no attribute 'ParseFromString' Tensorflow:AttributeError:&#39;function&#39;对象没有属性&#39;graph&#39; - Tensorflow: AttributeError: 'function' object has no attribute 'graph'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM