kleine Mathe-Spielereien

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

jetzt:

Code: Alles auswählen



# Defining equations to be solved
# in diagonally dominant form


f1 = lambda x,y,z: (17-y+2*z)/20
f2 = lambda x,y,z: (18-3*x+z)/20
f3 = lambda x,y,z: (25-2*x+3*y)/20

 
# Initial setup
x0 = 0
y0 = 0
z0 = 0
count = 1

# Reading tolerable error
e = float(input('Enter tolerable error: '))

# Implementation of Gauss Seidel Iteration
print('\nCount\tx\ty\tz\n')

condition = True

while condition:
    x1 = f1(x0,y0,z0)
    y1 = f2(x1,y0,z0)
    z1 = f3(x1,y0,z0)


    print('%d\t%0.4f\t%0.4f\t%0.4f\n' %(count, x1,y1,z1))
    e1 = abs(x0-x1);
    e2 = abs(y0-y1);
    e3 = abs(z0-z1);
    
    count += 1
    x0 = x1
    y0 = y1
    z0 = z1
    
    condition = e1>e and e2>e and e3>e
print('\nSolution: x=%0.3f, y=%0.3f and z = %0.3f\n'% (x1,y1,z1))


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

2.12.2024
und nn noch ein HGAUSS Seidel Verfahren, das allerdings von einer
Matrix ausgeht. Also hier wird der Zusammenhang von
Matrizen mit Gleichungssystemen klar.
OSWALD
OSWALD
User
Beiträge: 543
Registriert: Freitag 18. März 2022, 17:32

2.12.2024
Problem mit der Übertragung
?
OSWALD

Code: Alles auswählen


mport numpy as np

def gauss_seidel(A, b, x0, tol, max_iter):
    # Vérifier si la matrice est diagonalement dominante
    if not np.all(np.abs(np.diag(A)) > np.sum(np.abs(A), axis=1) - np.abs(np.diag(A))):
        print("Matrize ohne diagonale  Dominante.Keine Garantie für Konvergenz .")

    # Initialisation
    x = x0.copy()
    iter = 0
    error = tol + 1

    # Itération de Gauss-Seidel
    while error > tol and iter < max_iter:
        x_old = x.copy()
        for i in range(len(b)):
            x[i] = (b[i] - np.dot(A[i,:i], x[:i]) - np.dot(A[i,i+1:], x[i+1:])) / A[i,i]
        iter += 1
        error = np.max(np.abs(x - x_old))

    # Vérification de la convergence
    if iter == max_iter and error > tol:
        print("Keine Gauss-Seidel Konvergenz.")

    return x, iter

# Beispiel
A = np.array([[5, 1, 2, -1], 
              [0,  4, 1, -1],
              [-1,  1,  5, 1],
              [1,  2,  0,  6]])

b = np.array([7, -2, 2, -7])
x0 = np.zeros_like(b)
tol = 1e-3
max_iter = 6

x, iter = gauss_seidel(A, b, x0, tol, max_iter)
print("Solution:")
print(x)
print("Anzahl Iterationen", iter)



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

2.12.2024
Hier eine 'klassische ' Lösung eines Gleichungssytems mit scipy
OSWALD

Code: Alles auswählen


#     Beispiele  für   Lösung  von Gleichungssystemen
#     quadrat.Matrizen  notwendig
     
import scipy.linalg
A =[[-1,  2,  3, 5],
      [13,  4,  6, 3],
      [ 3,  -7,  3, 6],
      [16,  2, 11,-4]]

  

#A = [[  3,   0,  -2,  0,  0],
#     [  2,   6,   0,  0,  0],
#     [  40,   0, -12,  1,  0],
#     [  0,   40,   1,  0,  0],
#     [  0,   0,   40, 10,  7]]

b = [1, 1, 1, 7  ]                       #  

x = scipy.linalg.solve(A, b)
print(x) 




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

2.12.24
Ein weiteres Beispiel aus der Reihe von Näherungsverfahren:
"Bisektion"

Code: Alles auswählen


mport numpy as np
# Dieses Programm implementiert die Bisektionsmethode zum Finden
# der reellen Wurzel nichtlinearer Gleichungen in  Python.
# In diesem Python-Programm sind x0 und x1 zwei anfängliche Schätzungen
# und  e   Ist der tolerierbare Fehler  

#   ein Beispiel für Schätzwerte  :   1. = 1  , 2.  = 20

# Die untersuchte  Function
def f(x):
   return x**3-5*x-9*x  + np.sin(x)
    # return  np.sin(x**2) + 3*np.cos(x**3)
   
   
# Implementing Bisection Method
def bisection(x0,x1,e):
    step = 1
    print('\n\n*** BISECTION METHOD IMPLEMENTATION ***')
    condition = True
    while condition:
        x2 = (x0 + x1)/2
        print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, f(x2)))

        if f(x0) * f(x2) < 0:
            x1 = x2
        else:
            x0 = x2
        
        step = step + 1
        condition = abs(f(x2)) > e

    print('\n Die gesuchte Wurzel =    %0.8f' % x2)

