python3实现《机器学习实战》遇到的问题:range函数

来源:互联网 发布:银行数据录入员累吗 编辑:程序博客网 时间:2024/05/22 21:57

最近在看学习《机器学习实战》这本书。这本书上用的python2的语法,和python3的语法不太一样。由于本人python小白,看了python3的语法,准备自己实现一下代码,遇到了一些问题,故开贴记录一下。


书上P82页。书上给出的

dataIndex=range(m)
然后循环最后一句是

del(dataIndex[randIndex])

python3中这样报错了。

结果发现原来是del中需要时list对象,然后对于range函数来说,python3中返回的是迭代值,不是list。但是Python2中range函数返回的就是list了。因此,使用python3的时候需要修改成

dataIndex = list(range(m))


另外,这P82的程序5-4,在P84中调用了。调用的时候使用了:

weights=logRegres.stocGradAscent1(array(dataArr),labelMat)
重点是用了numpy中的array函数吧dataArray这个list变成了numpy.ndarray。

因为我在这犯错了。

它给出的loadDataSet()函数返回的是个list。我当时直接传递给了stocGradAscent1(),计算的时候在

weights = weights + alpha*error*dataMatrix[randIndex]
时总是报错:operands could not be broadcast together with shapes
这是因为此时调用没有用numpy.array把list转换成numpy.ndarray的话,dataMatrix会是一个list。

然后alpha*error是个数字,一个数乘list会把list复制那个数字那么多遍,比如:

a=[1,2]b=2*a
此时b不是[2,4],而是[1,2,1,2]

因此发生了广播错误


所以建议在进入函数第一句话前加上

dataMatrix=np.array(dataMatrix)
这样不管传递list或者numpy.ndarray都可以了。


如果坚持用list,而且不加上面那句话,可以把计算weights那句话改成:

weights = weights +np.dot(alpha*error, dataMatrix[randIndex])

这两种方法都可以的。


最后还有一个问题,我觉得这块儿随机使用样本的时候,那个写的有问题,我觉得应该是

 h = sigmoid(sum(dataMatrix[dataIndex[randIndex]]*weights)) error = classLabels[dataIndex[randIndex]] - h weights = weights + alpha * error * dataMatrix[dataIndex[randIndex]]

和它的区别是,它使用了randIndex的地方我全部变成了dataIndex[randIndex],感觉这样才能在外循环加1 的时候,内循环能够把每个样本遍历一遍。

大家可以都看看,讨论一下。





阅读全文
0 0
原创粉丝点击