Files
KI/P4/AI_41.ipynb
2025-11-21 16:48:18 +01:00

228 lines
7.9 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"id": "fd9c3cd6",
"metadata": {},
"source": [
"# Perceptron"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "e484400f",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"class Perceptron():\n",
" def __init__(self):\n",
" \"\"\"\n",
" Initialisiert das Perceptron mit zufälligen Gewichten\n",
" \n",
" Die Gewichte werden zwischen -1 und 1 für 3 Eingangssignale initialisiert.\n",
" \"\"\"\n",
" # Initialisiere Gewichte zufällig zwischen -1 und 1 für 3 Eingänge\n",
" self.synaptic_weights = 2 * np.random.random((3, 1)) - 1\n",
"\n",
" def sigmoid(self, x):\n",
" \"\"\"\n",
" Sigmoid-Aktivierungsfunktion.\n",
" \n",
" Args:\n",
" x: Eingabewert oder Array von Eingabewerten\n",
" \n",
" Returns:\n",
" Sigmoid-Transformation: S(x) = 1/(1 + e^(-x))\n",
" \"\"\"\n",
" return 1 / (1 + np.exp(-x))\n",
"\n",
" def sigmoid_derivative(self, x):\n",
" \"\"\"\n",
" Ableitung der Sigmoid-Funktion\n",
" \n",
" Args:\n",
" x: Sigmoid-Ausgabewert (bereits durch Sigmoid-Funktion transformiert)\n",
" \n",
" Returns:\n",
" Ableitung: Ṡ(x) = S(x) * (1 - S(x))\n",
" \"\"\"\n",
" return x * (1 - x)\n",
"\n",
" def think(self, inputs):\n",
" \"\"\"\n",
" Ein \"Denkschritt\" des Perceptrons für gegebene Eingaben.\n",
" \n",
" Args:\n",
" inputs: Array der Eingangssignale [I1, I2, I3]\n",
" \n",
" Returns:\n",
" Ausgabe des Perceptrons nach O = S(I × W)\n",
" \"\"\"\n",
" # Berechne gewichtete Summe und wende Sigmoid-Funktion an\n",
" return self.sigmoid(np.dot(inputs, self.synaptic_weights))\n",
"\n",
" def train(self, inputs, targets, iterations):\n",
" \"\"\"\n",
" Trainingsschleife mit Backpropagation und Gewichtsanpassungen.\n",
" \n",
" Args:\n",
" inputs: Trainings-Eingangsdaten (4x3 Matrix)\n",
" targets: Ziel-Ausgangsdaten (4x1 Matrix)\n",
" iterations: Anzahl der Trainingsiterationen\n",
" \"\"\"\n",
" for i in range(iterations):\n",
" # Vorwärtspropagation: Berechne Ausgabe\n",
" output = self.think(inputs)\n",
" \n",
" # Berechne Fehler: E_out = T - O\n",
" error = targets - output\n",
" \n",
" # Backpropagation: Berechne Gewichtsanpassungen\n",
" # ΔW = (Fehler * Sigmoid_Ableitung(Ausgabe)) × Eingaben^T\n",
" adjustments = np.dot(inputs.T, error * self.sigmoid_derivative(output))\n",
" \n",
" # Aktualisiere Gewichte: W = W + ΔW\n",
" self.synaptic_weights += adjustments"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "d3e6debc",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Zufällige synaptische Gewichte vor dem Training:\n",
"[[-0.24139241 -0.39997757 -0.17940957]]\n",
"\n",
"Trainiere das Perceptron...\n",
"\n",
"Synaptische Gewichte nach dem Training:\n",
"[[ 9.15628869 0.34019788 -4.91951613]]\n",
"\n",
"Test mit Trainingsdaten:\n",
"Eingabe: [0 0 1] → Ausgabe: 0.0072 (Ziel: 0)\n",
"Eingabe: [1 1 1] → Ausgabe: 0.9898 (Ziel: 1)\n",
"Eingabe: [1 0 0] → Ausgabe: 0.9999 (Ziel: 1)\n",
"Eingabe: [0 1 1] → Ausgabe: 0.0102 (Ziel: 0)\n",
"\n",
"Test mit neuer Eingabe [1, 1, 0]:\n",
"Eingabe: [1 1 0] → Vorhersage: 0.9999\n",
"\n",
"==================================================\n",
"Interaktive Eingabe:\n",
"\n",
"Geben Sie Werte für I1, I2, I3 ein (getrennt durch Kommas):\n",
" Perceptrons Überzeugung für [1. 0. 1.]: 0.9858\n",
"\n",
"Geben Sie Werte für I1, I2, I3 ein (getrennt durch Kommas):\n",
" Perceptrons Überzeugung für [1. 1. 0.]: 0.9999\n",
"\n",
"Geben Sie Werte für I1, I2, I3 ein (getrennt durch Kommas):\n",
"Programm beendet.\n"
]
}
],
"source": [
"# Erstelle Perceptron-Instanz\n",
"p = Perceptron()\n",
"\n",
"# Trainingsdaten\n",
"training_inputs = np.array([[0, 0, 1],\n",
" [1, 1, 1], \n",
" [1, 0, 0],\n",
" [0, 1, 1]])\n",
"\n",
"training_targets = np.array([[0, 1, 1, 0]]).T\n",
"\n",
"print(\"Zufällige synaptische Gewichte vor dem Training:\")\n",
"print(p.synaptic_weights.T)\n",
"\n",
"# Trainiere das Perceptron\n",
"print(\"\\nTrainiere das Perceptron...\")\n",
"p.train(training_inputs, training_targets, 10000)\n",
"\n",
"print(\"\\nSynaptische Gewichte nach dem Training:\")\n",
"print(p.synaptic_weights.T)\n",
"\n",
"# Teste das Perceptron mit Trainingsdaten\n",
"print(\"\\nTest mit Trainingsdaten:\")\n",
"for i, inp in enumerate(training_inputs):\n",
" output = p.think(inp.reshape(1, -1))\n",
" print(f\"Eingabe: {inp} → Ausgabe: {output[0][0]:.4f} (Ziel: {training_targets[i][0]})\")\n",
"\n",
"# Teste mit neuen Daten [1, 1, 0]\n",
"print(\"\\nTest mit neuer Eingabe [1, 1, 0]:\")\n",
"new_input = np.array([1, 1, 0])\n",
"prediction = p.think(new_input.reshape(1, -1))\n",
"print(f\"Eingabe: {new_input} → Vorhersage: {prediction[0][0]:.4f}\")\n",
"\n",
"# Interaktiver Teil für Jupyter Notebook\n",
"print(\"\\n\" + \"=\"*50)\n",
"print(\"Interaktive Eingabe:\")\n",
"\n",
"while True:\n",
" try:\n",
" print(\"\\nGeben Sie Werte für I1, I2, I3 ein (getrennt durch Kommas):\")\n",
" user_input = input(\"I1, I2, I3: \")\n",
" \n",
" # Prüfe auf Beenden-Kommandos\n",
" if user_input.lower() in ['quit', 'exit', 'q', 'beenden']:\n",
" print(\"Programm beendet.\")\n",
" break\n",
" \n",
" # Parse Benutzereingabe\n",
" values = [float(x.strip()) for x in user_input.split(',')]\n",
" if len(values) != 3:\n",
" print(\" Fehler: Bitte geben Sie genau 3 Werte getrennt durch Kommas ein.\")\n",
" print(\" Beispiel: 1,0,1 oder 0.5,1,0\")\n",
" continue\n",
" \n",
" # Teste das Perceptron\n",
" user_array = np.array(values)\n",
" result = p.think(user_array.reshape(1, -1))\n",
" \n",
" # Formatierte Ausgabe\n",
" print(f\" Perceptrons Überzeugung für {user_array}: {result[0][0]:.4f}\")\n",
" \n",
" except (ValueError, IndexError):\n",
" print(\" Ungültige Eingabe! Verwenden Sie das Format: 1,0,1\")\n",
" print(\" Oder geben Sie 'quit' zum Beenden ein.\")\n",
" except KeyboardInterrupt:\n",
" print(\"\\n\\n Programm durch Keyboard-Interrupt beendet (Strg+C)\")\n",
" break\n",
" except EOFError:\n",
" print(\"\\n\\n Eingabe beendet (Strg+D)\")\n",
" break"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".env",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.19"
}
},
"nbformat": 4,
"nbformat_minor": 5
}