# Input Section
x0 = input('1.Schätzung: ')                         #   Beispiel für Schätzwerte  :   1. = 1  , 2.  = 20
x1 = input('2 Schätzung: ')
e =   input('Tolerabler Fehler: ')

# Converting input to float
x0 = float(x0)
x1 = float(x1)
e   = float(e)

#Note: You can combine above two section like this
# x0 = float(input('First Guess: '))
# x1 = float(input('Second Guess: '))
# e = float(input('Tolerable Error: '))


# Checking Correctness of initial guess values and bisecting
if f(x0) * f(x1) > 0.0:
    print('Die Scätzwerte schliessen den  gesuchten Wert nicht ein.')
    print("noch einmal probieren")
else:
    bisection(x0,x1,e)


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

2.12.2024
Und hier noch eines der diversen Jacobi-Verfahren .
Gute Zeit OSWALD

Code: Alles auswählen


#  Jacobi-Verfahren  aus der  Numpy-Bibliothek zeigt die Aktualität des Jacobi-Verfahrens.
#  Es  arbeitet  änlich wie das  GAUSS-Seidel Verfahren
#  Beide spielen auch in der  KI eine grosse Rolle , etwa so  wie 
# andere Näherungs- und Iterarionsverfahren
import numpy as np

def jacobi_method(A, b, x0, tol=1e-6, max_iterations=100):
    n = len(b)
    x = x0.copy()
       
    errors = []
    
    for iteration in range(max_iterations):
        x_new = np.zeros_like(x)
        
        for i in range(n):
            
            s = sum(A[i][j] * x[j] for j in range(n) if j != i)
            x_new[i] = (b[i] - s) / A[i][i]
                
        error = np.linalg.norm(x_new - x, ord=np.inf)
        errors.append(error)
        
        print(f"Iteration {iteration + 1}: {x_new}, Error: {error}")
                
        if error < tol:
            print(f"Konvergenz  nach  {iteration + 1} iterations.")
            return x_new, errors

        x = x_new    
    print("keine   Konvergenz.")
    return x, errors

A = np.array([[6, -1, 1, 0],
              [-1, 1, -1, 0],
              [0, -1, 4, -1],
              [0, 0, -1, 3]], dtype=float)
b = np.array([5, 15, 15, 15], dtype=float)
x0 = np.zeros(len(b))
solution, errors = jacobi_method(A, b, x0)

print("Lösung:", solution)


import matplotlib.pyplot as plt

plt.plot(range(1, len(errors) + 1), errors, marker='.')
plt.xlabel('ITERATUIONEN')
plt.ylabel('Error')
plt.title('KONVERGENZ der Jacob-Methodei')
plt.yscale('log')  # Skalare zur Visualisierung der  Konvergenz'
plt.grid(True)
plt.show()

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

2.12.2024
Eine weitere Jacobi-Version , schwer verständlich(für mich),
aber offensichtlich ohne Fehler
OSWALD

Code: Alles auswählen


#Program: Jacobi.
import numpy as np
from numpy import *
def Jacobi(A, b, x, num_steps):
#"""My Jacobi function takes four inputs
#A, a square matrix, b, the input of Ax = b,
#x, the initial guess, and num_steps to iterate
#by Jacobi."""
     D = np.diag(np.diag(A),0)
     for k in range(num_steps):
            r = b - A@x
            x = x + np.linalg.inv(D)@r
            print(k+1, x)
            return x


# below are the matrix and vectors to input into my Jacobi function.

A = np.array([[13,1,-1],
                      [1,-4,2.2],
                      [-2,-1,5]])
b = np.array([1.3,-1.5,2.8])
x = np.array([cos(3),-sin(0.31),tanh(0.1)]) # initial guess for Jacobi
Jacobi(A, b, x, 0)
print(Jacobi(A, b, x, 11))


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

9.12.2024
In scipy fand ich eine sehr elegante Lösung
von nichtlinearen Gleichungen mit zwei
unbekannten.
Ich habe diesen Code auf drei u. vier Unbekannte erweitert.
Hier das Ergebnis.
Ansonsten habe ich mich mit Optimierungen und Gradienten befasst.
Insgesamt eine weite und anspruchsvolle Thematik,, der ich mich
zu nähern versuchte. Einige Näherungsversuche stelle ich hier auch vor.
Gute Zeit OSWALD

Code: Alles auswählen


#Lösung von   nicht linearen  Gleichungen

from scipy.optimize import fsolve
import numpy as np

# Original-Code aus  scipy    mt zwei unbekannten
def equations(vars):
    x, y  = vars
    eq1 = x**4 + 5*y  
    eq2 =4* np.cos(x) +2*y  

    return [eq1, eq2]
initial_guess = [1 , 1 ]
solution = fsolve(equations, initial_guess)
print("Ergebnis mit 2 Unbekannten:", solution)

 #                           Drei Unbekannte
def equations(vars):
    x, y,z  = vars
    eq1 = x**4 + 5*y +z
    eq2 =4* np.cos(x) +2*y -z
    eq3 = 2*x**2 -y/2 + np.sin(z+1)
    

    return [eq1, eq2, eq3]
initial_guess = [1 , 1 ,1 ]
solution = fsolve(equations, initial_guess)
print("Ergebnis mit 3 Unbekannten:", solution)

#                      Vier Unbekannte

def equations2(vars):
    x, y,z,v  = vars
    eq1 = x**4 + 5*y +z  - 2*v  
    eq2 =4* np.cos(x) +2*y -z + 3*v
    eq3 = 2*x**2 -y/2 + np.sin(z+1) - np.cos(v)
    eq4 =   3*x**2 + y/3  - np.cos(z) +   v**2
     

    return [eq1, eq2, eq3, eq4]
initial_guess = [1 , 1 ,1 ,1]
solution = fsolve(equations2, initial_guess)
print("Ergebnis mit 4 Unbekannten:",      solution)



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

11.12.2024
Bevor ich einige Beispielprogramme bringe , muss ich noch vorausschicken:
Was habe ich unter dem Begriff Gradient verstanden oder nicht verstanden ?

1 Analytisch betrachtet ist der Begriff "Vektor.Gradient " nichts als der Differentialquotient und dessen
Anwendung :

die Steignung, also slope , für einen ganz bestimmten Bereich , auf- oder
absteigend, plus oder minus , von 0 bis unendlich. Beispiel die "automatische Differenzierung"

2: die Geschwindigkeit des regelmäßigen oder abgestuften
Auf- oder Abstiegs : Neigung, ein Teil, der nach oben oder unten geneigt ist

3 Änderung des Wertes einer Größe (
wie Temperatur, Druck oder Konzentration) bei Änderung einer bestimmten Variablen
und insbesondere pro Entfernungseinheit in einer bestimmten Richtung

4 die Vektorsumme der partiellen Ableitungen nach den drei Koordinatenvariablen x, y und z , einer skalaren Größe,
deren Wert von Punkt zu Punkt variiert.

5 Analytisch betrachtet ist der Begriff "Vektor.Gradient " nichts als der Differentialquotient und dessen
Anwendung.
die Steignung, also slope , für einen ganz bestimmten Bereich , auf- oder
absteigend, plus oder minus , von 0 bis unendlich. Beispiel die "automatische Differenzierung"

5 In der Informatik insgesamt ist in allen Bereichen der Begriff Gradient zu finden.
Hier speziell geht es um die Rolle des Gradienten in der Optimierung von Funktionen, Methoden
und Programmen usw. Beispiel die "automatische Differenzierung" oder der
sog Gradientenabstieg..

Entsprechend schwer sind die gezeigten Beispiele zu verstehehen.
Gute Zeit OSWALD
OSWALD
User
Beiträge: 543
Registriert: Freitag 18. März 2022, 17:32

11.12.2024
Zur Einführung " Gradient absteigend"
noch leichter verständlich
OSWALD

Code: Alles auswählen


#GRADIENT ABSTEIGEND
import numpy as np

# Define the cost function f(x)
def cost_function(x):
    return x**3 - 4*x + 3

# Define the derivative of the cost function f'(x)
def gradient(x):
    return 1/3*x**2  - 4

# Gradient Descent parameters
learning_rate = 0.01  # Step size
iterations = 20     # Number of iterations

# Initial guess for x (starting point)
x = 0.0

# Gradient Descent optimization
for i in range(iterations):
    # Compute the gradient at the current point
    grad = gradient(x)
    
    # Update x using the Gradient Descent formula
    x = x - learning_rate * grad

# The value of x after optimization represents the minimum of the cost function
minimum_x = x
minimum_cost = cost_function(minimum_x)

# Print the result
print(f"Minimum value of x: {minimum_x}")
print(f"Minimum cost: {minimum_cost}")
 
import numpy as np
import matplotlib.pyplot as plt

# Define the cost function f(x)
def cost_function(x):
    return x**2 - 4*x + 3 

# Define the derivative of the cost function f'(x)
def gradient(x):
    return 2*x - 4


# Initialize the model parameter with a random value
x = np.random.randn()

# Set the learning rate
learning_rate = 0.1

# Set the maximum number of iterations
max_iterations = 100

# Initialize the list to store the cost values
cost_values = []

# Iterate until convergence or max iterations
for i in range(max_iterations):
    # Calculate the cost and gradient at the current parameter
    cost = cost_function(x)
    grad = gradient(x)

    # Update the parameter
    x = x - learning_rate * grad

    # Store the cost value
    cost_values.append(cost)

    # Print the progress
    if i % 10 == 0:
        print("Iteration {}: x = {}, cost = {}".format(i, x, cost))

# Plot the cost values
plt.plot(cost_values)
plt.xlabel("Iterations")
plt.ylabel("Cost")
plt.show()        

 
#Let's observe how x changes after each iteration of Gradient Descent!

import numpy as np
import matplotlib.pyplot as plt

# Define the cost function f(x)
def cost_function(x):
    return x**2 - 4*x + 3 

# Define the derivative of the cost function f'(x)
def gradient(x):
    return 2*x - 4

# Define the gradient descent algorithm
def gradient_descent(cost_function, gradient, x_init, alpha, num_iterations):
    x = x_init
    x_list = [x]
    for i in range(num_iterations):
        x = x - alpha * gradient(x)
        x_list.append(x)
        # Print the progress
        print("Iteration {}: x = {}, cost = {}".format(i, x, cost))
          
    return x_list

# Set the hyperparameters
alpha = 0.1
num_iterations = 5

# Run gradient descent on f(x)
x_init = 15
x_list = gradient_descent(cost_function, gradient, x_init, alpha, num_iterations)

# Create an array of x values
x = np.linspace(-2, 15, 100)

# Evaluate f(x) for each value of x
y = cost_function(x)

# Plot f(x) versus x
plt.plot(x, y)

# Plot the gradient descent iterations
for i in range(len(x_list) - 1):
    x1 = x_list[i]
    y1 = cost_function(x1)
    x2 = x_list[i + 1]
    y2 = cost_function(x2)
    plt.plot([x1, x2], [y1, y2], 'ro-')
    plt.text(x1, y1 + 0.5, round(y1, 2))

# Label the final cost value
x_final = x_list[-1]
y_final = cost_function(x_final)
plt.text(x_final, y_final + 0.5, round(y_final, 2))

# Add labels and a title to the plot
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Gradient descent iterations on f(x)')

# Display the plot
plt.show()  


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

11.12.2024
Auch Gradient-Abstieg, aber andere
Datenfindung

Code: Alles auswählen


import numpy as np
import matplotlib.pyplot as plt
 
def mean_squared_error(y_true, y_predicted):
     
    # Calculating the loss or cost
    cost = np.sum((y_true-y_predicted)**2) / len(y_true)
    return cost
 
# Gradient Descent Function
# Here iterations, learning_rate, stopping_threshold
# are hyperparameters that can be tuned
def gradient_descent(x, y, iterations = 100, learning_rate = 0.0001, 
                     stopping_threshold = 1e-3):
     
    # Initializing weight, bias, learning rate and iterations
    current_weight = 0.1
    current_bias = 0.01
    iterations = iterations
    learning_rate = learning_rate
    n = float(len(x))
     
    costs = []
    weights = []
    previous_cost = None
     
    # Estimation of optimal parameters 
    for i in range(iterations):
         
        # Making predictions
        y_predicted = (current_weight * x) + current_bias
         
        # Calculating the current cost
        current_cost = mean_squared_error(y, y_predicted)
 
        # If the change in cost is less than or equal to 
        # stopping_threshold we stop the gradient descent
        if previous_cost and abs(previous_cost-current_cost)<=stopping_threshold:
            break
         
        previous_cost = current_cost
 
        costs.append(current_cost)
        weights.append(current_weight)
         
        # Calculating the gradients
        weight_derivative = -(2/n) * sum(x * (y-y_predicted))
        bias_derivative = -(2/n) * sum(y-y_predicted)
         
        # Updating weights and bias
        current_weight = current_weight - (learning_rate * weight_derivative)
        current_bias = current_bias - (learning_rate * bias_derivative)
                 
        # Printing the parameters for each 1000th iteration
        print(f"Iteration {i+1}: Cost {current_cost}, Weight \
        {current_weight}, Bias {current_bias}")
     
     
    # Visualizing the weights and cost at for all iterations
    plt.figure(figsize = (8,6))
    plt.plot(weights, costs)
    plt.scatter(weights, costs, marker='o', color='red')
    plt.title("Cost vs Weights")
    plt.ylabel("Cost")
    plt.xlabel("Weight")
    plt.show()
     
    return current_weight, current_bias
 
 
def main():
     
    # Data
    X = np.array([32.50234527, 53.42680403, 61.53035803, 47.47563963, 59.81320787,
           55.14218841, 52.21179669, 39.29956669, 48.10504169, 52.55001444,
           45.41973014, 54.35163488, 44.1640495 , 58.16847072, 56.72720806,
           48.95588857, 44.68719623, 60.29732685, 45.61864377, 38.81681754])
    Y = np.array([31.70700585, 68.77759598, 62.5623823 , 71.54663223, 87.23092513,
           78.21151827, 79.64197305, 59.17148932, 75.3312423 , 71.30087989,
           55.16567715, 82.47884676, 62.00892325, 75.39287043, 81.43619216,
           60.72360244, 82.89250373, 97.37989686, 48.84715332, 56.87721319])
 
    estimated_weight, estimated_bias = gradient_descent(X, Y, iterations=2000)
    print(f"Estimated Weight: {estimated_weight}\nEstimated Bias: {estimated_bias}")
 
    # Making predictions using estimated parameters
    Y_pred = estimated_weight*X + estimated_bias
 
    # Plotting the regression line
    plt.figure(figsize = (8,6))
    plt.scatter(X, Y, marker='o', color='red')
    plt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color='blue',markerfacecolor='red',
             markersize=10,linestyle='dashed')
    plt.xlabel("X")
    plt.ylabel("Y")
    plt.grid()
    plt.title(" Hier werden Funktionen durch Arrays erstzt")
    plt.show()
 
     
