機(jī)器學(xué)習(xí)實(shí)戰(zhàn)填坑記—k近鄰算法

由于書(shū)上的代碼用的是Py2.6的,所以當(dāng)我用Py3.5的時(shí)候出現(xiàn)了一些問(wèn)題。

第2章 k-近鄰算法
問(wèn)題1:
在我加載函數(shù)classify0的時(shí)候按照書(shū)上的代碼出現(xiàn)錯(cuò)誤,Python3: AttributeError: 'dict' object has no attribute 'iteritems' 。經(jīng)研究發(fā)現(xiàn)是書(shū)上的Py2.7的代碼跟我用的Py3.5是有差異的,因此將函數(shù)中的classCount.iteritems()改為classCount.items()就好了。

問(wèn)題2:
當(dāng)我用>> reload(kNN)時(shí)候出現(xiàn)錯(cuò)誤:

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

經(jīng)查詢:In Python 2.x, this was a builtin, but in 3.x, it's in the imp module.
所以需要在前面加入命令from imp import reload

問(wèn)題3:
研究示例“使用k-近鄰算法改進(jìn)約會(huì)網(wǎng)站的配對(duì)效果”的時(shí)候加載命令datingDataMat,datingLabels = kNN.file2matrix('datingTestSet.txt')出現(xiàn)錯(cuò)誤:ValueError: invalid literal for int() with base 10: 'largeDoses'。
查看文件原來(lái)第四列為字符,下載的文件包含的有datingTestSet2.txt就是datingTestSet.txt對(duì)第4列轉(zhuǎn)換后得到的,現(xiàn)在也可以按如下方法對(duì)原來(lái)的文件datingTestSet.txt進(jìn)行變換得到datingTestSet2.txt

In [61]:table= pd.read_table('datingTestSet.txt', header = None)
In [62]:table.head(3)
Out[62]: 
       0         1         2           3
0  40920  8.326976  0.953952  largeDoses
1  14488  7.153469  1.673904  smallDoses
2  26052  1.441871  0.805124   didntLike
In [63]:table.columns = ('feixing','youxi','xiaofei','xiyin')
In [64]:table.head(3)
Out[64]: 
   feixing     youxi   xiaofei       xiyin
0    40920  8.326976  0.953952  largeDoses
1    14488  7.153469  1.673904  smallDoses
2    26052  1.441871  0.805124   didntLike
In [65]:table.count()
Out[65]: 
feixing    1000
youxi      1000
xiaofei    1000
xiyin      1000
dtype: int64

#將第四列按喜歡程度由弱到強(qiáng)轉(zhuǎn)換為數(shù)字1,2,3
In [66]:def xiyin2shuzi(x):
    if x == 'largeDoses':
        return 3
    if x == 'smallDoses':
        return 2
    if x == 'didntLike':
        return 1
In [67]: table['xiyin'] = table['xiyin'].apply(xiyin2shuzi)
In [68]:table.head()
Out[68]: 
   feixing      youxi   xiaofei  xiyin
0    40920   8.326976  0.953952      3
1    14488   7.153469  1.673904      2
2    26052   1.441871  0.805124      1
3    75136  13.147394  0.428964      1
4    38344   1.669788  0.134296      1
In [69]:table.to_csv('datingTestSet2.txt', header = False, index = False,sep = '\t')
# header: Whether to write out the column names (default True)
# index: whether to write row (index) names (default True)
# '\t'是tab,表示空格。為了跟變更前的數(shù)據(jù)保持一致。

參考文章:機(jī)器學(xué)習(xí)1k近鄰 (注意這里面的代碼盡管Print里面加了雙括號(hào)也是Py2.x的代碼)
Python3.X新特性

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容