【发布时间】:2014-01-25 06:10:54
【问题描述】:
这是来自Machine Learning In Action 一书的第 2 章,我正在尝试制作这里的情节:
作者已经发布了剧情的代码here,我认为这可能有点hacky(他还提到这个代码很草率,因为它超出了本书的范围)。
这是我重新创建情节的尝试:
首先,保存数据的.txt文件如下(来源:第2章中的“datingTestSet2.txt”here):
40920 8.326976 0.953952 largeDoses
14488 7.153469 1.673904 smallDoses
26052 1.441871 0.805124 didntLike
75136 13.147394 0.428964 didntLike
38344 1.669788 0.134296 didntLike
...
假设 datingDataMat 是形状为 `(1000L, 2L) 的 numpy.ndarray,其中第 0 列是“每年飞行里程数”,第 1 列是“玩视频游戏的时间百分比”,第 2 列是“升每周消耗的冰淇淋”,如上面的示例所示。
假设 datingLabels 是整数 1、2 或 3 的 list,分别表示“不喜欢”、“小剂量喜欢”和“大剂量喜欢” - 与上面的第 3 列相关联。
这是我必须创建情节的代码(file2matrix 的完整详细信息在最后):
datingDataMat,datingLabels = file2matrix("datingTestSet2.txt")
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot (111)
plt.xlabel("Freq flier miles")
plt.ylabel("% time video games")
# Not sure how to finish this: plt.legend([1, 2, 3], ["did not like", "small doses", "large doses"])
plt.scatter(datingDataMat[:,0], datingDataMat[:,1], 15.0*np.array(datingLabels), 15.0*np.array(datingLabels)) # Change marker color and size
plt.show()
输出在这里:
我主要关心的是如何创建这个传奇。有没有办法在不需要直接处理这些点的情况下做到这一点?
接下来,我很好奇是否可以找到一种方法来切换颜色以匹配情节的颜色。有没有办法做到这一点,而无需对各个点进行某种“处理”?
另外,如果有兴趣,这里是file2matrix 的实现:
def file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines())
returnMat = np.zeros((numberOfLines,3)) #numpy.zeros(shape, dtype=float, order='C')
classLabelVector = []
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip()
listFromLine = line.split('\t')
returnMat[index,:] = listFromLine[0:3] # FFmiles/yr, % time gaming, L ice cream/wk
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat,classLabelVector
【问题讨论】:
标签: python numpy matplotlib plot legend