if __name__=="__main__":
    main()
 

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

11.12.2024
jetzt ein Programm mit Gradienten und einigen "Bekannten",
vielen "Unbekannten" ,kompliziert,
OSWALD

Code: Alles auswählen


import tensorflow as tf
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
mpl.rcParams['figure.figsize'] = (8, 6)

x = tf.Variable(6.0)
y = tf.Variable(5.0)

with tf.GradientTape() as t:
  x_sq = x **3  -2*x** -15
  with t.stop_recording():
    y_sq = y**3 - 6*x**2 +10
    z = x_sq + y_sq

grad = t.gradient(z, {'x': x, 'y': y})
print(grad)
print('dz/dx:', grad['x'])   
print('dz/dy:', grad['y'])

 
x = tf.Variable(6.0)
y = tf.Variable(5.0)

with tf.GradientTape() as t:
  y_sq = y**3 + np.sin(x**2) 
  z = x**3 + tf.stop_gradient(y_sq)

grad = t.gradient(z, {'x': x, 'y': y})
 
print('dz/dx:', grad['x']) 
print('dz/dy:', grad['y'])


# Establish an identity operation, but clip during the gradient pass.
@tf.custom_gradient
def clip_gradients(y):
  def backward(dy):
    return tf.clip_by_norm(dy, 0.5)                       
  return y, backward

v = tf.Variable(3.0)
with tf.GradientTape() as t:
  output = clip_gradients(v * v)
print(t.gradient(output, v))  # calls "backward", which clips 4 to 2

class MyModule(tf.Module):

  @tf.function(input_signature=[tf.TensorSpec(None)])
  def call_custom_grad(self, x):
    return clip_gradients(x)

model = MyModule()

tf.saved_model.save(
    model,
    'saved_model',
    options=tf.saved_model.SaveOptions(experimental_custom_gradients=True))

# The loaded gradients will be the same as the above example.
v = tf.Variable(5.0)
loaded = tf.saved_model.load('saved_model')
with tf.GradientTape() as t:
  output = loaded.call_custom_grad(v * v)
print(t.gradient(output, v))

x0 = tf.constant(0.0)
x1 = tf.constant(0.0)

with tf.GradientTape() as tape0, tf.GradientTape() as tape1:
  tape0.watch(x0)
  tape1.watch(x1)

  y0 = tf.math.sin(x0)
  y1 = tf.nn.sigmoid(x1)
  y = y0 + y1
  ys = tf.reduce_sum(y)

tape0.gradient(ys, x0).numpy()   # cos(x) => 1.0
1.0
tape1.gradient(ys, x1).numpy()   # sigmoid(x1)*(1-sigmoid(x1)) => 0.25
25
 

#############################
x = tf.Variable(1.0)  # Create a Tensorflow variable initialized to 1.0

with tf.GradientTape() as t2:
  with tf.GradientTape() as t1:
    y = x **3 +np.cos(4*x)

  # Compute the gradient inside the outer `t2` context manager
  # which means the gradient computation is differentiable as well.
  dy_dx = t1.gradient(y, x)
d2y_dx2 = t2.gradient(dy_dx, x)

print('dy_dx:', dy_dx.numpy())                              
print('d2y_dx2:', d2y_dx2.numpy())                       

dy_dx: 3.0
d2y_dx2: 6.0

#######################################

x = tf.random.normal([6, 5])

layer = tf.keras.layers.Dense(10, activation=tf.nn.relu)

with tf.GradientTape() as t2:
  # The inner tape only takes the gradient with respect to the input,
  # not the variables.
  with tf.GradientTape(watch_accessed_variables=False) as t1:
    t1.watch(x)
    y = layer(x)
    out = tf.reduce_sum(layer(x)**2)
  # 1. Calculate the input gradient.
  g1 = t1.gradient(out, x)
  # 2. Calculate the magnitude of the input gradient.
  g1_mag = tf.norm(g1)

# 3. Calculate the gradient of the magnitude with respect to the model.
dg1_mag = t2.gradient(g1_mag, layer.trainable_variables)

[var.shape for var in dg1_mag]

 
#Als erstes Beispiel ist hier die Jacobi-Matrix eines Vektorziels in Bezug auf eine Skalarquelle.
x = tf.linspace(-10.0, 10.0, 200+1)
delta = tf.Variable(3.0)

with tf.GradientTape() as tape:
  y = tf.nn.sigmoid(x+delta)

dy_dx = tape.jacobian(y, delta)

print(y.shape)
print(dy_dx.shape)

#(201,)

plt.plot(x.numpy(), y, label='y')
plt.plot(x.numpy(), dy_dx, label='dy/dx')
plt.legend()
_ = plt.xlabel('x')

plt.title("Funktion und ihre automatische Differenzierung")
plt.grid()
plt.show()
###########################################
x = tf.random.normal([7, 5])
layer = tf.keras.layers.Dense(10, activation=tf.nn.relu)

with tf.GradientTape(persistent=True) as tape:
  y = layer(x)

print(y.shape)
##Und die Form des Schichtkernels ist (5, 10):
layer.kernel.shape

#TensorShape([5, 10])

############################
layer.kernel.shape

##Die Form der Jacobi-Matrix der Ausgabe in Bezug auf den Kernel
#besteht aus diesen beiden miteinander verketteten Formen:


j = tape.jacobian(y, layer.kernel)
j.shape

#TensorShape([7, 10, 5, 10])
################################
g = tape.gradient(y, layer.kernel)
print('g.shape:', g.shape)

j_sum = tf.reduce_sum(j, axis=[0, 1])
delta = tf.reduce_max(abs(g - j_sum)).numpy()
assert delta < 1e-3
print('delta:', delta)

g.shape: (5, 10)
delta: 2.3841858e-07

############################
x = tf.random.normal([6, 5])
layer1 = tf.keras.layers.Dense(8, activation=tf.nn.relu)
layer2 = tf.keras.layers.Dense(6, activation=tf.nn.relu)

with tf.GradientTape() as t2:
  with tf.GradientTape() as t1:
    x = layer1(x)
    x = layer2(x)
    loss = tf.reduce_mean(x**2)

  g = t1.gradient(loss, layer1.kernel)

h = t2.jacobian(g, layer1.kernel)

print(f'layer.kernel.shape: {layer1.kernel.shape}')
print(f'h.shape: {h.shape}')

layer.kernel.shape: (5, 8)
h.shape: (5, 8, 5, 8)

#############################
n_params = tf.reduce_prod(layer1.kernel.shape)

g_vec = tf.reshape(g, [n_params, 1])
h_mat = tf.reshape(h, [n_params, n_params])

#Die Hesse-Matrix sollte symmetrisch sein:
def imshow_zero_center(image, **kwargs):
  lim = tf.reduce_max(abs(image))
  plt.imshow(image, vmin=-lim, vmax=lim, cmap='seismic', **kwargs)
  plt.colorbar()

imshow_zero_center(h_mat)
plt.show()

# Reshape the update and apply it to the variable.
#
##################################
x = tf.random.normal([8, 6])

layer1 = tf.keras.layers.Dense(6, activation=tf.nn.elu)
layer2 = tf.keras.layers.Dense(5, activation=tf.nn.elu)

with tf.GradientTape(persistent=True, watch_accessed_variables=False) as tape:
  tape.watch(x)
  y = layer1(x)
  y = layer2(y)

y.shape

#TensorShape([7, 6])
#Die vollständige Jacobi-Matrix von y in Bezug auf  x  hat die Form (batch, ins, batch, outs),
#

j = tape.jacobian(y, x)
j.shape

#TensorShape([7, 6, 7, 5])
#

imshow_zero_center(j[:, 0, :, 0])
_ = plt.title('A (batch, batch) slice')
 

def plot_as_patches(j):
  # Reorder axes so the diagonals will each form a contiguous patch.
  j = tf.transpose(j, [1, 0, 3, 2])
  # Pad in between each patch.
  lim = tf.reduce_max(abs(j))
  j = tf.pad(j, [[0, 0], [1, 1], [0, 0], [1, 1]],
             constant_values=-lim)
  # Reshape to form a single image.
  s = j.shape
  j = tf.reshape(j, [s[0]*s[1], s[2]*s[3]])                      
  imshow_zero_center(j, extent=[-0.5, s[2]-0.5, s[0]-0.5, -0.5])

plot_as_patches(j)
_ = plt.title('All (batch, batch) slices are diagonal')
plt.title("Funktion und  ihre autom,atische Ableitung")
plt.show()
















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

16.12.2024

Die Entwicklung von Python und ihren Bibliotheken geht immer steiler
nach oben. Das bedeutet für mein Hobby , dass meine Lernkurve immer
flacher verläuft. Ich entdecke immer neue unbekannte Begriffe und stehe
damit vor der Frage , was ist wichtig zu lernen , was nicht.

Jetzt habe ich mir eine Methode ausgedacht, wie ich meine Lernkurve
steigern könnte:
Programm-Titel mit einem mir neuen Begriff.
# Isotone Regression#
Ich versuche den Inhalt zu analysieren:
Fazit, was muss ich nachholen, was kann ich 'Neues angehen'.


Aus der Medizin kennen wir den Begriff "Istonische Lösung":
Gleichbleibende Kochsalzkonzentration zur Aufrechterhaltung
der physiologischen Wirkung

Die" isotonische Regression " ist ein Regressionsverfahren,
mit dem eine isotone (ordnungserhaltende) Abbildung
zwischen einer abhängigen und einer unabhängigen Variable gefunden wird.

Die von der Abbildung beschriebene Kurve hat anders als beispielsweise
die lineare Regression keine feste Form,
sondern nur die Beschränkung, monoton steigend (oder fallend) zu sein,
während die Entfernung zu den Datenpunkten so gering wie möglich ist.
Hier ein Beispiel:
OSWALD

Code: Alles auswählen


mport matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection

from sklearn.isotonic import IsotonicRegression
from sklearn.linear_model import LinearRegression
from sklearn.utils import check_random_state

n = 100
x = np.arange(n)
rs = check_random_state(0)
y = rs.randint(-50, 50, size=(n,)) + 50.0 * np.log1p(np.arange(n))
#Passen Sie IsotonicRegression- und LinearRegression-Modelle an:

ir = IsotonicRegression(out_of_bounds="clip")
y_ = ir.fit_transform(x, y)

lr = LinearRegression()
lr.fit(x[:, np.newaxis], y)     # x needs to be 2d for LinearRegression

 

#Plot-Ergebnisse:

segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
lc = LineCollection(segments, zorder=0)
lc.set_array(np.ones(len(y)))
lc.set_linewidths(np.full(n, 0.5))

fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 6))

ax0.plot(x, y, "C0.", markersize=12)
ax0.plot(x, y_, "C1.-", markersize=12)
ax0.plot(x, lr.predict(x[:, np.newaxis]), "C2-")
ax0.add_collection(lc)
ax0.legend(("Training data", "Isotonic fit", "Linear fit"), loc="lower right")
ax0.set_title("Isotonic regression fit on noisy data (n=%d)" % n)

x_test = np.linspace(-10, 110, 1000)
ax1.plot(x_test, ir.predict(x_test), "C1-")
ax1.plot(ir.X_thresholds_, ir.y_thresholds_, "C1.", markersize=12)
ax1.set_title("Prediction function (%d thresholds)" % len(ir.X_thresholds_))

plt.show()

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

21.12.2024
Heute stelle ich noch zwei weitere Begriffe vor, die
in der Diskussion der KI-Entwicklung kaum Beachtung
finden und trotzdem essential sind.
- Interpolation und Extrrapolation -
Mit beiden habe ich mich in letzter Zeit beschäftigt.
Anschließend stelle ich dazu einige Programme zur illustration vor.
Lineare und nicht lineare Extraplation
OSWALD

Code: Alles auswählen


import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

def exponential_fit(x, a, b, c):
    return a*np.exp(-b*x) + c 

if __name__ == "__main__":
    x = np.array([0, 1.3, 2, 3.4, 4.3,5.5])
    y = np.array([30, 50, 80, 160, 300, 580])
      
    fitting_parameters, covariance = curve_fit(exponential_fit, x, y)
    a, b, c = fitting_parameters
    
    next_x = 6
    next_y = exponential_fit(next_x, a, b, c)
     
    plt.plot(y)
    plt.plot(np.append(y, next_y), 'ro')
    plt.title("Nicht lineare Extrapolation")
    plt.show()



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

21.12.2024
jetzt die meistverwendete kineare Extrapolation
(früher auch beim Gebrauch von Logarithmentafelnein
OSWALD

Code: Alles auswählen


.    Lineare Extrapolation :  Verlängerung über bestehenden Funktionbereich  hinaus          
#      einen Wert    zusätzlich   zu bestehenden Werten zu finden,
#     Nicht lineare Extrapolation : Verlängerung über einen   Kurvenbereich hinaus 
#     mit Anpassung an den weiteren  Kurvenverlauf,    also eine Art Optimierung

import numpy as np

# Example data
x = np.array([0, 1, 2, 3])
y = np.array([0, 2, 4, 6])

# Linear extrapolation function
slope = (y[-1] - y[-4]) / (x[-1] - x[-4])
intercept = y[-2] - slope * x[-2]
x_new = np.array([7, 12])
y_new = slope * x_new + intercept

# Plot Original data und extrapolierte  Werte
import matplotlib.pyplot as plt

plt.plot(x, y, 'o', label='data= gegebener Funktionsbereich')
          
plt.plot(x_new, y_new, '-', label='Lineare  Extrapolation')
plt.legend()
plt.title("Vermuteter Funktions-Verlauf über gegebene Daten hinaus")
plt.show()


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

22.12.2024
un zwei Beispiele für Interpolationsverfahren mit Python zur Demo.
Auch in Tensorflow, Torch, Teras usw werden Inteerpolationsverfahren
häufig angewandt.
OSWALD

Code: Alles auswählen

# FCiverse Interpolationsverfahren
#Höhergradige Polynome
#Schrittweise Interpolation
#Trigonometrische Interpolation         hier die  trigom.Variante
#Logarithmische Interpolation.


import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import barycentric_interpolate
x_observed = np.linspace(-10.0, 10.0, 11)
#y_observed = np.cos(x_observed)
#y_observed = np.sin(x_observed**4)
y_observed = np.sin(x_observed**3)
x = np.linspace(min(x_observed), max(x_observed), num=100)
y = barycentric_interpolate(x_observed, y_observed, x)
plt.plot(x_observed, y_observed, "o", label="beobachtete Daten auf Sinusfunktion")
plt.plot(x, y, label="trigonometrisch-baryzentrische   interpolation")
plt.legend()

plt.grid()
plt.title("Baryzentrische  nichtlineare Interpolation ")
plt.show()

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

22.12.2024
Und hier ein Beispiel aus der Praxis.
OSWALD

Code: Alles auswählen

"""Vergleich unterschiedlicher Interpolationsverfahren.

Interpolation der Messdaten der Luftdichte als Funktion der
Höhe. In diesem Programm werden die unterschiedlichen
Interpolationsarten verglichen:
   1.) Nächste-Nachbarn-Interpolation (nearest)
   2.) Lineare Interpolation (linear)
   3.) Kubische Interpolation (cubic)
"""

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate

# Messdaten Höhe [km] und Luftdichte [kg/m³].
messwerte_h = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                        11.02, 15, 20.06, 25, 32.16, 40])
messwerte_rho = np.array([1.225, 1.112, 1.007, 0.909, 0.819, 0.736,
                          0.660, 0.590, 0.526, 0.467, 0.414, 0.364,
                          0.195, 0.0880, 0.0401, 0.0132, 0.004])

