由于書上的代碼用的是Py2.6的薯酝,所以當(dāng)我用Py3.5的時候出現(xiàn)了一些問題排龄。
第2章 k-近鄰算法
問題1:
在我加載函數(shù)classify0的時候按照書上的代碼出現(xiàn)錯誤腕唧,Python3: AttributeError: 'dict' object has no attribute 'iteritems' 。經(jīng)研究發(fā)現(xiàn)是書上的Py2.7的代碼跟我用的Py3.5是有差異的赔退,因此將函數(shù)中的classCount.iteritems()改為classCount.items()就好了橙依。
問題2:
當(dāng)我用>> reload(kNN)時候出現(xiàn)錯誤:
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
問題3:
研究示例“使用k-近鄰算法改進(jìn)約會網(wǎng)站的配對效果”的時候加載命令datingDataMat,datingLabels = kNN.file2matrix('datingTestSet.txt')出現(xiàn)錯誤:ValueError: invalid literal for int() with base 10: 'largeDoses'。
查看文件原來第四列為字符,下載的文件包含的有datingTestSet2.txt就是datingTestSet.txt對第4列轉(zhuǎn)換后得到的票编,現(xiàn)在也可以按如下方法對原來的文件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里面加了雙括號也是Py2.x的代碼)
Python3.X新特性