Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.22 KB | None | 0 0
  1. import re
  2.  
  3.  
  4. def get_words(doc):
  5.     """Поделба на документот на зборови. Стрингот се дели на зборови според
  6.    празните места и интерпукциските знаци
  7.  
  8.    :param doc: документ
  9.    :type doc: str
  10.    :return: множество со зборовите кои се појавуваат во дадениот документ
  11.    :rtype: set(str)
  12.    """
  13.     # подели го документот на зборови и конвертирај ги во мали букви
  14.     # па потоа стави ги во резултатот ако нивната должина е >2 и <20
  15.     words = set()
  16.     for word in re.split('\\W+', doc):
  17.         if 2 < len(word) < 20:
  18.             words.add(word.lower())
  19.     return words
  20.  
  21.  
  22. class DocumentClassifier:
  23.     def __init__(self, get_features):
  24.         # број на парови атрибут/категорија (feature/category)
  25.         self.feature_counts_per_category = {}
  26.         # број на документи во секоја категорија
  27.         self.category_counts = {}
  28.         # функција за добивање на атрибутите (зборовите) во документот
  29.         self.get_features = get_features
  30.  
  31.     def increment_feature_counts_per_category(self, current_feature, current_category):
  32.         """Зголемување на бројот на парови атрибут/категорија
  33.  
  34.        :param current_feature: даден атрибут
  35.        :param current_category: дадена категорија
  36.        :return: None
  37.        """
  38.         self.feature_counts_per_category.setdefault(current_feature, {})
  39.         self.feature_counts_per_category[current_feature].setdefault(current_category, 0)
  40.         self.feature_counts_per_category[current_feature][current_category] += 1
  41.  
  42.     def increment_category_counts(self, cat):
  43.         """Зголемување на бројот на предмети (документи) во категорија
  44.  
  45.        :param cat: категорија
  46.        :return: None
  47.        """
  48.         self.category_counts.setdefault(cat, 0)
  49.         self.category_counts[cat] += 1
  50.  
  51.     def get_feature_counts_per_category(self, current_feature, current_category):
  52.         """Добивање на бројот колку пати одреден атрибут се има појавено во
  53.        одредена категорија
  54.  
  55.        :param current_feature: атрибут
  56.        :param current_category: категорија
  57.        :return: None
  58.        """
  59.         if current_feature in self.feature_counts_per_category \
  60.                 and current_category in self.feature_counts_per_category[current_feature]:
  61.             return float(self.feature_counts_per_category[current_feature][current_category])
  62.         return 0.0
  63.  
  64.     def get_category_count(self, current_category):
  65.         """Добивање на бројот на предмети (документи) во категорија
  66.  
  67.        :param current_category: категорија
  68.        :return: број на предмети (документи)
  69.        """
  70.         if current_category in self.category_counts:
  71.             return float(self.category_counts[current_category])
  72.         return 0
  73.  
  74.     def get_total_count(self):
  75.         """Добивање на вкупниот број на предмети"""
  76.         return sum(self.category_counts.values())
  77.  
  78.     def categories(self):
  79.         """Добивање на листа на сите категории"""
  80.         return self.category_counts.keys()
  81.  
  82.     def train(self, item, current_category):
  83.         """Тренирање на класификаторот. Новиот предмет (документ)
  84.  
  85.        :param item: нов предмет (документ)
  86.        :param current_category: категорија
  87.        :return: None
  88.        """
  89.         # Се земаат атрибутите (зборовите) во предметот (документот)
  90.         features = self.get_features(item)
  91.         # Се зголемува бројот на секој атрибут во оваа категорија
  92.         for current_feature in features:
  93.             self.increment_feature_counts_per_category(current_feature, current_category)
  94.  
  95.         # Се зголемува бројот на предмети (документи) во оваа категорија
  96.         self.increment_category_counts(current_category)
  97.  
  98.     def get_feature_per_category_probability(self, current_feature, current_category):
  99.         """Веројатноста е вкупниот број на пати кога даден атрибут f (збор) се појавил во
  100.        дадена категорија поделено со вкупниот број на предмети (документи) во категоријата
  101.  
  102.        :param current_feature: атрибут
  103.        :param current_category: карактеристика
  104.        :return: веројатност на појавување
  105.        """
  106.         if self.get_category_count(current_category) == 0:
  107.             return 0
  108.         return self.get_feature_counts_per_category(current_feature, current_category) \
  109.                / self.get_category_count(current_category)
  110.  
  111.     def weighted_probability(self, current_feature, current_category, prf, weight=1.0, ap=0.5):
  112.         """Пресметка на тежински усогласената веројатност
  113.  
  114.        :param current_feature: атрибут
  115.        :param current_category: категорија
  116.        :param prf: функција за пресметување на основната веројатност
  117.        :param weight: тежина
  118.        :param ap: претпоставена веројатност
  119.        :return: тежински усогласена веројатност
  120.        """
  121.         # Пресметај ја основната веројатност
  122.         basic_prob = prf(current_feature, current_category)
  123.         # Изброј колку пати се има појавено овој атрибут (збор) во сите категории
  124.         totals = sum([self.get_feature_counts_per_category(current_feature, currentCategory) for currentCategory in
  125.                       self.categories()])
  126.         # Пресметај ја тежински усредената веројатност
  127.         bp = ((weight * ap) + (totals * basic_prob)) / (weight + totals)
  128.         return bp
  129.  
  130.  
  131. class NaiveBayes(DocumentClassifier):
  132.     def __init__(self, get_features):
  133.         super().__init__(get_features)
  134.         self.thresholds = {}
  135.  
  136.     def set_threshold(self, current_category, threshold):
  137.         """Поставување на праг на одлучување за категорија
  138.  
  139.        :param current_category: категорија
  140.        :param threshold: праг на одлучување
  141.        :return: None
  142.        """
  143.         self.thresholds[current_category] = threshold
  144.  
  145.     def get_threshold(self, current_category):
  146.         """Добивање на прагот на одлучување за дадена класа
  147.  
  148.        :param current_category: категорија
  149.        :return: праг на одлучување за дадената категорија
  150.        """
  151.         if current_category not in self.thresholds:
  152.             return 1.0
  153.         return self.thresholds[current_category]
  154.  
  155.     def calculate_document_probability_in_class(self, item, current_category):
  156.         """Ја враќа веројатноста на документот да е од класата current_category
  157.        (current_category е однапред позната)
  158.  
  159.        :param item: документ
  160.        :param current_category: категорија
  161.        :return:
  162.        """
  163.         # земи ги зборовите од документот item
  164.         features = self.get_features(item)
  165.         # помножи ги веројатностите на сите зборови
  166.         p = 1
  167.         for current_feature in features:
  168.             p *= self.weighted_probability(current_feature, current_category,
  169.                                            self.get_feature_per_category_probability)
  170.  
  171.         return p
  172.  
  173.     def get_category_probability_for_document(self, item, current_category):
  174.         """Ја враќа веројатноста на класата ако е познат документот
  175.  
  176.        :param item: документ
  177.        :param current_category: категорија
  178.        :return: веројатност за документот во категорија
  179.        """
  180.         cat_prob = self.get_category_count(current_category) / self.get_total_count()
  181.         calculate_document_probability_in_class = self.calculate_document_probability_in_class(item, current_category)
  182.         # Bayes Theorem
  183.         return calculate_document_probability_in_class * cat_prob / (1.0 / self.get_total_count())
  184.  
  185.     def classify_document(self, item, default=None):
  186.         """Класифицирање на документ
  187.  
  188.        :param item: документ
  189.        :param default: подразбирана (default) класа
  190.        :return:
  191.        """
  192.         probs = {}
  193.         # најди ја категоријата (класата) со најголема веројатност
  194.         max = 0.0
  195.         for cat in self.categories():
  196.             probs[cat] = self.get_category_probability_for_document(item, cat)
  197.             if probs[cat] > max:
  198.                 max = probs[cat]
  199.                 best = cat
  200.  
  201.         # провери дали веројатноста е поголема од threshold*next best (следна најдобра)
  202.         for cat in probs:
  203.             if cat == best:
  204.                 continue
  205.             if probs[cat] * self.get_threshold(best) > probs[best]: return default
  206.  
  207.         return best
  208.  
  209.  
  210. train_data = [
  211.     ("""What Are We Searching for on Mars?
  212. 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.
  213. 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.
  214. """,
  215.      "science"),
  216.     ("""Mountains of Ice are Melting, But Don't Panic (Op-Ed)
  217. 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.
  218. 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.
  219. 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.
  220. """,
  221.      "science"),
  222.     ("""Some scientists think we'll find signs of aliens within our lifetimes. Here's how.
  223. 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.
  224. "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."
  225. """,
  226.      "science"),
  227.     ("""'Magic' Mushrooms in Royal Garden: What Is Fly Agaric?
  228. Hallucinogenic mushrooms are perhaps the last thing you'd expect to find growing in the Queen of England's garden.
  229. 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).
  230. A. muscaria is a bright red-and-white mushroom, and the fungus is psychoactive when consumed.
  231. """,
  232.      "science"),
  233.     ("""Upcoming Parks : 'Lost Corner' Finds New Life in Sandy Springs
  234. 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.
  235. """,
  236.      "science"),
  237.     ("""Stargazers across the world got a treat this weekend when the Geminids meteor shower gave the best holiday displays a run for their money.
  238. 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.
  239. 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.
  240. """,
  241.      "science"),
  242.     ("""Envisioning a River of Air
  243. 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
  244. """,
  245.      "science"),
  246.     ("""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.
  247. """
  248.      , "sport"),
  249.     ("""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.
  250. 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.
  251. """
  252.      , "sport"),
  253.     ("""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.
  254. """
  255.      , "sport"),
  256.     ("""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.
  257. """
  258.      , "sport")
  259.     , ("""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.
  260. """
  261.        , "sport"),
  262.     ("""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.
  263. """
  264.      , "sport"),
  265.     ("""When St. John's landed Rysheed Jordan, the consensus was that he would be an excellent starter.
  266. So far, that's half true.
  267. 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.
  268. ''I thought Rysheed played with poise,'' Red Storm coach Steve Lavin said. ''Played with the right pace. Near perfect game.''
  269. """
  270.      , "sport"),
  271.     ("""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.
  272. """
  273.      , "sport"),
  274. ]
  275.  
  276. if __name__ == "__main__":
  277.     recenica = input()
  278.     klasa1 = NaiveBayes(get_words)
  279.     for item in train_data:
  280.         klasa1.train(item[0], item[1])
  281.     cat = klasa1.classify_document(recenica)
  282.     ver = round(klasa1.get_category_probability_for_document(recenica, cat), 10)
  283.     print(f'{cat}')
  284.     print(f'{ver}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement