kleine Mathe-Spielereien

mit matplotlib, NumPy, pandas, SciPy, SymPy und weiteren mathematischen Programmbibliotheken.
OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

17.6.2024
Es hat lange gedauert, bis ich sicher war, diese
Thematik in etwa verstanden zu haben.
Insgesamt ist dieses Thema sehr um fangreich und kompliziert.
Für mich als Anfänger nur ein Scgnupperkurs.
Hier eine Darsllung der confusion matrix
als Ereignisbaum.
OSWALD

Code: Alles auswählen



from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

#Laden des Iris-Datensatzes
iris = load_iris()
X = iris.data 

y = iris.target

#Aufteilung der Daten in Trainings- und Testsets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=1)

#Erstellen des Entscheidungsbaum-Klassifikators
clf = DecisionTreeClassifier(criterion='gini', max_depth=None, random_state=1)

#Trainieren des Modells
clf.fit(X_train, y_train)

#Vorhersagen auf dem Testset
y_pred = clf.predict(X_test)

#Bewertung der Modellleistung
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")

#Ausgabe der Confusion Matrix und des Klassifikationsberichts
print("Confusion Matrix:")
print(confusion_matrix(y_test, y_pred))
print("Classification Report:")
print(classification_report(y_test, y_pred))

import matplotlib.pyplot as plt
from sklearn.tree import plot_tree

# Visualisierung des Entscheidungsbaums
plt.figure(figsize=(15, 10))
plot_tree(clf, feature_names=iris.feature_names, class_names=iris.target_names, filled=True, rounded=True)
plt.show()

OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

19.6.2024
Abschliessend zum Thema noch ein Beispiel , bei dem ich
" etwas hinter die Kulissen geschaut" habe.
Insgesamt ist diese Thematik sehr kompliziert.
Gute Zeit OSWALD

Code: Alles auswählen


rom sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import make_pipeline
import matplotlib.pyplot as plt

#       breast cancer Datenatz  laden
bc = datasets.load_breast_cancer()
print()
print("      Das ist der 'breast_cancer' Datensatz")
print(bc)
X = bc.data
y = bc.target
print(bc.target)
#
#      Trainieren #
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=1, stratify=y)
#0.3
#      Pipeline trainieren  
#
pipeline = make_pipeline(StandardScaler(),
RandomForestClassifier(n_estimators=10, max_features=5, max_depth=2, random_state=1))
 
#    Pipeline - Schätzer     fitten
pipeline.fit(X_train, y_train)
  
from sklearn.metrics import confusion_matrix
#
#      Vorhersagen
#
y_pred = pipeline.predict(X_test)

#  Confusion Matrix berechnen
conf_matrix = confusion_matrix(y_true=y_test, y_pred=y_pred)
# Visualisierung mit Matplotlib
#
fig, ax = plt.subplots(figsize=(7.5, 7.5))
ax.matshow(conf_matrix, cmap=plt.cm.Reds, alpha=0.4)  # matshow(() : Anzeige des Arrays  als  C-Matrix 2D . Farben

print("aktualierte Confusions-Matrix   : "  ,conf_matrix)       #      Aktualisierte    2D -  Confusions-Matrix  

for i in range(conf_matrix.shape[0]):
    for j in range(conf_matrix.shape[1]):
        ax.text(x=j, y=i,s=conf_matrix[i, j], va='center', ha='center', size='xx-large')

plt.xlabel('  Vorhersage      ', fontsize=18)
plt.ylabel('  Aktuell             '  , fontsize=18)
plt.title('Confusion Matrix',fontsize = 18)
plt.show()

#Extract the true positive, true negative, false positive, and false negative values from the confusion matrix
tn, fp, fn, tp = conf_matrix.ravel()
 
# Print the true positive, true negative, false positive, and false negative values
print("True Positive (TP): ", tp)
print("True Negative (TN): ", tn)
print("False Positive (FP): ", fp)
print("False Negative (FN): ", fn)
 
