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

此代码显示错误为::

TypeError: unsupported operand type(s) for *: 'float' and 'numpy.ndarray'

根据作者的说法,我应该能够根据数据标签生成不同的颜色。

4

3 回答 3

3

该数组应包含数值。

>>> 15.0 * array([1,2])
array([ 15.,  30.])

>>> 15.0 * array(['1','2'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'float' and 'numpy.ndarray'

检查 的值datingLabels

于 2013-10-25T08:21:13.350 回答
2

这是另一种方法

作者提供了约会测试集2.txt

你可以在这里下载(我假设你已经完成了)

http://www.manning.com/pharrington/

您可以在此文件中找到第四列的值是数字

但是约会标签仍然充满了字符串值,例如 ['3', '2', '1', .....]

所以 15.0*array(datingLabels) 不起作用

要转换数组的类型,请使用 .astype() 方法

15.0*array(datingLabels).astype(float)

from numpy import array 
import matplotlib
import matplotlib.pyplot as plt
from fileread import file2matrix
datingDataMat,datingLabels = file2matrix('datingDataTest2.txt')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:,1], datingDataMat[:,2],15.0*array(datingLabels).astype(float), 15.0*array(datingLabels).astype(float))
plt.show()

它应该工作!

于 2014-10-17T07:51:16.127 回答
2

我遇到了类似的问题。这就是我所做的。我将标签转换为包含数值。我正在使用 python 2.7 ,不确定 3.3 版本是否会自动处理它。

新数据标签 = []

对于 datLabel 中的项目:

if item == 'largeDoses':

    newdatLabel.append(2)

elif item == 'smallDoses':

    newdatLabel.append(1)

elif item == 'didntLike':

    newdatLabel.append(0)
于 2014-01-05T19:26:14.383 回答