Advertisement
Kemudraj

klasifikacija_zad1

Aug 22nd, 2017
347
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.10 KB | None | 0 0
  1. Задача 1 Problem 1 (3 / 3)
  2. Дадено е тренинг множество од неколку документи. Притоа се знае секој документ од која класа е (science или sport). Mножеството е претставено како листи од торки, така што во секоја торка прв елемент е текстот на документот како стринг, а втор елемент е класата како стринг. Да се истренира модел врз основа на тренинг множеството и потоа за секој документ прочитан од стандарден влез да се испечати неговата класа.
  3.  
  4. #!/usr/bin/python
  5. #-*- coding: utf-8 -*-
  6.  
  7. import re
  8. import math
  9.  
  10. train_data=[
  11. ("""What Are We Searching for on Mars?
  12. Martians terrified me growing up. I remember watching the 1996 movie Mars Attacks! and fearing that the Red Planet harbored hostile alien neighbors. Though I was only 6 at the time, I was convinced life on Mars meant little green men wielding vaporizer guns. There was a time, not so long ago, when such an assumption about Mars wouldn’t have seemed so far-fetched.
  13. Like a child watching a scary movie, people freaked out after listening to “The War of the Worlds,” the now-infamous 1938 radio drama that many listeners believed was a real report about an invading Martian army. Before humans left Earth, humanity’s sense of what—or who—might be in our galactic neighborhood was, by today’s standards, remarkably optimistic.
  14. """,
  15. "science"),
  16. ("""Mountains of Ice are Melting, But Don't Panic (Op-Ed)
  17. If the planet lost the entire West Antarctic ice sheet, global sea level would rise 11 feet, threatening nearly 13 million people worldwide and affecting more than $2 trillion worth of property.
  18. Ice loss from West Antarctica has been increasing nearly three times faster in the past decade than during the previous one — and much more quickly than scientists predicted.
  19. This unprecedented ice loss is occurring because warm ocean water is rising from below and melting the base of the glaciers, dumping huge volumes of additional water — the equivalent of a Mt. Everest every two years — into the ocean.
  20. """,
  21. "science"),
  22. ("""Some scientists think we'll find signs of aliens within our lifetimes. Here's how.
  23. Finding extraterrestrial life is the essence of science fiction. But it's not so far-fetched to predict that we might find evidence of life on a distant planet within a generation.
  24. "With new telescopes coming online within the next five or ten years, we'll really have a chance to figure out whether we're alone in the universe," says Lisa Kaltenegger, an astronomer and director of Cornell's new Institute for Pale Blue Dots, which will search for habitable planets. "For the first time in human history, we might have the capability to do this."
  25. """,
  26. "science"),
  27. ("""'Magic' Mushrooms in Royal Garden: What Is Fly Agaric?
  28. Hallucinogenic mushrooms are perhaps the last thing you'd expect to find growing in the Queen of England's garden.
  29. Yet a type of mushroom called Amanita muscaria — commonly known as fly agaric, or fly amanita — was found growing in the gardens of Buckingham Palace by the producers of a television show, the Associated Press reported on Friday (Dec. 12).
  30. A. muscaria is a bright red-and-white mushroom, and the fungus is psychoactive when consumed.
  31. """,
  32. "science"),
  33. ("""Upcoming Parks : 'Lost Corner' Finds New Life in Sandy Springs
  34. At the corner of Brandon Mill Road, where Johnson Ferry Road turns into Dalrymple Road, tucked among 24 forested acres, sits an early 20th Century farmhouse. A vestige of Sandy Springs' past, the old home has found new life as the centerpiece of Lost Forest Preserve. While the preserve isn't slated to officially debut until some time next year, the city has opened the hiking trails to the public until construction begins on the permanent parking lot (at the moment the parking lot is a mulched area). The new park space includes community garden plots, a 4,000-foot-long hiking trail and an ADA-accessible trail through the densely wooded site. For Atlantans seeking an alternate escape to serenity (or those who dig local history), it's certainly worth a visit.
  35. """,
  36. "science"),
  37. ("""Stargazers across the world got a treat this weekend when the Geminids meteor shower gave the best holiday displays a run for their money.
  38. The meteor shower is called the "Geminids" because they appear as though they are shooting out of the constellation of Gemini. The meteors are thought to be small pieces of an extinct comment called 3200 Phaeton, a dust cloud revolving around the sun. Phaeton is thought to have lost all of its gas and to be slowly breaking apart into small particles.
  39. Earth runs into a stream of debris from 3200 Phaethon every year in mid-December, causing a shower of meteors, which hit its peak over the weekend.
  40. """,
  41. "science"),
  42. ("""Envisioning a River of Air
  43. By the classification rules of the world of physics, we all know that the Earth's atmosphere is made of gas (rather than liquid, solid, or plasma). But in the world of flying it's often useful to think
  44. """,
  45. "science"),
  46. ("""Following Sunday's 17-7 loss to the Seattle Seahawks, the San Francisco 49ers were officially eliminated from playoff contention, and they have referee Ed Hochuli to blame. OK, so they have a lot of folks to point the finger at for their 7-7 record, but Hochuli's incorrect call is the latest and easiest scapegoat.
  47. """
  48. ,"sport"),
  49. ("""Kobe Bryant and his teammates have an odd relationship. That makes sense: Kobe Bryant is an odd guy, and the Los Angeles Lakers are an odd team.
  50. They’re also, for the first time this season, the proud owners of a three-game winning streak. On top of that, you may have heard, Kobe Bryant passed Michael Jordan on Sunday evening to move into third place on the NBA’s all-time scoring list.
  51. """
  52. ,"sport"),
  53. ("""The Patriots continued their divisional dominance and are close to clinching home-field advantage throughout the AFC playoffs. Meanwhile, both the Colts and Broncos again won their division titles with head-to-head wins.The Bills' upset of the Packers delivered a big blow to Green Bay's shot at clinching home-field advantage throughout the NFC playoffs. Detroit seized on the opportunity and now leads the NFC North.
  54. """
  55. ,"sport"),
  56. ("""If you thought the Washington Redskins secondary was humbled by another scintillating performance from New Yorks Giants rookie wide receiver sensation Odell Beckham Jr., think again.In what is becoming a weekly occurrence, Beckham led NFL highlight reels on Sunday, collecting 12 catches for 143 yards and three touchdowns in Sunday's 24-13 victory against an NFC East rival.
  57. """
  58. ,"sport")
  59. ,("""That was two touchdowns and 110 total yards for the three running backs. We break down the fantasy implications.The New England Patriots' rushing game has always been tough to handicap. Sunday, all three of the team's primary running backs put up numbers, and all in different ways, but it worked for the team, as the Patriots beat the Miami Dolphins, 41-13.
  60. """
  61. ,"sport"),
  62. ("""General Santos (Philippines) (AFP) - Philippine boxing legend Manny Pacquiao vowed to chase Floyd Mayweather into ring submission after his US rival offered to fight him next year in a blockbuster world title face-off. "He (Mayweather) has reached a dead end. He has nowhere to run but to fight me," Pacquiao told AFP late Saturday, hours after the undefeated Mayweather issued the May 2 challenge on US television. The two were long-time rivals as the "best pound-for-pound" boxers of their generation, but the dream fight has never materialised to the disappointment of the boxing world.
  63. """
  64. ,"sport"),
  65. ("""When St. John's landed Rysheed Jordan, the consensus was that he would be an excellent starter.
  66. So far, that's half true.
  67. Jordan came off the bench Sunday and tied a career high by scoring 24 points to lead No. 24 St. John's to a 74-53 rout of Fordham in the ECAC Holiday Festival.
  68. ''I thought Rysheed played with poise,'' Red Storm coach Steve Lavin said. ''Played with the right pace. Near perfect game.''
  69. """
  70. ,"sport"),
  71. ("""Five-time world player of the year Marta scored three goals to lead Brazil to a 3-2 come-from-behind win over the U.S. women's soccer team in the International Tournament of Brasilia on Sunday. Carli Lloyd and Megan Rapinoe scored a goal each in the first 10 minutes to give the U.S. an early lead, but Marta netted in the 19th, 55th and 66th minutes to guarantee the hosts a spot in the final of the four-team competition.
  72. """
  73. ,"sport"),
  74. ]
  75. def getwords(doc):
  76.     # regularen izraz koj ke go deli stringot na zborovi
  77.     # stringot se deli na zborovi na site prazni mesta i interpunkciski znaci
  78.     splitter=re.compile('\\W*')
  79.     # podeli go dokumentot na zborovi
  80.     # i konvertiraj gi vo mali bukvi
  81.     # pa potoa stavi gi vo lista
  82.     # ako nivnata dolzina e >2 i <20
  83.     words=[word.lower() for word in splitter.split(doc) if len(word)>2 and len(word)<20]
  84.     # se vrakja recnik cii klucevi se zborovite koi
  85.     # se vo dokumentot, a eden zbor duri i da se
  86.     # srekjava poveke pati vo recnikot ke bide samo ednas
  87.     # vrednosta (1) vo recnikot ne e potrebna
  88.     return dict([(word,1) for word in words])
  89.  
  90.  
  91. # {'python': {'bad': 0, 'good': 6}, 'the': {'bad': 3, 'good': 3}}
  92.  
  93.  
  94. class documentClassifier:
  95.     def __init__(self,getfeatures,filename=None):
  96.         # Broj na parovi atribut/kategorija (feature/category)
  97.         self.featureCountsPerCategory={}
  98.         # Broj na dokumenti vo sekoja kategorija
  99.         self.categoryCounts={}
  100.         # funkcija za dobivanje na atributite (zborovite) vo dokumentot
  101.         self.getfeatures = getfeatures
  102.  
  103.  
  104.     # Zgolemuvanje na brojot na parovi atribut/kategorija
  105.     def incrementFeatureCountsPerCategory(self,currentFeature,currentCategory):
  106.         self.featureCountsPerCategory.setdefault(currentFeature,{})
  107.         self.featureCountsPerCategory[currentFeature].setdefault(currentCategory,0)
  108.         self.featureCountsPerCategory[currentFeature][currentCategory]+=1
  109.  
  110.     # Zgolemuvanje na brojot na predmeti(dokumenti) vo kategorija
  111.     def incrementCategoryCounts(self,cat):
  112.         self.categoryCounts.setdefault(cat,0)
  113.         self.categoryCounts[cat]+=1
  114.  
  115.     # Dobivanje na brojot kolku pati
  116.     # odreden atribut se ima pojaveno vo odredena kategorija
  117.     def getFeatureCountsPerCategory(self,currentFeature,currentCategory):
  118.         if currentFeature in self.featureCountsPerCategory and currentCategory in self.featureCountsPerCategory[currentFeature]:
  119.             return float(self.featureCountsPerCategory[currentFeature][currentCategory])
  120.         return 0.0
  121.  
  122.     # Dobivanje na brojot na predmeti(dokumenti) vo kategorija
  123.     def getCategoryCount(self,currentCategory):
  124.         if currentCategory in self.categoryCounts:
  125.             return float(self.categoryCounts[currentCategory])
  126.         return 0
  127.  
  128.     # Dobivanje na vkupniot broj na predmeti
  129.     def getTotalCount(self):
  130.         return sum(self.categoryCounts.values())
  131.  
  132.     # Dobivanje na lista na site kategorii
  133.     def categories(self):
  134.         return self.categoryCounts.keys()
  135.  
  136.     # Treniranje na klasifikatorot
  137.     # Noviot predmet (dokument) item pripagja na kategorijata cat
  138.     def train(self,item,currentCategory):
  139.         # Se zemaat atributite (zborovite) vo predmetot(dokumentot)
  140.         features=self.getfeatures(item)
  141.         # Se zgolemuva brojot na sekoj atribut vo ovaa kategorija
  142.         for currentFeature in features:
  143.             self.incrementFeatureCountsPerCategory(currentFeature,currentCategory)
  144.  
  145.         # Se zgolemuva brojot na predmeti (dokumenti) vo ovaa kategorija
  146.         self.incrementCategoryCounts(currentCategory)
  147.  
  148.  
  149.     def getFeaturePerCategoryProbability(self,currentFeature,currentCategory):
  150.         if self.getCategoryCount(currentCategory)==0: return 0
  151.         # Verojatnosta e vkupniot broj na pati koga
  152.         # ovoj atribut f (zbor) se pojavil vo ovaa
  153.         # kategorija podeleno so vkupniot broj na
  154.         # predmeti (dokumenti) vo ovaa kategorija
  155.         return self.getFeatureCountsPerCategory(currentFeature,currentCategory)/self.getCategoryCount(currentCategory)
  156.  
  157.     def weightedprob(self,currentFeature,currentCategory,prf,weight=1.0,ap=0.5):
  158.         # Presmetaj ja osnovnata verojatnost
  159.         basicprob=prf(currentFeature,currentCategory)
  160.         # Izbroj kolku pati se ima pojaveno ovoj atribut (zbor)
  161.         # vo site kategorii
  162.         totals=sum([self.getFeatureCountsPerCategory(currentFeature,currentCategory) for currentCategory in self.categories()])
  163.         # Presmetaj ja tezinski usrednetata verojatnost
  164.         bp=((weight*ap)+(totals*basicprob))/(weight+totals)
  165.         return bp
  166.  
  167.  
  168.  
  169. class naivebayes(documentClassifier):
  170.  
  171.     def __init__(self,getfeatures):
  172.         documentClassifier.__init__(self,getfeatures)
  173.         self.thresholds={}
  174.  
  175.     def setThreshold(self,currentCategory,threshold):
  176.         self.thresholds[currentCategory]=threshold
  177.  
  178.     def getThreshold(self,currentCategory):
  179.         if currentCategory not in self.thresholds: return 1.0
  180.         return self.thresholds[currentCategory]
  181.  
  182.     # ja vrakja verojatnosta na dokumentot da e od klasata cat (cat e odnapred poznata)
  183.     def caclulateDocumentProbabilityInClass(self,item,currentCategory):
  184.         # zemi gi zborovite vo dokumentot item
  185.         features=self.getfeatures(item)
  186.         # pomnozi gi verojatnostite na site zborovi
  187.         p=1
  188.         for currentFeature in features: p*=self.weightedprob(currentFeature,currentCategory,self.getFeaturePerCategoryProbability)
  189.  
  190.         return p
  191.  
  192.     # Ja vrakja verojatnosta na klasata ako e poznat dokumentot
  193.     def getCategoryProbabilityForDocument(self,item,currentCategory):
  194.         catprob=self.getCategoryCount(currentCategory)/self.getTotalCount()
  195.         caclulateDocumentProbabilityInClass=self.caclulateDocumentProbabilityInClass(item,currentCategory)
  196.         # Bayes Theorem
  197.         return caclulateDocumentProbabilityInClass*catprob/(1.0/self.getTotalCount())
  198.  
  199.     # klasificiranje na dokument
  200.     def classifyDocument(self,item,default=None):
  201.         probs={}
  202.         # najdi ja kategorijata (klasata)
  203.         # so najgolema verojatnost
  204.         max=0.0
  205.         for cat in self.categories():
  206.             probs[cat]=self.getCategoryProbabilityForDocument(item,cat)
  207.             if probs[cat]>max:
  208.                 max=probs[cat]
  209.                 best=cat
  210.  
  211.         # proveri dali verojatnosta e pogolema od
  212.         # threshold*next best (sledna najdobra)
  213.         for cat in probs:
  214.             if cat==best: continue
  215.             if probs[cat]*self.getThreshold(best)>probs[best]: return default
  216.  
  217.         return best
  218.  
  219.  
  220.  
  221. def trainClassifier(cl, data):
  222.     for item in range(len(data)):
  223.         cl.train(data[item][0],data[item][1])
  224.  
  225.  
  226. if __name__ == "__main__":
  227.     cl=naivebayes(getwords)
  228.     trainClassifier(cl,train_data)
  229.     recenica = input()
  230.     klasa=cl.classifyDocument(recenica)
  231.     print klasa
  232.  
  233. Sample input
  234. """So far this season Chelsea have looked the class of the league, but that does not faze Rooney."""
  235.  
  236. Sample output
  237. science
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement