2 lichenghao 96 lichenghao_96 于 2017.09.05 10:32 提问

function takes at least 2 arguments(1 given)

机器学习实战kNN篇手写数字识别:

 def img2vector(filename):
    file=open(filename)
    imgvector=zeros((1,1024))
    for i in range(32):
        line=file.readline()
        for j in range(32):
            imgvector[0,32*i+j]=int(line[j])
    return imgvector

def handwritingClassifier():
    hwlabels=[]
    trainingfilelist=listdir('trainingDigits')
    m=len(trainingfilelist)
    trainingMat=zeros((m,1024))
    for i in range(m):
        fn=trainingfilelist[i]
        filename1=fn.split('.')[0]
        filelabel=int(filename1.split('_')[0])
        hwlabels.append(filelabel)
        trainingMat[i,:]=img2vector('trainingDigits/%s' % fn)
    testfilelist=listdir('testDigits')
    mT=len(testfilelist)
    errorCount=0.0
    for i in range(mT):
        filenameT=testfilelist[i]
        filename1T=filenameT.split('.')[0]
        filelabelT=int(filename1T.split('_')[0])
        testfilevector=img2vector('testDigits/%s' % filenameT)
        predictlabel=Classifier(testfilevector,trainingMat,hwlabels,5)
        if (predictlabel!=filelabelT):
            errorCount+=1.0
        print "the classifier came back with %d ,the real answer is %d " % (predictlabel,filelabelT)
    print "the error rate is %f" % (errorCount/float(mT))

结果在命令行输入import kNN ...kNN.handwritingClassifier()的时候

TypeError Traceback (most recent call last)
in ()
1 import kNN
----> 2 kNN.handwritingClassifier()

C:\Users\Administrator\kNN.py in handwritingClassifier()
99 filelabel=int(filename1.split('_')[0])
100 hwlabels.append(filelabel)
--> 101 trainingMat[i,:]=img2vector('trainingDigits/%s' % fn)
102 testfilelist=listdir('testDigits')
103 mT=len(testfilelist)

C:\Users\Administrator\kNN.py in img2vector(filename)
81
82 def img2vector(filename):
---> 83 file=open(filename)
84 imgvector=zeros((1,1024))
85 for i in range(32):

TypeError: function takes at least 2 arguments (1 given)

小白一枚,请问到底哪里有问题,open函数不是只要一个参数吗,用的是python2.7望指教!!

2个回答

devmiao
devmiao   Ds   Rxr 2017.09.05 11:09

函数需要2个参数,你只给了1个,看看手册去

lichenghao_96
lichenghao_96   2017.09.05 11:23

解决了,不是这个问题,我开头from os import * 好像内置函数把原来的open覆盖了,新的open可能要两个,怪不得

Csdn user default icon
上传中...
上传图片
插入图片