# Calculate accuracy
accuracy = (tp + tn) / (tp + tn + fp + fn)
 
# Calculate precision
precision = tp / (tp + fp)
 
# Calculate recall
recall = tp / (tp + fn)
 
# Calculate F1-score
f1_score = 2 * (precision * recall) / (precision + recall)
 
# Print the formulas for accuracy, precision, recall, and F1-score
print("\n\nFormulas:")
print("Accuracy: (TP + TN) / (TP + TN + FP + FN)")
print("Precision: TP / (TP + FP)")
print("Recall: TP / (TP + FN)")
print("F1-score: 2 * (Precision * Recall) / (Precision + Recall)")
 
# Print the accuracy, precision, recall, and F1-score
print("\n\nMetrics:")
print("Genauigkeit: ", round(accuracy, 2))
print("Präcision: ", round(precision, 2))    #   tatsächlich erkrankte Patienten
print("Recall: ", round(recall, 2))               #   alle als krank erkannte  ""
print("F1-score: ", round(f1_score, 2))     #   harmon.-Mittel aus Präcision und recall

OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

20.6.2024
Die Confusion Matrix findet oft Anwendung
zur Qualitätskontrolle in machine learn. z.B.
in der Gesichtserkennung.
Inndem komplizierten Code finden sich die bekannten
Funktionen(trainieren,testen,optimieren,klassifizieren, normslisieren) usw.
Die einfache 2D Matrix reicht aber dafür nicht mehr aus, wie das Beispiel
zeigt. Gute Zeit OSWALD

Code: Alles auswählen

from time import time
import matplotlib.pyplot as plt
from scipy.stats import loguniform

from sklearn.datasets import fetch_lfw_people
from sklearn.decomposition import PCA
from sklearn.metrics import ConfusionMatrixDisplay, classification_report
from sklearn.model_selection import RandomizedSearchCV, train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
#Laden Sie die Daten herunter, falls sie nicht bereits auf der Festplatte sind,
#und laden Sie sie als Numpy-Arrays

lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)

# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape

# for machine learning we use the 2 data directly (as relative pixel
# positions info is ignored by this model)
X = lfw_people.data
n_features = X.shape[1]

# the label to predict is the id of the person
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]

print("Total dataset size:")
print("n_samples: %d" % n_samples)
print("n_features: %d" % n_features)
print("n_classes: %d" % n_classes)
#Total dataset size:
n_samples: 1288
n_features: 1850
n_classes: 7
#Teilen Sie es in einen Trainingssatz und einen Test auf #
#und behalten Sie 25 % der Daten zum Testen.

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42
)

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
#Berechnen Sie eine PCA (Eigengesichter) auf dem Gesichtsdatensatz (der als unbeschrifteter Datensatz behandelt wird): unüberwachte Merkmalsextraktion / Dimensionsreduzierung

n_components = 150

print(
    "Extracting the top %d eigenfaces from %d faces" % (n_components, X_train.shape[0])
)
t0 = time()
pca = PCA(n_components=n_components, svd_solver="randomized", whiten=True).fit(X_train)
print("done in %0.3fs" % (time() - t0))

eigenfaces = pca.components_.reshape((n_components, h, w))

print("Projecting the input data on the eigenfaces orthonormal basis")
t0 = time()
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print("done in %0.3fs" % (time() - t0))
#Extracting the top 150 eigenfaces from 966 faces
#done in 0.089s
#Projecting the input data on the eigenfaces orthonormal basis
#done in 0.006s
#Trainieren eines SVM-Klassifizierungsmodells

