2016-07-17 34 views
-1

我正在閱讀「機器學習在行動」一書。將Python字符串轉換爲int用於分類

第2章中的一個示例將字符串轉換爲int以供分類使用。例如,'student' = 1, 'teacher' = 2, engineer = 3。基數爲10

無效字面INT():

請參見下面的代碼在12線,而一個錯誤出現,而我執行它「largeDose」

哪裏是我的問題。

def file2matrix(filename): 
    fr = open(filename) 
    numberOfLines = len(fr.readlines())   #get the number of lines in the file 
    returnMat = zeros((numberOfLines,3))  #prepare matrix to return 
    classLabelVector = []      #prepare labels return 
    fr = open(filename) 
    index = 0 
    for line in fr.readlines(): 
     line = line.strip() 
     listFromLine = line.split('\t') 
     returnMat[index,:] = listFromLine[0:3] 
     classLabelVector.append(int(listFromLine[-1])) 
     index += 1 
    return returnMat,classLabelVector 

主叫代碼:

from numpy import * 
import kNN 
datingDataMat,datingLabels = kNN.file2matrix('datingTestSet.txt') 
import matplotlib 
import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = fig.add_subplot(111) 
#ax.scatter(datingDataMat[:,1], datingDataMat[:,2]) 
ax.scatter(datingDataMat[:,1], datingDataMat[:,2], array(datingLabels),  array(datingLabels)) 
plt.show() 

回溯和錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile 
    execfile(filename, namespace) 
    File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile 
    exec(compile(scripttext, filename, 'exec'), glob, loc) 
    File "C:/Users/Zhiming Zhang/Documents/Machine Learning/kNN/execute.py", line 10, in <module> 
    datingDataMat,datingLabels = kNN.file2matrix('datingTestSet.txt') 
    File "kNN.py", line 48, in file2matrix 
    classLabelVector.append(int(listFromLine[-1])) 

ValueError異常:無效的字面INT()基數爲10: 'largeDoses'

+0

沒有事實並非如此。剛剛編輯。謝謝 – user6601116

+0

這是錯誤:無效文字爲int()與基地10:'largeDose' – user6601116

+0

請提供錯誤和來電顯示 –

回答

0

你試試使用轉換函數int()將類似「largeDose」的字符串轉換爲int。但是,這不是如何工作。函數int()僅將看起來像整數(例如,"123")的字符串轉換爲整數。

在你的情況下,你可以使用if - elif - else級聯或字典。

級聯:

if listFromLine[-1] == 'largeDose': 
    result = 1 
elif listFromLine[-1] == 'teacher': 
    result = 2 
elif … 
    … 
else: 
    result = 0 # or raise an exception or whatever 

詞典:

conversion = { 
    'largeDose': 1, 
    'teacher': 2, 
    … } 
# ... 
# later, in the loop: 
classLabelVector.append(conversion[listFromLine[-1]]) 
+0

這看起來很酷。我會嘗試。非常感謝你! – user6601116

+0

歡迎來到StackOverflow!如果你覺得這個答案有用,請點擊它(點擊其上方的向上三角形)。如果它確實解決了您的問題,請接受它(除此之外,請點擊複選標記)。和快樂的黑客;-) – Alfe

+0

我試圖upvote你回答但失敗。我怎樣才能接受你的答案?謝謝! – user6601116