1. 程式人生 > >機器學習實戰——k-近鄰演算法Python實現問題記錄

機器學習實戰——k-近鄰演算法Python實現問題記錄

 

準備 kNN.py 的python模組

from numpy import *
import operator
def createDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels = ['A','A','B','B']
    return group,labels

問題:ValueError: only 2 non-keyword arguments accepted

是由於一開始array裡陣列少了一對中括號

array([1.0,1.1],[1.0,1.0],[0,0],[0,0.1])     - --------加上就好了。如上圖Python3.5中:iteritems變為items

問題:AttributeError: 'dict' object has no attribute 'iteritems'

Python3.6中:iteritems變為items


正常結果:

問題:NameError: name 'reload' is not defined

對於 Python 2.X

import sys
reload(sys)

對於 <= Python 3.3

import imp
imp.reload(sys)

對於 >= Python 3.4

import importlib
importlib.reload(sys)

問題:AttributeError: module 'kNN' has no attribute 'file2matrix'

其實雖然能調出來,原理還是沒搞明白 = =

問題:ValueError: invalid literal for int() with base 10: 'largeDoses'

下面是網上參考文獻[1]中的例子

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.0'

現象表現:

如果寫int("1.0")就會錯誤,因為Python假設需要進行int轉型的字串僅僅包含數字,這時候用round(float("1.0"))就ok了。

據此找到上面錯誤的原因是: 該書程式碼示例有錯, datingTestSet.txt應改為datingTestSet2.txt, 因為前者最末列是字串, 後者最末列是整數.

問題:ValueError: embedded null character

出現這個錯誤的原因python直譯器在遇到'\'會自動增加一個'\'以便與轉義字元區分,但是遇到轉義字元時不會增加'\',而書中的程式碼的檔案目錄有'\0',故而才會報錯;解決方法,是把檔案路路徑中的'\'改為'/'

 

問題:TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'

a = 'Peter'
b = 'Linda'

print("who is the murder? %s or %s?") % (a, b)

後來才發現,python3.x與python2.x有一點區別,
原來%(變數名,...)應該是加在print括號裡的
如:print("who is the murder? %s or %s" % (a, b))

問題:NameError: name 'raw_input' is not defined

原因出在raw_input ,python3.0版本後用input替換了raw_input

問題:NameError: name 'img2vecctor' is not defined

           NameError: name 'listdir' is not defined

1.

import os
os.listdir()

2. from os import *

這裡需要注意幾個問題,如果直接使用import os的時候,那麼呼叫是就需要寫成os.listdir(),如果是使用from os import *,那麼是可以直接使用listdir(),但是會出現模組之間的命名衝突問題,對程式碼的穩定性會有一定的影響,所以LZ建議如果對模組函式還不是很熟悉的情況下使用第一種方法。