print("Fitting the classifier to the training set")
t0 = time()
param_grid = {
    "C": loguniform(1e3, 1e5),
    "gamma": loguniform(1e-4, 1e-1),
}
clf = RandomizedSearchCV(
    SVC(kernel="rbf", class_weight="balanced"), param_grid, n_iter=10
)
clf = clf.fit(X_train_pca, y_train)
print("done in %0.3fs" % (time() - t0))
print("Best estimator found by grid search:")
print(clf.best_estimator_)
#Fitting the classifier to the training set
#done in 5.388s
#Best estimator found by grid search:
SVC(C=76823.03433306456, class_weight='balanced', gamma=0.0034189458230957995)
#Quantitative Bewertung der Modellqualität am Testset

print("Predicting people's names on the test set")
t0 = time()
y_pred = clf.predict(X_test_pca)
print("done in %0.3fs" % (time() - t0))

print(classification_report(y_test, y_pred, target_names=target_names))
ConfusionMatrixDisplay.from_estimator(
    clf, X_test_pca, y_test, display_labels=target_names, xticks_rotation="vertical"
)
plt.tight_layout()
plt.show()

OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

21.6.2024
Wenn ich ein Thema wirklich verstehen will,
muss ich mich mit vielen unterschiedlichen Aspekten
vertraut machen. Deshalb ein weiteres Bespiel aus der
sehr umfanreichen Materie. OSWALD

Code: Alles auswählen


###        Grafische Darstellung der Leistungsfähigkeit eines binären Klassifizierungsmodels.
###        für alle Klassifizierungs-Schwellenwerte  (treshold)

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
import matplotlib.pyplot as plt


#   Logistisches        Regressionsmodell anpassen

url = "https://raw.githubusercontent.com/Statology/Python-Guides/main/default.csv"
data = pd.read_csv(url)
print("Hier die vorliegenden   Daten  anschauen ; ")
print( data)
#    Prädiktorvariablen und die Antwortvariable  voreinstellen
X = data[['student', 'balance', 'income']]  
y = data[['default']]

#     Datensatz in Trainings- (70 %) und Testsätze (30 %) aufteilen
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.5,random_state=0) 

#     Modell  instanziieren
log_regression =      LogisticRegression()

#     Modell mithilfe der Trainingsdaten an
log_regression.fit(X_train,y_train)

#   : Zeichnen Sie die ROC-Kurve
#      TP  Richtig-Positiv-Rate und
#       FP Falsch-Positiv-Rate und erstellen eine ROC-Kurve
#       Metriken definieren
y_pred_proba = log_regression.predict_proba(X_test)[::,1]
fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)
print()
print(fpr)
print()
print(tpr)

#        ROC-Kurve erstellen
plt.plot(fpr,tpr)
plt.ylabel(' TP  True  Positiver Anteil')
plt.xlabel(' FP  False Positiver Anteil')
plt.title("ROC -Kurve  (=Grenzwertoptimierungskurve)")
plt.show()

#  Berechnen der AUC 
#    Je näher AUC    (von 0.5 >  1)   an 1 liegt, desto besser ist das Modell.
     
 
y_pred_proba = log_regression.predict_proba(X_test)[::,1]
fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)
auc = metrics.roc_auc_score(y_test, y_pred_proba)

#       ROC-Kurve erstellen
plt.plot(fpr,tpr,label="         AUC   Fläche unter der Kurve="+str(auc))
plt.ylabel(' TP  True Positive Anteil')
plt.xlabel('  FP False Positive Anteil')
plt.legend(loc=6)
           
plt.title("ROC-Kurve  = [Receiver Operating Characteristic].")
plt.show()


OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

11.7.2024
In den letzten Wochen habe ich mich intensiv
mit folgendem Themenkreis befasst:
Scipy. Numpy,
Matrizen, inversen Matrizen, Determinanten
Matrizenrechnung, Lösung von Gleichungen
etwas Algebra , insgesamt ein riesiges Pensum.
Für alles was ich verstanden habe , versuche ich Beispiele
zu bringen. Mal sehen.
Gute Zeit OSWALD
OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

