Advertisement
Kemudraj

klasifikacija_zad3

Aug 22nd, 2017
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.28 KB | None | 0 0
  1. Задача 3 Problem 3 (2 / 2)
  2. За секоја прочитан документ од стандарден влез да се испечатат зборовите кои се употребуваат за класификација, класата и веројатноста на зборот да е од таа класа (заокружено на 4 децимали), како и тежинската веројатност на зборот да припаѓа на класата (заокружено на 4 децимали). На крај да се испечати предвидената класа на документот и логаритам со основа 2 од веројатноста со која се предвидува (заокружено на 4 децимали).
  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.  
  76.  
  77. def getwords(doc):
  78.     # regularen izraz koj ke go deli stringot na zborovi
  79.     # stringot se deli na zborovi na site prazni mesta i interpunkciski znaci
  80.     splitter = re.compile('\\W*')
  81.     # podeli go dokumentot na zborovi
  82.     # i konvertiraj gi vo mali bukvi
  83.     # pa potoa stavi gi vo lista
  84.     # ako nivnata dolzina e >2 i <20
  85.     words = [word.lower() for word in splitter.split(doc) if len(word) > 2 and len(word) < 20]
  86.     # se vrakja recnik cii klucevi se zborovite koi
  87.     # se vo dokumentot, a eden zbor duri i da se
  88.     # srekjava poveke pati vo recnikot ke bide samo ednas
  89.     # vrednosta (1) vo recnikot ne e potrebna
  90.     return dict([(word, 1) for word in words])
  91.  
  92.  
  93. # {'python': {'bad': 0, 'good': 6}, 'the': {'bad': 3, 'good': 3}}
  94.  
  95.  
  96. class documentClassifier:
  97.     def __init__(self, getfeatures, filename=None):
  98.         # Broj na parovi atribut/kategorija (feature/category)
  99.         self.featureCountsPerCategory = {}
  100.         # Broj na dokumenti vo sekoja kategorija
  101.         self.categoryCounts = {}
  102.         # funkcija za dobivanje na atributite (zborovite) vo dokumentot
  103.         self.getfeatures = getfeatures
  104.  
  105.     # Zgolemuvanje na brojot na parovi atribut/kategorija
  106.     def incrementFeatureCountsPerCategory(self, currentFeature, currentCategory):
  107.         self.featureCountsPerCategory.setdefault(currentFeature, {})
  108.         self.featureCountsPerCategory[currentFeature].setdefault(currentCategory, 0)
  109.         self.featureCountsPerCategory[currentFeature][currentCategory] += 1
  110.  
  111.     # Zgolemuvanje na brojot na predmeti(dokumenti) vo kategorija
  112.     def incrementCategoryCounts(self, cat):
  113.         self.categoryCounts.setdefault(cat, 0)
  114.         self.categoryCounts[cat] += 1
  115.  
  116.     # Dobivanje na brojot kolku pati
  117.     # odreden atribut se ima pojaveno vo odredena kategorija
  118.     def getFeatureCountsPerCategory(self, currentFeature, currentCategory):
  119.         if currentFeature in self.featureCountsPerCategory and currentCategory in self.featureCountsPerCategory[
  120.             currentFeature]:
  121.             return float(self.featureCountsPerCategory[currentFeature][currentCategory])
  122.         return 0.0
  123.  
  124.     # Dobivanje na brojot na predmeti(dokumenti) vo kategorija
  125.     def getCategoryCount(self, currentCategory):
  126.         if currentCategory in self.categoryCounts:
  127.             return float(self.categoryCounts[currentCategory])
  128.         return 0
  129.  
  130.     # Dobivanje na vkupniot broj na predmeti
  131.     def getTotalCount(self):
  132.         return sum(self.categoryCounts.values())
  133.  
  134.     # Dobivanje na lista na site kategorii
  135.     def categories(self):
  136.         return self.categoryCounts.keys()
  137.  
  138.     # Treniranje na klasifikatorot
  139.     # Noviot predmet (dokument) item pripagja na kategorijata cat
  140.     def train(self, item, currentCategory):
  141.         # Se zemaat atributite (zborovite) vo predmetot(dokumentot)
  142.         features = self.getfeatures(item)
  143.         # Se zgolemuva brojot na sekoj atribut vo ovaa kategorija
  144.         for currentFeature in features:
  145.             self.incrementFeatureCountsPerCategory(currentFeature, currentCategory)
  146.  
  147.         # Se zgolemuva brojot na predmeti (dokumenti) vo ovaa kategorija
  148.         self.incrementCategoryCounts(currentCategory)
  149.  
  150.     def getFeaturePerCategoryProbability(self, currentFeature, currentCategory):
  151.         if self.getCategoryCount(currentCategory) == 0: return 0
  152.         # Verojatnosta e vkupniot broj na pati koga
  153.         # ovoj atribut f (zbor) se pojavil vo ovaa
  154.         # kategorija podeleno so vkupniot broj na
  155.         # predmeti (dokumenti) vo ovaa kategorija
  156.         return self.getFeatureCountsPerCategory(currentFeature, currentCategory) / self.getCategoryCount(
  157.             currentCategory)
  158.  
  159.     def weightedprob(self, currentFeature, currentCategory, getFeaturePerCategoryProbability, weight=1.0, ap=0.5):
  160.         # Presmetaj ja osnovnata verojatnost
  161.         basicprob = getFeaturePerCategoryProbability(currentFeature, currentCategory)
  162.         # Izbroj kolku pati se ima pojaveno ovoj atribut (zbor)
  163.         # vo site kategorii
  164.         totals = sum([self.getFeatureCountsPerCategory(currentFeature, currentCategory) for currentCategory in
  165.                       self.categories()])
  166.         # Presmetaj ja tezinski usrednetata verojatnost
  167.         bp = ((weight * ap) + (totals * basicprob)) / (weight + totals)
  168.         return bp
  169.  
  170.  
  171. class naivebayes(documentClassifier):
  172.     def __init__(self, getfeatures):
  173.         documentClassifier.__init__(self, getfeatures)
  174.         self.thresholds = {}
  175.  
  176.     def setThreshold(self, currentCategory, threshold):
  177.         self.thresholds[currentCategory] = threshold
  178.  
  179.     def getThreshold(self, currentCategory):
  180.         if currentCategory not in self.thresholds: return 1.0
  181.         return self.thresholds[currentCategory]
  182.  
  183.     # ja vrakja verojatnosta na dokumentot da e od klasata cat (cat e odnapred poznata)
  184.     def caclulateDocumentProbabilityInClass(self, item, currentCategory):
  185.         # zemi gi zborovite vo dokumentot item
  186.         features = self.getfeatures(item)
  187.         # pomnozi gi verojatnostite na site zborovi
  188.         p = 1
  189.         for currentFeature in features: p *= self.weightedprob(currentFeature, currentCategory,
  190.                                                                self.getFeaturePerCategoryProbability)
  191.  
  192.         return p
  193.  
  194.     # Ja vrakja verojatnosta na klasata ako e poznat dokumentot
  195.     def getCategoryProbabilityForDocument(self, item, currentCategory):
  196.         catprob = self.getCategoryCount(currentCategory) / self.getTotalCount()
  197.         caclulateDocumentProbabilityInClass = self.caclulateDocumentProbabilityInClass(item, currentCategory)
  198.         # Bayes Theorem
  199.         return caclulateDocumentProbabilityInClass * catprob / (1.0 / self.getTotalCount())
  200.  
  201.     # klasificiranje na dokument
  202.     def classifyDocument(self, item, default=None):
  203.         probs = {}
  204.         # najdi ja kategorijata (klasata)
  205.         # so najgolema verojatnost
  206.         max = 0.0
  207.         for cat in self.categories():
  208.             probs[cat] = self.getCategoryProbabilityForDocument(item, cat)
  209.             if probs[cat] > max:
  210.                 max = probs[cat]
  211.                 best = cat
  212.  
  213.         # proveri dali verojatnosta e pogolema od
  214.         # threshold*next best (sledna najdobra)
  215.         for cat in probs:
  216.             if cat == best: continue
  217.             if probs[cat] * self.getThreshold(best) > probs[best]: return default
  218.  
  219.         return best
  220.  
  221. def trainClassifier(cl, data):
  222.     if len(data) > 0:
  223.         for d in data:
  224.             cl.train(d[0], d[1])
  225.  
  226. if __name__ == "__main__":
  227.     cl = naivebayes(getwords)
  228.     trainClassifier(cl, train_data)
  229.     recenica = input()
  230.     zborovi = cl.getfeatures(recenica).keys()
  231.     kategorii = cl.categories()
  232.  
  233.     for zbor in zborovi:
  234.         for kategorija in kategorii:
  235.             verojatnostNaZbor = round(cl.getFeaturePerCategoryProbability(zbor,'science'), 4) if kategorija == 'science' else round(cl.getFeaturePerCategoryProbability(zbor, 'sport'), 4)
  236.             verojatnostNaZborTezinska = round(cl.weightedprob(zbor, 'science', cl.getFeaturePerCategoryProbability), 4) if kategorija == 'science' else round(cl.weightedprob(zbor, 'sport', cl.getFeaturePerCategoryProbability), 4)
  237.  
  238.             print zbor, kategorija, verojatnostNaZbor, verojatnostNaZborTezinska
  239.     klasa = cl.classifyDocument(recenica)
  240.     verojatnost = round(math.log(cl.getCategoryProbabilityForDocument(recenica, klasa),2), 4)
  241.     print klasa, verojatnost
  242.  
  243. Sample input
  244. """Japan on Tuesday ordered the slaughter of some 4,000 chickens after officials confirmed bird flu at a poultry farm in the southwest of the country. DNA tests confirmed the H5 strain of the virus at a farm in Miyazaki after its owner reported more than 20 sudden deaths among his poultry on Sunday and Monday, the agriculture ministry said."""
  245.  
  246. Sample output
  247. and science 0.8571 0.8316
  248. and sport 0.875 0.8482
  249. among science 0.1429 0.3214
  250. among sport 0.0 0.25
  251. ordered science 0.0 0.5
  252. ordered sport 0.0 0.5
  253. deaths science 0.0 0.5
  254. deaths sport 0.0 0.5
  255. flu science 0.0 0.5
  256. flu sport 0.0 0.5
  257. tuesday science 0.0 0.5
  258. tuesday sport 0.0 0.5
  259. some science 0.2857 0.3571
  260. some sport 0.0 0.1667
  261. strain science 0.0 0.5
  262. strain sport 0.0 0.5
  263. officials science 0.0 0.5
  264. officials sport 0.0 0.5
  265. owner science 0.0 0.5
  266. owner sport 0.0 0.5
  267. japan science 0.0 0.5
  268. japan sport 0.0 0.5
  269. agriculture science 0.0 0.5
  270. agriculture sport 0.0 0.5
  271. its science 0.1429 0.3214
  272. its sport 0.0 0.25
  273. confirmed science 0.0 0.5
  274. confirmed sport 0.0 0.5
  275. said science 0.0 0.25
  276. said sport 0.125 0.3125
  277. dna science 0.0 0.5
  278. dna sport 0.0 0.5
  279. miyazaki science 0.0 0.5
  280. miyazaki sport 0.0 0.5
  281. sunday science 0.0 0.0714
  282. sunday sport 0.75 0.7143
  283. bird science 0.0 0.5
  284. bird sport 0.0 0.5
  285. southwest science 0.0 0.5
  286. southwest sport 0.0 0.5
  287. tests science 0.0 0.5
  288. tests sport 0.0 0.5
  289. his science 0.0 0.1667
  290. his sport 0.25 0.3333
  291. monday science 0.0 0.5
  292. monday sport 0.0 0.5
  293. farm science 0.0 0.5
  294. farm sport 0.0 0.5
  295. after science 0.1429 0.2619
  296. after sport 0.125 0.25
  297. slaughter science 0.0 0.5
  298. slaughter sport 0.0 0.5
  299. reported science 0.1429 0.3214
  300. reported sport 0.0 0.25
  301. virus science 0.0 0.5
  302. virus sport 0.0 0.5
  303. 000 science 0.1429 0.3214
  304. 000 sport 0.0 0.25
  305. than science 0.2857 0.3571
  306. than sport 0.0 0.1667
  307. poultry science 0.0 0.5
  308. poultry sport 0.0 0.5
  309. ministry science 0.0 0.5
  310. ministry sport 0.0 0.5
  311. country science 0.0 0.5
  312. country sport 0.0 0.5
  313. chickens science 0.0 0.5
  314. chickens sport 0.0 0.5
  315. sudden science 0.0 0.5
  316. sudden sport 0.0 0.5
  317. the science 1.0 0.9688
  318. the sport 1.0 0.9688
  319. more science 0.1429 0.3214
  320. more sport 0.0 0.25
  321. sport -42.2017
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement