Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Точност на наивен баесов класификатор Problem 2 (2 / 4)
- Изградете композитен наивен баесов класификатор кој ќе одредува дали даден документ е формален или неформален. Класификаторот претставува композиција од два класификатори кои работат на следниот начин. Првиот класификатор ги користи првите 40% од документите во податочното множество. Вториот класификатор ги користи вторите 40% од податочното множество. Останатите 20% од податочното множество се користат за тестирање. Тренирајте ги двата класификатори со соодветното подмножество.
- Точноста на класификаторот се пресметува на следниот начин: број на точно класифицирани документи од двата поединечни класификатори / вкупен број на документи во множеството за тестирање (одреден документ се смета за точно класифициран доколку со двата поединечни класификатори се добие вистинската класа)
- Испечатете ја точноста на наивниот баесов класификатор. Потоа, за документот прочитан од стандарден влез испечатете ја класата во која тој припаѓа. Доколку со двата поединечни класификатори се добие истата класа, тогаш се печати таа. Во спротивно се печати непозната (unknown) класа."""
- import re
- def get_words(doc):
- """Поделба на документот на зборови. Стрингот се дели на зборови според
- празните места и интерпукциските знаци
- :param doc: документ
- :type doc: str
- :return: множество со зборовите кои се појавуваат во дадениот документ
- :rtype: set(str)
- """
- # подели го документот на зборови и конвертирај ги во мали букви
- # па потоа стави ги во резултатот ако нивната должина е >2 и <20
- words = set()
- for word in re.split('\\W+', doc):
- if 2 < len(word) < 20:
- words.add(word.lower())
- return words
- class DocumentClassifier:
- def __init__(self, get_features):
- # број на парови атрибут/категорија (feature/category)
- self.feature_counts_per_category = {}
- # број на документи во секоја категорија
- self.category_counts = {}
- # функција за добивање на атрибутите (зборовите) во документот
- self.get_features = get_features
- def increment_feature_counts_per_category(self, current_feature, current_category):
- """Зголемување на бројот на парови атрибут/категорија
- :param current_feature: даден атрибут
- :param current_category: дадена категорија
- :return: None
- """
- self.feature_counts_per_category.setdefault(current_feature, {})
- self.feature_counts_per_category[current_feature].setdefault(current_category, 0)
- self.feature_counts_per_category[current_feature][current_category] += 1
- def increment_category_counts(self, cat):
- """Зголемување на бројот на предмети (документи) во категорија
- :param cat: категорија
- :return: None
- """
- self.category_counts.setdefault(cat, 0)
- self.category_counts[cat] += 1
- def get_feature_counts_per_category(self, current_feature, current_category):
- """Добивање на бројот колку пати одреден атрибут се има појавено во
- одредена категорија
- :param current_feature: атрибут
- :param current_category: категорија
- :return: None
- """
- if current_feature in self.feature_counts_per_category \
- and current_category in self.feature_counts_per_category[current_feature]:
- return float(self.feature_counts_per_category[current_feature][current_category])
- return 0.0
- def get_category_count(self, current_category):
- """Добивање на бројот на предмети (документи) во категорија
- :param current_category: категорија
- :return: број на предмети (документи)
- """
- if current_category in self.category_counts:
- return float(self.category_counts[current_category])
- return 0
- def get_total_count(self):
- """Добивање на вкупниот број на предмети"""
- return sum(self.category_counts.values())
- def categories(self):
- """Добивање на листа на сите категории"""
- return self.category_counts.keys()
- def train(self, item, current_category):
- """Тренирање на класификаторот. Новиот предмет (документ)
- :param item: нов предмет (документ)
- :param current_category: категорија
- :return: None
- """
- # Се земаат атрибутите (зборовите) во предметот (документот)
- features = self.get_features(item)
- # Се зголемува бројот на секој атрибут во оваа категорија
- for current_feature in features:
- self.increment_feature_counts_per_category(current_feature, current_category)
- # Се зголемува бројот на предмети (документи) во оваа категорија
- self.increment_category_counts(current_category)
- def get_feature_per_category_probability(self, current_feature, current_category):
- """Веројатноста е вкупниот број на пати кога даден атрибут f (збор) се појавил во
- дадена категорија поделено со вкупниот број на предмети (документи) во категоријата
- :param current_feature: атрибут
- :param current_category: карактеристика
- :return: веројатност на појавување
- """
- if self.get_category_count(current_category) == 0:
- return 0
- return self.get_feature_counts_per_category(current_feature, current_category) \
- / self.get_category_count(current_category)
- def weighted_probability(self, current_feature, current_category, prf, weight=1.0, ap=0.5):
- """Пресметка на тежински усогласената веројатност
- :param current_feature: атрибут
- :param current_category: категорија
- :param prf: функција за пресметување на основната веројатност
- :param weight: тежина
- :param ap: претпоставена веројатност
- :return: тежински усогласена веројатност
- """
- # Пресметај ја основната веројатност
- basic_prob = prf(current_feature, current_category)
- # Изброј колку пати се има појавено овој атрибут (збор) во сите категории
- totals = sum([self.get_feature_counts_per_category(current_feature, currentCategory) for currentCategory in
- self.categories()])
- # Пресметај ја тежински усредената веројатност
- bp = ((weight * ap) + (totals * basic_prob)) / (weight + totals)
- return bp
- class NaiveBayes(DocumentClassifier):
- def __init__(self, get_features):
- super().__init__(get_features)
- self.thresholds = {}
- def set_threshold(self, current_category, threshold):
- """Поставување на праг на одлучување за категорија
- :param current_category: категорија
- :param threshold: праг на одлучување
- :return: None
- """
- self.thresholds[current_category] = threshold
- def get_threshold(self, current_category):
- """Добивање на прагот на одлучување за дадена класа
- :param current_category: категорија
- :return: праг на одлучување за дадената категорија
- """
- if current_category not in self.thresholds:
- return 1.0
- return self.thresholds[current_category]
- def calculate_document_probability_in_class(self, item, current_category):
- """Ја враќа веројатноста на документот да е од класата current_category
- (current_category е однапред позната)
- :param item: документ
- :param current_category: категорија
- :return:
- """
- # земи ги зборовите од документот item
- features = self.get_features(item)
- # помножи ги веројатностите на сите зборови
- p = 1
- for current_feature in features:
- p *= self.weighted_probability(current_feature, current_category,
- self.get_feature_per_category_probability)
- return p
- def get_category_probability_for_document(self, item, current_category):
- """Ја враќа веројатноста на класата ако е познат документот
- :param item: документ
- :param current_category: категорија
- :return: веројатност за документот во категорија
- """
- cat_prob = self.get_category_count(current_category) / self.get_total_count()
- calculate_document_probability_in_class = self.calculate_document_probability_in_class(item, current_category)
- # Bayes Theorem
- return calculate_document_probability_in_class * cat_prob / (1.0 / self.get_total_count())
- def classify_document(self, item, default=None):
- """Класифицирање на документ
- :param item: документ
- :param default: подразбирана (default) класа
- :return:
- """
- probs = {}
- # најди ја категоријата (класата) со најголема веројатност
- max = 0.0
- for cat in self.categories():
- probs[cat] = self.get_category_probability_for_document(item, cat)
- if probs[cat] > max:
- max = probs[cat]
- best = cat
- # провери дали веројатноста е поголема од threshold*next best (следна најдобра)
- for cat in probs:
- if cat == best:
- continue
- if probs[cat] * self.get_threshold(best) > probs[best]: return default
- return best
- train_data = [
- ("""I like Rhythm and Blue music.""", 'formal'),
- ("""Back in my day Emo was a comedian :/""", 'informal'),
- ("""Why sit and listen to Locke, Jack, or Syead?""", 'informal'),
- ("""There's nothing he needs to change.""", 'formal'),
- ("""It does not exist.""", 'formal'),
- ("""I like when the Prime Minister goes door to door to find the girl!""", 'informal'),
- ("""Mine is book by Steve Martin called 'The Pleasure of my Company'.""", 'formal'),
- ("""What differentiates a mosquitoo from a blonde?""", 'formal'),
- ("""They're pretty good. Also, that's a good song.""", 'formal'),
- ("""And every time I hear that song I get butterflies in my stomach!""", 'informal'),
- ("""It's the biggest load of crap I've seen for ages.""", 'informal'),
- ("""I do not think Beyonce can sing, dance, or act. You mentioned Rihanna, who is that?""", 'formal'),
- ("""as i lay dying is far far away from christ definitaly!""", 'informal'),
- ("""I was unaware that you were in law enforcement, as well.""", 'formal'),
- ("""I might be seeing them in a few months!""", 'informal'),
- ("""I called to say 'I Love You""", 'formal'),
- ("""that´s why they needed to open that hatch so much!""", 'informal'),
- (
- """I would most likely not vote for him, although I believe Melania would be the most attractive First Lady in our country's history.""",
- 'formal'),
- ("""I do not hate him.""", 'formal'),
- ("""He's supposed to be in jail!""", 'informal'),
- ("""i thought that she did an outstanding job in the movie""", 'informal'),
- ("""Nicole Kidman, I love her eyes""", 'informal'),
- ("""Youtube.com also features many of the current funny ads.""", 'formal'),
- ("""I enjoy watching my companion attempt to role-play with them.""", 'formal'),
- ("""omg i love that song im listening to it right now""", 'informal'),
- ("""Some of my favorite television series are Monk, The Dukes of Hazzard, Miami Vice, and The Simpsons.""",
- 'formal'),
- ("""I have a desire to produce videos on Full Metal Alchemist.""", 'formal'),
- ("""tell him you want a 3 way with another hot girl""", 'informal'),
- (
- """I would travel to that location and physically assault you at this very moment, however, I am unable to swim.""",
- 'formal'),
- ("""No, no, no that was WITNESS...""", 'informal'),
- ("""aneways shonenjump.com is cool and yeah narutos awsum""", 'informal'),
- (
- """Your mother is so unintelligent that she was hit by a cup and told the police that she was mugged.""", 'formal'),
- ("""You must be creative and find something to challange us.""", 'formal'),
- ("""i think they would have, quite a shame isn't it""", 'informal'),
- ("""I am watching it right now.""", 'formal'),
- ("""I do not know; the person who invented the names had attention deficit disorder.""", 'formal'),
- ("""im a huge green day fan!!!!!""", 'informal'),
- ("""I believe, rather, that they are not very smart on this topic.""", 'formal'),
- ("""Of course it is Oprah, because she has been providing better advice for a longer time.""", 'formal'),
- ("""Chicken Little my son loves that movie I have to watch at least 4 times a day!""", 'informal'),
- ("""That is the key point, that you fell asleep.""", 'formal'),
- ("""A brunette female, a blonde, and person with red hair walked down a street.""", 'formal'),
- ("""who is your best bet for american idol season five""", 'informal'),
- ("""That is funny. Girls need to be a part of everything.""", 'formal'),
- ("""In point of fact, Chris's performance looked like the encoure performed at a Genesis concert.""", 'formal'),
- ("""In my time, Emo was a comedian.""", 'formal'),
- ("""my age gas prices and my blood pressure LOL""", 'informal'),
- ("""Moriarty and so forth, but what character did the Peruvian actor portray?""", 'formal'),
- ("""What did the beaver say to the log?""", 'formal'),
- ("""Where in the world do you come up with these questions????""", 'informal'),
- ("""even though i also agree that the girls on Love Hina are pretty scrumptious""", 'informal'),
- ("""I miss Aaliyah, she was a great singer.""", 'formal'),
- ("""and the blond says Great they already put me on my first murder mystery case""", 'informal'),
- ]
- if __name__ == '__main__':
- sample = input()
- train_data1 = train_data[:int(len(train_data)*0.4)]
- train_data2 = train_data[int(len(train_data)*0.4) : int(len(train_data)*0.8)]
- test_data = train_data[int(len(train_data)*0.8):]
- klasa1 = NaiveBayes(get_words)
- klasa2 = NaiveBayes(get_words)
- brojac1 = 0
- for d in train_data1:
- klasa1.train(d[0],d[1])
- for d in train_data2:
- klasa2.train(d[0],d[1])
- for t in test_data:
- y1 = klasa1.classify_document(t[0])
- y2 = klasa2.classify_document(t[0])
- if y1 == t[1] and y2 == t[1]:
- brojac1 += 1
- print(brojac1/len(test_data))
- x1 = klasa1.classify_document(sample)
- x2 = klasa2.classify_document(sample)
- if x1 == x2:
- print(x1)
- else:
- print("unknown")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement