Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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'),
- ]
- import re
- def get_words(doc, words_to_ignore=None):
- """Поделба на документот на зборови. Стрингот се дели на зборови според
- празните места и интерпукциските знаци
- :param doc: документ
- :type doc: str
- :return: множество со зборовите кои се појавуваат во дадениот документ
- :rtype: set(str)
- """
- # подели го документот на зборови и конвертирај ги во мали букви
- # па потоа стави ги во резултатот ако нивната должина е >2 и <20
- words = set()
- letters_only = re.sub("[^a-zA-Z]", # Search for all non-letters
- " ", # Replace all non-letters with spaces
- str(doc))
- for word in re.split('\\W+', letters_only):
- if words_to_ignore is None:
- if 2 < len(word) < 20:
- words.add(word.lower())
- else:
- if 2 < len(word) < 20 and word.lower() not in words_to_ignore:
- 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, words_to_ignore=None):
- """Тренирање на класификаторот. Новиот предмет (документ)
- :param item: нов предмет (документ)
- :param current_category: категорија
- :return: None
- """
- # Се земаат атрибутите (зборовите) во предметот (документот)
- features = self.get_features(item, words_to_ignore)
- # Се зголемува бројот на секој атрибут во оваа категорија
- 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, words_to_ignore=None):
- """Ја враќа веројатноста на документот да е од класата current_category
- (current_category е однапред позната)
- :param item: документ
- :param current_category: категорија
- :return:
- """
- # земи ги зборовите од документот item
- features = self.get_features(item, words_to_ignore)
- # помножи ги веројатностите на сите зборови
- p = 1
- for currentFeature in features:
- p *= self.weighted_probability(currentFeature, current_category,
- self.get_feature_per_category_probability)
- return p
- def get_category_probability_for_document(self, item, current_category, words_to_ignore=None):
- """Ја враќа веројатноста на класата ако е познат документот
- :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,
- words_to_ignore)
- # Bayes Theorem
- return calculate_document_probability_in_class * cat_prob / (1.0 / self.get_total_count())
- def classify_document(self, item, default=None, words_to_ignore=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, words_to_ignore)
- 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
- import math
- if __name__ == '__main__':
- sample = input()
- number1 = math.floor((40 / 100) * len(train_data))
- number2 = number1 * 2
- baesov_classificator1 = train_data[:number1]
- baesov_classificator2 = train_data[number1:number2]
- test_case = train_data[number2:]
- train_model1 = NaiveBayes(get_words)
- train_model2 = NaiveBayes(get_words)
- for item in baesov_classificator1:
- train_model1.train(item[0], item[1])
- for item in baesov_classificator2:
- train_model2.train(item[0], item[1])
- counter = 0
- for row in test_case:
- predicted_class1 = train_model1.classify_document(row)
- predicted_class2 = train_model2.classify_document(row)
- if row[-1] == predicted_class1 and row[-1] == predicted_class2 and predicted_class1 == predicted_class2:
- counter += 1
- accuracy = counter / len(test_case)
- predicted_class1 = train_model1.classify_document(sample)
- predicted_class2 = train_model2.classify_document(sample)
- print(accuracy)
- if predicted_class1 == predicted_class2:
- print(predicted_class1)
- else:
- print("unknown")
Add Comment
Please, Sign In to add comment