# Erzeuge die Interpolationsfunktionen.
interp_cubic = scipy.interpolate.interp1d(messwerte_h,
                                          messwerte_rho,
                                          kind='cubic')
interp_linear = scipy.interpolate.interp1d(messwerte_h,
                                           messwerte_rho,
                                           kind='linear')
interp_nearest = scipy.interpolate.interp1d(messwerte_h,
                                            messwerte_rho,
                                            kind='nearest')

# Erzeuge ein fein aufgelöstes Array von Höhen.
h = np.linspace(0, np.max(messwerte_h), 1000)

# Erzeuge eine Figure und eine Axes.
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xlabel('$h$ [km]')
ax.set_ylabel('$\\rho$ [kg/m³]')
ax.set_xlim(10, 40)
ax.set_ylim(0, 0.4)
ax.grid()

# Plotte die Messdaten und die drei Interpolationsfunktionen.
ax.plot(messwerte_h, messwerte_rho, 'or', label='Messung', zorder=5)
ax.plot(h, interp_nearest(h), '-k', label='nearest')
ax.plot(h, interp_linear(h), '-b', label='linear')
ax.plot(h, interp_cubic(h), '-r', label='cubic')
ax.legend()

# Zeige die Grafik an.
plt.show()

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

23.12.2024
Logarithmen und Python
Anbei habe ich einige Riutinen zusammen gestellt,
die bei der Arbeit vielleicht nützlich werden könnten.
Gute Zeit OSWALD


Code: Alles auswählen


#Nach dem Satz von Lindemann-Weierstraß ist der natürliche Logarithmus
#jeder algebraischen Zahl außer 0 und 1
#eine transzendente Zahl.
 
import math
from math import  *
import numpy as np 

print("Natürlicher Logarithmus: ", math.log(2))
print()

#print("Natürlicher Logarithmus: ", math.log(-2))   #Achtung Fehler  keine neg. L
#print()


print ("Log Basis2: ",(math.log2(20))) 
print( ) 
 
 
print ("Log Basis3 : ",math.log(20,3)) 
print() 
 
print ("Log Basis4 : ",math.log(20,4)) 
print() 
 
print ("Log Basis10 : ",math.log(20,10)) 
print() 
 
#print ("Log value(1+1) for x = 1 is: ")             #ergibt  konkret  log4(2)  siehe  oben
print("Log Basis(beliebig)value(1+15) for x = 15 is:" , 2.772588722239781

print()



#################################
import numpy as np 
  
 
# Graphical representation   
# of log() function 
import numpy as np 
import matplotlib.pyplot as plt 
##################  
#in_array = [1, 1.2, 1.4, 1.6, 1.8, 2] 
#out_array = np.log(in_array) 
##################  
#Jetzt störe ich die Daten
in_array = [2, 4, 8, 16, 18, 2.0] 
out_array = np.log(in_array) 
###################

print ("out_array : ", out_array) 
  
plt.plot(in_array, in_array,  
         color = 'blue', marker = "*") 
  
# red for numpy.log() 
plt.plot(out_array, in_array,  
         color = 'red', marker = "o") 
           
plt.title("numpy.log()") 
plt.xlabel("out_array") 
plt.ylabel("in_array") 

plt.show()    



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

24.12.2024
Mit der Fehlerfunktion von scipy habe ich versucht
sowohl x als auch 1/x ohne Fehlermeldung
graphisvh darztustellen.
Hier ist der Versuch.
Aber ich verstehe das Ergebnis noch nicht ganz.
Mit sympy keine Probleme. Mit scipy sonst schon.
Gute Zeit OSWALD

Code: Alles auswählen

#gaussnormal F(x), f(x)
import numpy as np
from scipy import special
import matplotlib.pyplot as plt
x = np.linspace(-3, 3,100)
###########
plt.plot(x, special.erf(x)) , plt.plot(x, special.erf(1/x))
##############
plt.xlabel('$x oder 1/x  $')
plt.ylabel('$erf(x,1/x)$')
plt.title("Lineare Regression    und  1/x   ") 
plt.grid(True) 
plt.show()












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

24.12.2014
Hier mein Problem
Oswald

Code: Alles auswählen


from scipy.integrate import quad
import numpy as np
 
# Integration   von   1/x =  log(x)      #nat.log
def integrand(x):
       return (x**-1)                   #x**-1 = 1/x
print(quad(integrand, 0, 0.01))
print(np.log(2))





Antworten