<jupyter_start><jupyter_text>Modelltrening for å gjette NVDBJira tasks<jupyter_code># -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import spacy
import os
import sys
import re
import operator<jupyter_output><empty_output><jupyter_text>Hent inn jira-data- fjern null-verdier og inspiser datasett<jupyter_code>jira = os.path.join(os.getcwd(), 'data', 'jira.csv')
df = pd.read_csv(jira, usecols=["Description", "Component/s"])
df.columns = ['text', 'label']
df = df.dropna().reset_index(drop=True)
df
df.iloc[920].text<jupyter_output><empty_output><jupyter_text>Mye rart i dataen her. Vask den!<jupyter_code>spacy_model = 'nb_core_news_lg'
nlp = spacy.load(spacy_model)
nlp.add_pipe('sentencizer')
strip_bracket = r'(?<=\[).*?(?=\])'
strip_paren = r'(?<=\().*?(?=\))'
strip_tag = r'(?<=\<).*?(?=\>)'
valid_words = r'[^\s\-][\w \-]+[^\s\-]'

def flat_map(xs):
    ys = []
    for x in xs:
        ys.extend(x)
    return ys

def hyphen_no_date(word):
    if '-' in word:
        return word.split('-')[0].isalpha()
    return word.isalnum()

def clear_jira(text):
    text = re.sub(strip_bracket, '', text)
    text = re.sub(strip_paren, '', text)
    text = re.sub(strip_tag, '', text)
    text = ' '.join([w for w in text.splitlines() if len(w) > 0])
    text = ' '.join(re.findall(valid_words, text))    
    text = [w for w in text.split(' ') if hyphen_no_date(w)]
    text = [w for w in text if w[0] != '!']  # avoid image tags (!image-hash)
    
    text = ' '.join(text)
    return text

def clean(row):
    text = clear_jira(row.text)
    doc = nlp(text)
    row['text'] = text.lower()    
    row['label'] = row['label'].lower()

    return row

df = df.apply(clean, axis=1)
def get_texts_from_name(name, field='text'):
    return list(df[(df.label.str.contains(name.lower()))][field])

get_texts_from_name('vegkart')[:5]<jupyter_output><empty_output><jupyter_text>Dette ser bedre ut! Rydd opp enda mer :)- start med å fjerne labels med for få eksempler<jupyter_code>data.label.value_counts()
THRESHOLD = 60
labels = [x for x, y in data.label.value_counts().items() if y > THRESHOLD]
data = data[data.label.isin(labels)]
data.label.value_counts()<jupyter_output><empty_output><jupyter_text>Kategoriser dataen for å være snill med maskinlæringsmodeller<jupyter_code>def categorize_labels(row):
    row['cats'] = { l : l == row.label for l in labels }
    return row

data = data.apply(categorize_labels, axis=1)
data.drop(['label'], axis=1, inplace=True)
data<jupyter_output><empty_output><jupyter_text>Splitt opp i trening og valideringssett<jupyter_code>from sklearn.model_selection import train_test_split
train, test = train_test_split(data, test_size=0.2)
test
def make_docs(data):   
    docs = []
    # nlp.pipe([texts]) is way faster than running nlp(text) for each text
    # as_tuples allows us to pass in a tuple, the first one is treated as text
    # the second one will get returned as it is.
    for doc, label in nlp.pipe(data, as_tuples=True):
        doc.cats = label
        # put them into a nice list
        docs.append(doc)
    
    return docs
from spacy.tokens import DocBin
_test = list(zip(test.text.tolist(), test.cats.tolist()))
_train = list(zip(train.text.tolist(), train.cats.tolist()))

train_docs = make_docs(_train)
test_docs = make_docs(_test)
doc_bin = DocBin(docs=train_docs)
doc_bin.to_disk("./data/train.spacy")
doc_bin = DocBin(docs=test_docs)
doc_bin.to_disk("./data/valid.spacy")
nlp = spacy.load("output/model-best")
text = ""
print("type : ‘quit’ to exit")
# predict the sentiment until someone writes quit
while text != "quit":
    text = input("Skriv noe for : ")
    doc = nlp(text)
    print(doc.cats)
x = {'datafangst': 0.3518565595149994, 'les-api': 0.44431495666503906, 'skriv-api': 0.3457692861557007, 'vegkart': 0.5625988841056824, 'rapportgenerator': 0.4080062210559845, 'nvdb-ind': 0.38103434443473816}
x<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15681299162649073, 'fraction_numerical': 0.03019538188277087, 'mean_word_length': 4.437241379310345, 'pattern_counts': {'":': 1, '<': 29, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '340919', 'license': 'MIT', 'n_tokens_mistral': 1595, 'n_tokens_neox': 1511, 'n_words': 338, 'path': 'eksamensretting/spacy/parse Jira.ipynb', 'repo_name': 'ph10m/NorNLP', 'size': '3941'}