2021-05-08 23:00:32 +02:00
|
|
|
'''
|
|
|
|
Autor: Dominik Strzałko
|
|
|
|
Data: 05.08.2021
|
|
|
|
Zadanie: naiwny bayes2 gotowa biblioteka (Skeptic vs paranormal subreddits)
|
2021-05-08 23:02:56 +02:00
|
|
|
|
|
|
|
Wyniki z geval:
|
|
|
|
Likelihood 0.0000
|
|
|
|
Accuracy 0.7367
|
|
|
|
F1.0 0.4367
|
|
|
|
Precision 0.8997
|
|
|
|
Recall 0.2883
|
2021-05-08 23:00:32 +02:00
|
|
|
'''
|
2021-05-08 19:02:05 +02:00
|
|
|
import numpy as np
|
|
|
|
from sklearn.preprocessing import LabelEncoder
|
|
|
|
from sklearn.naive_bayes import MultinomialNB
|
2021-05-08 22:45:55 +02:00
|
|
|
from sklearn.pipeline import make_pipeline
|
2021-05-08 19:02:05 +02:00
|
|
|
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
|
|
|
2021-05-08 23:00:32 +02:00
|
|
|
def open_tsv(tsv):
|
|
|
|
'''
|
|
|
|
Funkcja do zamiany plików tsv jako listy linii tekstu.
|
|
|
|
|
|
|
|
Na wejście potrzebuje ścieżkę do pliku .tsv
|
|
|
|
|
|
|
|
np. X = open_tsv("train/expected.tsv")
|
|
|
|
'''
|
|
|
|
with open(tsv) as f:
|
|
|
|
return f.readlines()
|
|
|
|
|
2021-05-08 22:45:55 +02:00
|
|
|
def Create_model(X_tsv, Y_tsv):
|
2021-05-08 23:00:32 +02:00
|
|
|
'''
|
|
|
|
Funkcja przeznaczona do tworzenia modelu uczenia maszynowego.
|
|
|
|
|
|
|
|
Na wejście trzeba podać zbiór X_train oraz Y_train w formie plików tsv.
|
2021-05-08 19:02:05 +02:00
|
|
|
|
2021-05-08 23:00:32 +02:00
|
|
|
np. model = Create_model("train/in.tsv", "train/expected.tsv")
|
|
|
|
'''
|
2021-05-08 19:02:05 +02:00
|
|
|
|
2021-05-08 23:00:32 +02:00
|
|
|
X = open_tsv(X_tsv)
|
|
|
|
Y = open_tsv(Y_tsv)
|
2021-05-08 19:02:05 +02:00
|
|
|
|
2021-05-08 22:45:55 +02:00
|
|
|
Y = LabelEncoder().fit_transform(Y)
|
|
|
|
pipeline = make_pipeline(TfidfVectorizer(),MultinomialNB())
|
2021-05-08 19:02:05 +02:00
|
|
|
|
2021-05-08 22:45:55 +02:00
|
|
|
return pipeline.fit(X, Y)
|
2021-05-08 19:02:05 +02:00
|
|
|
|
2021-05-08 22:45:55 +02:00
|
|
|
|
|
|
|
def predict(model, X_tsv, file_name):
|
2021-05-08 23:00:32 +02:00
|
|
|
'''
|
|
|
|
Funkcja przeznaczona do predykcji wyników na podstawie modelu oraz zbiory X. trzecim argumentem w funkcji jest nazwa pliku z predykcjami, do zapisania na dysku.
|
2021-05-08 22:45:55 +02:00
|
|
|
|
2021-05-08 23:00:32 +02:00
|
|
|
np. predict(model, "dev-0/in.tsv", "dev-0/out.tsv")
|
|
|
|
'''
|
|
|
|
X = open_tsv(X_tsv)
|
2021-05-08 22:45:55 +02:00
|
|
|
|
|
|
|
prediction = model.predict(X)
|
|
|
|
np.savetxt(file_name, prediction, fmt='%d')
|
2021-05-08 19:02:05 +02:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
2021-05-08 23:02:56 +02:00
|
|
|
|
2021-05-08 22:45:55 +02:00
|
|
|
model = Create_model("train/in.tsv", "train/expected.tsv")
|
|
|
|
|
2021-05-08 19:02:05 +02:00
|
|
|
predict(model, "dev-0/in.tsv", "dev-0/out.tsv")
|
|
|
|
predict(model, "test-A/in.tsv", "test-A/out.tsv")
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|