11.7.2024
Zur Bearbeitung von Matrizen stellt Python zwei Bibliotheken
Verfügung: scipy und numpy
scipy.linalg enthält alle Funktionen die auch in numpy.linalg enthalten sind ,
sowie einige andere, erweiterte Funktionen, die nicht in numpy.linalg. enthalten sind .
Es gibt also zwei Klassen : scipy.linalg und numpy.linalg ,

Mit deren Anwendung aber hat man die schwierige und sehr umfangreiche Thematik noch
lange nicht verstanden. Ein erstes kleines Programm soll das zeigen.
OSWALD

Code: Alles auswählen

 

import numpy as np
print("Das ist eine  quadratische Matrix   ") 
  
a = np.array([[1, 2], [0, 4]])
print(a)
print("Berechnung der Determinanten :   a*d - b*c ") 
np.linalg.det(a)
print(np.linalg.det(a))

a = np.array([[1, 2], [0, 4]])
print(a)
print("Berechnung der Determinanten :   a*d - b*c ") 
np.linalg.det(a)
print(np.linalg.det(a))


print("Das ist  ein Stapel  von Matrizen   ") 
b = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])

print("mit drei Determinanten",np.linalg.det(b))
print("shape :"   ,b.shape)

 
OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

12.7.2024
Hier zeige ich die beiden Matrix-Klassen
an Beispielen
Oswald

# Unterschied np.ARRAY und np.MATRIX
# NumPy-Matrizen simd streng 2-dimensional
# NumPy-Arrays arrays v sind n-dimensional.



# X und Y zwei np.Matrizen , dann X * Y = Matrixmultiplikation.
# X und Y zwei np.ARRAYS , dann X * Y = Komponentenweise Multiplikation.


import numpy as np

x = np.array( ((2,3), (3, 5)) )
y = np.array( ((1,2), (5, -1)) )
x * y
print(x*y)

print()

x = np.matrix( ((2,3), (3, 5)) )
y = np.matrix( ((1,2), (5, -1)) )
print(x * y)
OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

12..7.2024
So kann man eine Matrix invertieren
anschließend der Test.
Alle Beispiele zunächst zur ersten Orientierung
Oswald

Code: Alles auswählen

import numpy as np

a = np.array([[1, 2, 3], [1, 3, 3], [1, 2, 4]])
print("Original-Matrix    :",a)
ainv = np.linalg.inv(a)
print("Matrix invertiert  :"  ,ainv)
print()
print(ainv)
print() 
print("überprüft",np.allclose(np.dot(ainv, a), np.eye(3)))

OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

12.7.2024
Die Multiplikation von Matrizen ist eine sehr wichtige Methode
beim Rechnen mit Matrizen, z.B. beim Lösen von Gleichungen etc
OSWALD

Code: Alles auswählen


######	Multiplikation von 3*4 und 4*3 Matritzen

import numpy as np
A = np.array([[11, 12, 13, 14], 
                      [21, 22, 23, 24], 
                      [31, 32, 33, 34]])
print(A)


B = np.array([[5, 4, 2], 
                      [1, 0, 2], 
                      [3, 8, 2], 
                      [24, 12, 57]])

print(np.dot(A ,B))
#[[ 442  316  870]
# [ 772  556 1500]
# [1102  796 2130]]
#   N E U: Jetzt gibt es für das dot-Produkt auch einen    Infix-Operator, und zwar @:

print(A @ B) 
#[[ 442  316  870]
# [ 772  556 1500]
 #[1102  796 2130]]
#   Damit die Matrizenmultiplikation (also dot)
#   für zwei Matrizen A und B im zweidimensionalen Fall funktionieren kann, muss gelten:

A.shape[-1] == B.shape[-2]

# zur Kontrolle 
print(A.shape[-1] == B.shape[-2]) 
True

OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

12.7.2024
Die Normalisierung von Daten für Matrizen ist unerlässlich
für Berechnungen mit Matrizen und darüber hinaus.
Oswald

