2017-04-25 104 views
0

我正在使用Python(Richart,Pedro Coelho)書中的Building Machine Learning Systems的逐行示例。NameError:未定義名稱'labels'

進口虹膜數據集後,我們希望與Setosa

data = load_iris() 
features = data['data'] 
plength = features[:, 2] 
# use numpy operations to get setosa features 
is_setosa = (labels == 'setosa') 

提取那些我得到這個

>>> is_setosa = (labels == 'setosa') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'labels' is not defined 

我想這是錯字,所以我嘗試

>>> is_setosa = plenght(labels == 'setosa') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'plenght' is not defined 
>>> is_setosa = plength(labels == 'setosa') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'labels' is not defined 
>>> is_setosa = data(labels == 'setosa') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'labels' is not defined 

什麼我現在應該做什麼? 如何檢查數據對象?

>>> data.labels 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/home/milenko/miniconda2/lib/python2.7/site-packages/sklearn/datasets/base.py", line 58, in __getattr__ 
    raise AttributeError(key) 
AttributeError: labels 
>>> data.dtypes 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/home/milenko/miniconda2/lib/python2.7/site-packages/sklearn/datasets/base.py", line 58, in __getattr__ 
    raise AttributeError(key) 
AttributeError: dtypes 

這是描述

- class:\n    - Iris-Setosa\n    - Iris-Versicolour\n    - Iris-Virginica\n : 
+5

很明顯,變量'labels'沒有被定義! – luoluo

+0

你可以做一些類似data ['labels']或data.labels的東西......檢查數據對象 – FLab

+0

你不想在你的'is_setosa'變量中設置一個布爾值。爲此,你正在比較'labels =='setosa''。現在'標籤'沒有定義過。介意寫上面的聲明像'labels =「」'? – ishaan

回答

1

如果你只需要輸入data到IPython的控制檯,您將看到數據集的描述的相關部分。特別是有兩個字段:data['target']包含與data['target_names']中報告的名稱對應的數字標籤{0,1,2},即{'setosa','versicolor','virginica'}。

所以,你也許可以定義labels如下:

labels = map(lambda x: dict(enumerate(data['target_names']))[x], data['target']) 
0

它主要在東陽書中的代碼是沒有定義「標籤」的。根據上下文,添加以下代碼:

target = data['target'] 
target_names = data['target_names'] 
labels=np.array([target_names[i] for i in target])