2012-08-01 4 views
0

이 pysqlite2 AttributeError 문제를 해결하는 방법 : X 인스턴스에 'con'속성이 없습니다?</p> <pre><code>res=self.con.execute( </code></pre> <p>이 기능에서 (getfeatures이 사전을 반환) : 나는 아래,이 줄을 전체 코드를 실행하면

AttributeError: naivebayes instance has no attribute 'con'    

I :

def fcount(self,f,cat): 
    res=self.con.execute(
     'select count from fc where feature="%s" and category="%s"' 
     %(f,cat)).fetchone() 
    if res==None: return 0 
    else: return float(res[0]) 

이 오류를 생성 pysqlite2를 설치했는데 pysqlite2 테스트를 실행하면 OK입니다.

는 또한 (A import sqlite3 문을하고 self.con=sqlite3.connect(":memory:")에 의해 self.con=sqlite.connect(dbfile)를 교체하는 대신 pysqlite2의 sqlite3를 내장 사용했는데, 그 중 하나가 작동하지 않았다.

방법이 오류를 해결하기 위해?에 대한

감사합니다 어떤 도움 전체 코드 여기

:.

from pysqlite2 import dbapi2 as sqlite 

import re 
import math 

def getfeatures(doc): 
    splitter=re.compile('\\W*') 
    # Split the words by non-alpha characters 
    words=[s.lower() for s in splitter.split(doc) 
      if len(s)>2 and len(s)<20] 
    # Return the unique set of words only 
# return dict([(w,1) for w in words]).iteritems() 
    return dict([(w,1) for w in words]) 

class classifier: 
    def __init__(self,getfeatures,filename=None): 
    # Counts of feature/category combinations 
    self.fc={} 
    # Counts of documents in each category 
    self.cc={} 
    self.getfeatures=getfeatures 

    def setdb(self,dbfile): 
    self.con=sqlite.connect(dbfile) 
    self.con.execute('create table if not exists fc(feature,category,count)') 
    self.con.execute('create table if not exists cc(category,count)') 


    def incf(self,f,cat): 
    count=self.fcount(f,cat) 
    if count==0: 
     self.con.execute("insert into fc values ('%s','%s',1)" 
         % (f,cat)) 
    else: 
     self.con.execute(
     "update fc set count=%d where feature='%s' and category='%s'" 
     % (count+1,f,cat)) 

    def fcount(self,f,cat): 
    res=self.con.execute(
     'select count from fc where feature="%s" and category="%s"' 
     %(f,cat)).fetchone() 
    if res==None: return 0 
    else: return float(res[0]) 

    def incc(self,cat): 
    count=self.catcount(cat) 
    if count==0: 
     self.con.execute("insert into cc values ('%s',1)" % (cat)) 
    else: 
     self.con.execute("update cc set count=%d where category='%s'" 
         % (count+1,cat)) 

    def catcount(self,cat): 
    res=self.con.execute('select count from cc where category="%s"' 
         %(cat)).fetchone() 
    if res==None: return 0 
    else: return float(res[0]) 

    def categories(self): 
    cur=self.con.execute('select category from cc'); 
    return [d[0] for d in cur] 

    def totalcount(self): 
    res=self.con.execute('select sum(count) from cc').fetchone(); 
    if res==None: return 0 
    return res[0] 


    def train(self,item,cat): 
    features=self.getfeatures(item) 
    # Increment the count for every feature with this category 
    for f in features.keys(): 
## for f in features: 
     self.incf(f,cat) 
    # Increment the count for this category 
    self.incc(cat) 
    self.con.commit() 

    def fprob(self,f,cat): 
    if self.catcount(cat)==0: return 0 

    # The total number of times this feature appeared in this 
    # category divided by the total number of items in this category 
    return self.fcount(f,cat)/self.catcount(cat) 

    def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5): 
    # Calculate current probability 
    basicprob=prf(f,cat) 

    # Count the number of times this feature has appeared in 
    # all categories 
    totals=sum([self.fcount(f,c) for c in self.categories()]) 

    # Calculate the weighted average 
    bp=((weight*ap)+(totals*basicprob))/(weight+totals) 
    return bp 




class naivebayes(classifier): 

    def __init__(self,getfeatures): 
    classifier.__init__(self,getfeatures) 
    self.thresholds={} 

    def docprob(self,item,cat): 
    features=self.getfeatures(item) 

    # Multiply the probabilities of all the features together 
    p=1 
    for f in features: p*=self.weightedprob(f,cat,self.fprob) 
    return p 

    def prob(self,item,cat): 
    catprob=self.catcount(cat)/self.totalcount() 
    docprob=self.docprob(item,cat) 
    return docprob*catprob 

    def setthreshold(self,cat,t): 
    self.thresholds[cat]=t 

    def getthreshold(self,cat): 
    if cat not in self.thresholds: return 1.0 
    return self.thresholds[cat] 

    def classify(self,item,default=None): 
    probs={} 
    # Find the category with the highest probability 
    max=0.0 
    for cat in self.categories(): 
     probs[cat]=self.prob(item,cat) 
     if probs[cat]>max: 
     max=probs[cat] 
     best=cat 

    # Make sure the probability exceeds threshold*next best 
    for cat in probs: 
     if cat==best: continue 
     if probs[cat]*self.getthreshold(best)>probs[best]: return default 
    return best 


def sampletrain(cl): 
    cl.train('Nobody owns the water.','good') 
    cl.train('the quick rabbit jumps fences','good') 
    cl.train('buy pharmaceuticals now','bad') 
    cl.train('make quick money at the online casino','bad') 
    cl.train('the quick brown fox jumps','good') 


nb = naivebayes(getfeatures) 

sampletrain(nb) 

#print ('\nbuy is classified as %s'%nb.classify('buy')) 
#print ('\nquick is classified as %s'%nb.classify('quick')) 

##print getfeatures('Nobody owns the water.') 

답변

0

코드가 엉망입니다. 먼저 http://www.python.org/dev/peps/pep-0008/을 읽으십시오. 직접 호출 대신 super() 함수를 사용하여 객체에서 새 클래스를 상속하고 con 속성을 사용하기 전에 self.set_db() 메서드를 __init__ 메서드에 호출하십시오. AttributeError: naivebayes instance has no attribute 'con'은 그러한 속성이 없을 때 발생합니다. db와는 전혀 관련이 없습니다.

+0

감사합니다, 빅터하지만,이 코드는 (좋은) 책은 "집단 프로그래밍 지성". 방금 https://raw.github.com/cataska/programming-collective-intelligence-code/master/chapter6/docclass.py에서 코드를 복사하고 코드의 일부를 잘라 냈습니다 (fisherclassifier, naivebayes 만 사용하기 때문에). 분류 자). 어쨌든 감사합니다! – craftApprentice

+0

naivebayes의 __init의 __()는 명시 적으로,이 방법의 동작을 확장하는 슈퍼 클래스 (분류)를 호출하는 재정의 된 이후 : 데프 __init __ (자기, getfeatures가) : 분류 .__의 init __ (자기 클래스 naivebayes (분류) , getfeatures) 상속 문제가 무엇인지 이해할 수 없습니다. 정확히 어떻게 고쳐? – craftApprentice

0

귀하의 코드 세트 setdb에있는 연결을 사용하지만 해당 방법을 호출하지 않습니다. 아마도 __init__ 메서드에서 호출 할 수 있습니다.

0

"훈련 된 분류 자 ​​유지"절의 133 페이지에서 "분류자를 초기화 한 후에는 데이터베이스 파일의 이름으로 setdb 메서드를 호출해야합니다."라고 표시됩니다. 그것은 당신의 문제를 처리해야합니다.

예 :
는 CL = docclass.fisherclassifier (docclass.getwords는)
cl.setdb ('test1.db')