Code: Alles auswählen


#                      Matrix normalisieren mit  sklearn und / oder   numpy    

from sklearn.preprocessing import normalize
import numpy 

matrix = numpy.arange(0,27,3).reshape(3,3).astype(numpy.float64)
normed_matrix = normalize(matrix, axis=1, norm='l1')
print("Matrix original  :",matrix)
print()
print("Matrix normalisiert :",normed_matrix)
print()
#########################

print("Matrix normalisieren mit   numpy")
import numpy as np
 
def normalize_2d(matrix):
    # Only this is changed to use 2-norm put 2 instead of 1
    norm = np.linalg.norm(matrix, 1)
    # normalized matrix
    matrix = matrix/norm  
    return matrix
 
# gives and array starting from -2 and ending at 13
array = np.arange(16) - 2 
# converts 1d array to a matrix
matrix = array.reshape(4, 4)  
print("Original  Matrix \n", matrix)
normalized_matrix = normalize_2d(matrix)
print("Normalisierte  Matrix ", normalized_matrix)

OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

12.7.2024
Im folgenden Beispiel
habe ich zunächst eine 3x3 Matrix erstellt.
von dieser die Determinante bestimmt, dann die
matrix invertiert und dann wiederum davon auch die
Determinante bestimmt.
Beim Versuch , drei unbekannte Variablen in einem
lLGS mit numpy.linalg zu errechnen gescheitert.
mit inverser Matrix ist das sehr gut möglich,
hier aber nicht darstellbar.
Mit sympy ginge es wohl auch
.Oswald
OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

es ging irgendwie verloren
OSWALD

Code: Alles auswählen


import numpy as np
from scipy import linalg
A = np.array([[1,3,5],[2,5,1],[2,3,8]])
print(A)
print(np.linalg.det(A)) 
B =np. linalg.inv(A)

print("Inverse Matrix   :" ,np. linalg.inv(B))
print()
print("Determinante   "  ,np.linalg.det(B))           
print(np.linalg.det(B)) 









OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

13.7.2024
Die Lösung von LGS-Gleichungen mit numpy oder scipy
ist sehr einfach.
Hier zwei Beispiele
OSWALD

Code: Alles auswählen


mport  numpy as  np 
a = np.array([[3, 0 ], [0.5, 3]])
print(a)
b = np.array([1, 2])
print(b)
print()
x = np.linalg.solve(a, b)
print(x)

np.allclose(np.dot(a, x), b)
print(np.allclose(np.dot(a, x), b))
True
print()
print("-----------------------------")
###########

a = np.array([[3.5,1], [1,2.7]])
print(a)
b = np.array([9,8])
print(b)
print()

x = np.linalg.solve(a, b)
print(x)
print()

np.allclose(np.dot(a, x), b)
print(np.allclose(np.dot(a, x), b))
True


OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

14.7.2024
*Eigenwerte einer Matrix*
Zur Berechnung von Eigenwerten in Matrizen
kann ich nur ein Programm von Numpy hier beitragen.
Ich habe mich damit beschäftigt. Aber es geht
wohl weit über mein Hobby- Interessen hinaus.
Es ist sicher mehr etwas für Mathematiker.
OSWALD

Code: Alles auswählen


import numpy
import numpy.linalg as linalg

A = numpy.random.rand(10,10)
print("A =    eine  10 x10 -Zufallsmatrix")
print()
print(A) 
ew,ev = linalg.eig(A)    # Eigenwert und  dazugehörigen Eigenvektor bestimmen.
                                     # erechnen der (i.d.R. komplexen) Eigenwerte:

ew_abs = numpy.abs(ew)
                                     #Mit argmax/argmin  Index des maximalen/minimalen Eigenwerts
ew_max = numpy.argmax(ew_abs)
ew_min = numpy.argmin(ew_abs)

