Inhalt

Aktueller Ordner: /
πŸ““ Jupyter Notebook - Kernel: Python (Pyodide)
πŸ“ Markdown Zelle #1
Die Wahrscheinlichkeiten werden als Gleitkommazahlen zwischen 0 und 1 dargestellt und die Wahrscheinlichkeitsverteilungen fΓΌr jedes nicht-terminale Symbol in einem WΓΆrterbuch gespeichert. Das Bayes-Netz wird mit einem Pandas DataFrame definiert, wobei jede Zeile eine gerichtete Kante von einem Knoten zu einem anderen zusammen mit der Wahrscheinlichkeit der Kante darstellt.
🧩 Code Zelle #2
import numpy as np
import pandas as pd
import random

# Define the grammar rules and their probabilities
grammar = {
    "anfang": {"s vkg": 1.0},
    "s vkg": {"ende": 1.0},
    "kbbd": {"vbbd": 1.0},
    "kba": {"vba": 1.0},
    "kae": {"vae": 1.0},
    "kaa": {"vaa": 1.0},
    "s bbd": {"s ba": 1.0},
    "s ae": {"s ae": 0.5, "s aa": 0.5},
    "s ae": {"s aa": 1.0},
    "s b": {"s b": 0.5, "s a": 0.5},
    "s b": {"s a": 1.0},
    "s vt": {"s b s b": 0.5, "s b s a": 0.25, "s a s b": 0.25},
    "s vt": {"s b s a": 0.5, "s a s b": 0.5},
    "s vt": {"s a s a": 1.0},
    "kbg": {"vbg": 1.0},
    "kav": {"vav": 1.0},
    "s bg": {"s vt s av": 1.0},
    "s vt": {"s vt": 0.5, "s av": 0.5},
    "s vt": {"s av": 1.0},
}

# Define the probability distributions for each nonterminal symbol
prob_dist = {}
for nt in grammar:
    for rhs in grammar[nt]:
        prob = grammar[nt][rhs]
        prob_dist[(nt, rhs)] = prob

# Define the Bayes net using the probability distributions
bayes_net = pd.DataFrame(columns=["From", "To", "Prob"])
for nt in grammar:
    for rhs in grammar[nt]:
        for tok in rhs.split():
            bayes_net = bayes_net.append({"From": nt, "To": tok, "Prob": prob_dist[(nt, rhs)]}, ignore_index=True)

# Define the starting symbol and the ending symbol
start_symbol = "anfang"
end_symbol = "ende"

# Define a function to generate a sentence using the grammar
def generate_sentence():
    stack = [start_symbol]
    sentence = []
    while len(stack) > 0:
        curr_nt = stack.pop()
        if curr_nt in grammar:
            rhs_options = list(grammar[curr_nt].keys())
            rhs_probs = [grammar[curr_nt][rhs] for rhs in rhs_options]
            chosen_rhs = np.random.choice(rhs_options, p=rhs_probs)
            stack.extend(reversed(chosen_rhs.split()))
        else:
            sentence.append(curr_nt)
    return sentence

# Generate 10 sentences using the grammar
for i in range(10):
    sentence = generate_sentence()
    print(" ".join(sentence))
🧩 Code Zelle #3