Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何修复此Python继承AttributeError:X实例没有属性';con';?_Python_Oop_Class_Inheritance - Fatal编程技术网

如何修复此Python继承AttributeError:X实例没有属性';con';?

如何修复此Python继承AttributeError:X实例没有属性';con';?,python,oop,class,inheritance,Python,Oop,Class,Inheritance,当我运行下面的代码(最后是整个代码)时,这一行: res=self.con.execute( 从该函数(其中getfeatures返回字典): 产生以下错误: AttributeError: naivebayes instance has no attribute 'con' 首先,我认为这是一个pysqlite2问题。但是我已经安装了pysqlite2,当我运行pysqlite2测试时,我就可以了。我还尝试使用内置的sqlite3而不是pysqlite2(执行导

当我运行下面的代码(最后是整个代码)时,这一行:

res=self.con.execute(
从该函数(其中getfeatures返回字典):

产生以下错误:

AttributeError: naivebayes instance has no attribute 'con'              
首先,我认为这是一个pysqlite2问题。但是我已经安装了pysqlite2,当我运行pysqlite2测试时,我就可以了。我还尝试使用内置的sqlite3而不是pysqlite2(执行
导入sqlite3
语句,并将
self.con=sqlite.connect(dbfile)
替换为
self.con=sqlite3.connect(“:memory:”)
,但也不起作用

因此,在前面的一个问题中,我收到反馈说这不是pysqlite2问题,而是继承问题。但是由于naivebayes中的init()被重新定义为显式调用超类(分类器)以扩展其行为,因此:

class naivebayes(classifier):

  def __init__(self,getfeatures):
    classifier.__init__(self,getfeatures)
我不明白继承的问题是什么。到底如何解决它

PS-代码不是我的。它来自(优秀的)书籍“编程集体智能”。我只是从raw.github.com/cataska/Programming Collective Intelligence code/…复制了它,并剪切了部分代码(fisherclassifier,因为我只使用naivebayes分类器)

谢谢你的帮助

下面是整个代码:

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.')
从pysqlite2导入dbapi2作为sqlite
进口稀土
输入数学
def getfeatures(文档):
拆分器=重新编译(“\\W*”)
#按非字母字符拆分单词
words=[s.lower(),表示splitter.split(doc)中的s
如果透镜>2且透镜最大值:
最大值=问题[cat]
最佳=猫
#确保概率超过阈值*次优
对于cat in probs:
如果cat==最佳:继续
if probs[cat]*self.getthreshold(best)>probs[best]:返回默认值
回报最好
def采样序列(cl):
cl.train(‘没有人拥有水’,‘好’)
cl.train(“快兔子跳栅栏”,“好”)
cl.train(“立即购买药品”,“不良”)
cl.train(‘在网上赌场快速赚钱’,‘坏’)
cl.train(“棕色狐狸快速跳跃”,“好”)
nb=朴素贝叶斯(getfeatures)
样本列车(nb)
#打印('\n购买被分类为%s'%n分类('buy'))
#打印('\n单击被分类为%s'%n%n分类('quick'))
##打印getfeatures('没有人拥有水')

只需附加
分类器。
self.setdb('autocreated\u db\u file')的\uu init\uuu
方法


只需使用self.setdb('autocreated_db_file')附加
classifier.\uu_初始化\uuu
方法:

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.')
class classifier:                                             
    def __init__(self,getfeatures,filename=None):
    ...
    self.setdb('autocreated_db_file')