#womit wir dann auf den entsprechenden Eintrag zugreifen können:
print("======================================")
print( "max EW                                     ", ew[ew_max])
print( "  + EV                                         ", ev[ew_max])
print( "min EW                                      ", ew[ew_min])
print ("  + EV                                          ", ev[ew_min])



OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

15.7.2024
Die Berechnung von LGS- Gleichungen und
zwei Variablen war einfach.
Gilt Gleiches auch für Nichtlineare (NGS) Gleichungen mit zwei Variablen?
Dieser Frage bin ich nachgegangen:
Sowohl numpy als auch scipy bieten NGS-Lösungen an.
Ich habe scipy untersucht. Es funktioniert einwandfrei.
(Mit Matriizen funktioniert es nicht.)
Hier ein Beispiel .
OSWALD

Code: Alles auswählen


###########################
import scipy
from scipy.optimize import fsolve
import numpy as np
 

def equations(vars):
    x, y = vars
    eq1 = x**2 + np.cos(y**2) - 5
    eq2 = np.cos(x) +3* y +4
    return [eq1, eq2]
initial_guess = [1 , 1 ]
#solution = fsolve(equations, initial_guess)
print("Solution:", solution)

OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

15.7-2024
Ich habe getestet, ob das gleiche Programm auch mit trigonometrischen
Variablen funktioniert. Es gab keine Fehlermeldung. Ich bin aber
keineswegs sicher , ob es sich bei den Ergebnissen nicht um 'Hausnummern'
handeln könnte. Im Moment kann ich das nicht nachprüfen.
OSWALD

Code: Alles auswählen


###########################
import scipy
from scipy.optimize import fsolve
import numpy as np
 

def equations(vars):
    x, y = vars
    eq1 = x**2 + np.cos(y**2) - 5
    eq2 = np.cos(x) +3* y +4
    return [eq1, eq2]
initial_guess = [1 , 1 ]
#solution = fsolve(equations, initial_guess)
print("Solution:", solution)


OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

18.7.2024
Ich habe mich an einen neuen 'Programm' versucht:
Lineare und nichtlineare Gleichungssysteme mit 2 Variablen
in einem einzigen Programm..

Wie soll das gehen ?
Einfache Veränderungen
der Argumente und/ oder
Veränderungen der Elemente der Polynome.
ergibt LGS oder NGS
Fehler bitte melden
OSWALD

Code: Alles auswählen


rom scipy.optimize import minimize  
import numpy as np
from numpy import  *
 
# Define the equations
def equation1(x, y):
#Argumente
    a = 0
    b = 9
    c = sin(y**2)
    return    a* x +   b*y   - c * 25
 #########################################
def equation2(x, y ):
#Argumente
    a = 2
    b = 3
    c = 0
    return a * x**2 + b * y**2     - c * 25


  

# Define the objective function for optimization
def objective(xy):
    x,y = xy
    return equation1(x, y)**2 + equation2(x, y )**2
 # Initial guess
initial_guess = [1, 1]
 
# Perform optimization
result = minimize(objective, initial_guess)
solution_optimization = result.x
 
print("Optimization Method Solution:", solution_optimization)






OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

19.7.2024
Obwohl ich mich gerade mit LGS und NGS-gleichungen
beschäftige , stecke ichj mittendrin im Thema Matrix.
Im oben gezeigten Gleichungssystem habe ich versucht
ein bisschenhinter die Kulissen geschaut und entdeckt,
dass auch hie Matrizen eine Rolle spielen.
Es handelt sich hier um die sog. circular-Natrix , eine von
Dutzenden weiteren Matrizen , die auch bei scipy behandelt
und immer kompliziert werden
Hier eine erweitere Ausgabe des zuketzt gezeigten Codes.
OSWALD
OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

19,7,2024
zum Schluss dieser Thematik noch
Herstellung und Normalisierung einer quadratischen Matrix
OSWALD

Code: Alles auswählen


# Herstellung  einer  q u a d r a t i s c h e n     Matrix
import numpy as np                          
X =  5             #    Reihen      5x5 Matrix
Y=   5             #    Spalten     
LIM =  1        #    z.B. von 0  -   bis  1.0    Matrize  = np.random.rand(X, Y)*LIM              
Matrix  = np.random.rand(X, Y)*LIM   
print("Original-Matrix    :",Matrix)                       
print()
norm = np.linalg.norm(Matrix)       
print("Das ist die sog.Euklidische Norm  :", norm)         
print()

Det =    np.linalg.det(Matrix)
print("Determinante    : ",Det)
print()

normalisiert = Matrix/norm    
print("Hier ist die normalisierte Matrix   :", normalisiert)    


OSWALD
User
Beiträge: 589
Registriert: Freitag 18. März 2022, 17:32

20.7.2024
Die 'mystischen ' Zeichen ,die ich oben erwänt haben,
wollte ich aber dann doch aufklären,
Und dabei bin wieder auf die Rosenbrok -Funktion gestossen,
m,it der ich mich vor löängerer Zeit schon einmal beschäftigt habe.

-Die Rosenbrok Funktion ist eine Testfunktion
Es gibt zahlreiche , etwa 20 analoge Testfunktionen für die Einzieloptimierung
In der angewandten Mathematik sind Testfunktionen , so wie die Rosenbrok-Funktion,
sogenannte künstliche Landschaften , nützlich, Alle sind als 3D Visualisierungen
darstellbar. Alle kann man in alle Rixhtungen skrollen.
Eiigenschaften von Optimierungsalgorithmen sind etwa

Konvergenzrate.
Präzision.
Robustheit.
Allgemeine Leistung.
(Python fasziniert mich inner mehr)

Hier zeige ch diese Funktion

Code: Alles auswählen


from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
import numpy as np
from matplotlib import cm
def f(x1, x2):
    return 100*(x2-x1**2)**2+(x1-1)**2
    x1 = np.linspace(-5, 10)
    x2 = np.linspace(-5, 10)
    X1, X2 = np.meshgrid(x1, x2)
    F = f(x1, x2)
    plt.contour(X1, X2, f(X1, X2))

def plotter(E, A):
  fig = plt.figure(figsize = [12, 8])
  ax = plt.axes(projection='3d')
  ax.plot_surface(X1, X2, f(X1, X2), cmap='jet', alpha=0.8)
  ax.plot_wireframe(X1, X2, f(X1, X2), rcount=15, ccount=15)
  ax.view_init(elev=E, azim=A)
  ax.set_xlabel('X')
  ax.set_ylabel('Y')
  ax.set_zlabel('f(X, Y)')
  ax.contourf(x1, x2, f(X1, X2))
  print("solution 2")
  plotter(45, 45)
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
def f(x1, x2): return 100*(x2-x1**2)**2+(x1-1)**2
x1 = np.linspace(-5, 10)
x2 = np.linspace(-5, 10)
X1, X2 = np.meshgrid(x1, x2)
F = f(x1, x2)
plt.contour(X1, X2, f(X1, X2))

def plotter(E, A):
  fig = plt.figure(figsize = [12, 8])
  ax = plt.axes(projection='3d')
  ax.plot_surface(X1, X2, f(X1, X2), cmap='jet', alpha=0.8)
  ax.plot_wireframe(X1, X2, f(X1, X2), rcount=15, ccount=15)
  ax.view_init(elev=E, azim=A)
  ax.set_xlabel('X')
  ax.set_ylabel('Y')
  ax.set_zlabel('f(X, Y)')
  ax.contourf(x1, x2, f(X1, X2))
  print("solution 2")
plotter(45, 45)
from ipywidgets import interactive
iplot = interactive(plotter, E = (-90,90, 5),
                            A = (-90, 90, 5))
plt.show()
iplot

Antworten