kleine Mathe-Spielereien
20.7.2024
Hier noch eine nähere Bschreibung
der sog .'mystischen Attribute'.
x (ndarray) The solution of the optimization.
success (bool) Whether or not the optimizer exited successfully.
status (int) Termination status of the optimizer. Its value depends on the underlying solver. Refer to message for details.
message (str) Description of the cause of the termination.
fun, jac, hess, hess_inv (ndarray) Values of objective function, Jacobian, Hessian or its inverse (if available). The Hessians may be approximations, see the documentation of the function in question.
nfev, njev, nhev (int) Number of evaluations of the objective functions and of its Jacobian and Hessian.
nit (int) Number of iterations performed by the optim
Gute Zeit OSWALD
Hier noch eine nähere Bschreibung
der sog .'mystischen Attribute'.
x (ndarray) The solution of the optimization.
success (bool) Whether or not the optimizer exited successfully.
status (int) Termination status of the optimizer. Its value depends on the underlying solver. Refer to message for details.
message (str) Description of the cause of the termination.
fun, jac, hess, hess_inv (ndarray) Values of objective function, Jacobian, Hessian or its inverse (if available). The Hessians may be approximations, see the documentation of the function in question.
nfev, njev, nhev (int) Number of evaluations of the objective functions and of its Jacobian and Hessian.
nit (int) Number of iterations performed by the optim
Gute Zeit OSWALD
28.7.2024
Seit einigen Wochen beschäftige ich mich wieder mit
dem Thema INTEGRATION.
Scipy Version 1.14.0 meldet , dass das Modul scipy.misc
seit Version .1.10.0 veraltet is ud vollständig entfernt wurde.
Integration und Differentialgleichungen läuft jetzt
unter scipy.integrate
Insgesamt gab es viele Verbesserungen und Erweiterungen.
Wenn also in Zukunft die folgende Warnung
erscheint,
# DeprecationWarning: `scipy.integrate.romberg` is deprecated as of SciPy 1.12.0
# and will be removed in SciPy 1.15.0. Please use`scipy.integrate.quad` instead. PyPy arbeitet jedoch aktiv an der Verbesserung).
dann muss ich mich neu informieren.
Generell kann man feststellen, dass Python mit seinen Bibliotheken
eine enorme Entwicklung genommen hat.
Trotz mancher Unbequemlichkeiten habe ich die neueste Version von Python.Gute Zeit OSWALD
Seit einigen Wochen beschäftige ich mich wieder mit
dem Thema INTEGRATION.
Scipy Version 1.14.0 meldet , dass das Modul scipy.misc
seit Version .1.10.0 veraltet is ud vollständig entfernt wurde.
Integration und Differentialgleichungen läuft jetzt
unter scipy.integrate
Insgesamt gab es viele Verbesserungen und Erweiterungen.
Wenn also in Zukunft die folgende Warnung
erscheint,
# DeprecationWarning: `scipy.integrate.romberg` is deprecated as of SciPy 1.12.0
# and will be removed in SciPy 1.15.0. Please use`scipy.integrate.quad` instead. PyPy arbeitet jedoch aktiv an der Verbesserung).
dann muss ich mich neu informieren.
Generell kann man feststellen, dass Python mit seinen Bibliotheken
eine enorme Entwicklung genommen hat.
Trotz mancher Unbequemlichkeiten habe ich die neueste Version von Python.Gute Zeit OSWALD
3.8.2024
Python. mein Hobby, wird für mich immer interessanter.
Als solide Grundlage für KI wird Python weitrr an Bedeutung
trotz aller Unkenrufe , weiter zunehmen-
Es gibt nämlich keine Wunder.
Der Börsenhype um KI erinnert mich stark an die
Tulpenzwiebeln von Amsterdam .
Guten Zeit OSWALD
Python. mein Hobby, wird für mich immer interessanter.
Als solide Grundlage für KI wird Python weitrr an Bedeutung
trotz aller Unkenrufe , weiter zunehmen-
Es gibt nämlich keine Wunder.
Der Börsenhype um KI erinnert mich stark an die
Tulpenzwiebeln von Amsterdam .
Guten Zeit OSWALD
4.8.2024
Nach etlichen updates, upgrades und neuen downloads
bin ich zurückgekehrt nach tensoflow.
ich werde jetzt mit diversen kleineren Datenmengen
und bestimmten mir bekannten Dateninhalten versuchen
mehr Verständnis für tensorflow zu erlangen.
Gute Zeit Oswald
Nach etlichen updates, upgrades und neuen downloads
bin ich zurückgekehrt nach tensoflow.
ich werde jetzt mit diversen kleineren Datenmengen
und bestimmten mir bekannten Dateninhalten versuchen
mehr Verständnis für tensorflow zu erlangen.
Gute Zeit Oswald
Code: Alles auswählen
import tensorflow as tf
import tensorflow.keras
import numpy as np
X_train = (np.random.sample((1,4, 3, 5, 3)))
y_train = (np.random.sample((106 ,3)))
print(X_train.shape)
print(y_train)
6.8.2024
Tensorflow und Hardware.
Ich habe ein ' Tensoflw sequential ' Programm
heruntergeladen.
Es läuft ganz gut , bis die Ausgabe in 'Datensalat übergeht.
Damit kann ich meine Hardwarekapazität in etwa einschätzen
Der Inhalt ist hier nur von sekundären Bedeutung.
Ich weiß nicht, was noch an Ergebnissen erscheinen könnte.
Ichwerde ihn trotzdem untersuchen. Vielleicht bleibt noch etwas hängen..
Gute Zeit OSWALD
Tensorflow und Hardware.
Ich habe ein ' Tensoflw sequential ' Programm
heruntergeladen.
Es läuft ganz gut , bis die Ausgabe in 'Datensalat übergeht.
Damit kann ich meine Hardwarekapazität in etwa einschätzen
Der Inhalt ist hier nur von sekundären Bedeutung.
Ich weiß nicht, was noch an Ergebnissen erscheinen könnte.
Ichwerde ihn trotzdem untersuchen. Vielleicht bleibt noch etwas hängen..
Gute Zeit OSWALD
Code: Alles auswählen
mport tensorflow as tf
import keras
from keras import layers
import tensorflow as tf
import keras
from keras import layers
# Define Sequential model with 3 layers
model = keras.Sequential(
[
layers.Dense(2, activation="relu", name="layer1"),
layers.Dense(3, activation="relu", name="layer2"),
layers.Dense(4, name="layer3"),
]
)
# Call model on a test input
x = tf.ones((3, 3))
y = model(x)
# Create 3 layers
layer1 = layers.Dense(2, activation="relu", name="layer1")
layer2 = layers.Dense(3, activation="relu", name="layer2")
layer3 = layers.Dense(4, name="layer3")
# Call layers on a test input
x = tf.ones((3, 3))
y = layer3(layer2(layer1(x)))
model = keras.Sequential(
[
layers.Dense(2, activation="relu"),
layers.Dense(3, activation="relu"),
layers.Dense(4),
]
)
model.layers
model = keras.Sequential()
model.add(layers.Dense(2, activation="relu"))
model.add(layers.Dense(3, activation="relu"))
model.add(layers.Dense(4))
model.pop()
print(len(model.layers)) # 2
model = keras.Sequential(name="my_sequential")
model.add(layers.Dense(2, activation="relu", name="layer1"))
model.add(layers.Dense(3, activation="relu", name="layer2"))
model.add(layers.Dense(4, name="layer3"))
layer = layers.Dense(3)
layer.weights # Empty
[]
# Call layer on a test input
x = tf.ones((1, 4))
y = layer(x)
layer.weights # Now it has weights, of shape (4, 3) and (3,)
#[<tf.Variable 'dense_6/kernel:0' shape=(4, 3) dtype=float32, numpy=
# array([[ 0.1752373 , 0.47623062, 0.24374962],
# [-0.0298934 , 0.50255656, 0.78478384],
# [-0.58323103, -0.56861055, -0.7190975 ],
# [-0.3191281 , -0.23635858, -0.8841506 ]], dtype=float32)>,
# <tf.Variable 'dense_6/bias:0' shape=(3,) dtype=float32, numpy=array([0., 0., 0.], dtype=float32)>]
model = keras.Sequential(
[
layers.Dense(2, activation="relu"),
layers.Dense(3, activation="relu"),
layers.Dense(4),
]
) # No weights at this stage!
# At this point, you can't do this:
# model.weights
# You also can't do this:
# model.summary()
# Call the model on a test input
x = tf.ones((1, 4))
y = model(x)
print("Number of weights after calling the model:", len(model.weights)) # 6
model.summary()
Model: "sequential_3"
#_________________________________________________________________
# Layer (type) Output Shape Param #
#=================================================================
# dense_7 (Dense) (1, 2) 10
# dense_8 (Dense) (1, 3) 9
# dense_9 (Dense) (1, 4) 16
#Total params: 35 (140.00 Byte)
#Trainable params: 35 (140.00 Byte)
#Non-trainable params: 0 (0.00 Byte)
model = keras.Sequential()
model.add(keras.Input(shape=(4,)))
model.add(layers.Dense(2, activation="relu"))
model.summary()
Model: "sequential_4"
# Layer (type) Output Shape Param #
#=================================================================
# dense_10 (Dense) (None, 2) 10
#Total params: 10 (40.00 Byte)
#Trainable params: 10 (40.00 Byte)
#Non-trainable params: 0 (0.00 Byte)
#
#model.layers
#A simple alternative is to just pass an input_shape argument to your first layer:
model = keras.Sequential()
model.add(layers.Dense(2, activation="relu", input_shape=(4,)))
model.summary()
Model: "sequential_5"
#Total params: 10 (40.00 Byte)
#Trainable params: 10 (40.00 Byte)
#Non-trainable params: 0 (0.00 Byte)
#_________________________________________________________________
model = keras.Sequential()
model.add(keras.Input(shape=(250, 250, 3))) # 250x250 RGB images
model.add(layers.Conv2D(32, 5, strides=2, activation="relu"))
model.add(layers.Conv2D(32, 3, activation="relu"))
model.add(layers.MaxPooling2D(3))
# Can you guess what the current output shape is at this point? Probably not.
# Let's just print it:
model.summary()
# The answer was: (40, 40, 32), so we can keep downsampling...
model.add(layers.Conv2D(32, 3, activation="relu"))
model.add(layers.Conv2D(32, 3, activation="relu"))
model.add(layers.MaxPooling2D(3))
model.add(layers.Conv2D(32, 3, activation="relu"))
model.add(layers.Conv2D(32, 3, activation="relu"))
model.add(layers.MaxPooling2D(2))
# And now?
model.summary()
# Now that we have 4x4 feature maps, time to apply global max pooling.
model.add(layers.GlobalMaxPooling2D())
# Finally, we add a classification layer.
model.add(layers.Dense(10))
Model: "sequential_6"
# Layer (type) Output Shape Param #
#=================================================================
# conv2d (Conv2D) (None, 123, 123, 32) 2432
# conv2d_1 (Conv2D) (None, 121, 121, 32) 9248
# max_pooling2d (MaxPooling2 (None, 40, 40, 32) 0
# D)
#Total params: 11680 (45.62 KB)
#Trainable params: 11680 (45.62 KB)
#Non-trainable params: 0 (0.00 Byte)
#_________________________________________________________________
#Model: "sequential_6"
#=================================================================
#conv2d (Conv2D) (None, 123, 123, 32) 2432
# conv2d_1 (Conv2D) (None, 121, 121, 32) 9248
# max_pooling2d (MaxPooling2 (None, 40, 40, 32) 0
# D)
# conv2d_2 (Conv2D) (None, 38, 38, 32) 9248
# conv2d_3 (Conv2D) (None, 36, 36, 32) 9248
# max_pooling2d_1 (MaxPoolin (None, 12, 12, 32) 0
# g2D)
# conv2d_4 (Conv2D) (None, 10, 10, 32) 9248
# conv2d_5 (Conv2D) (None, 8, 8, 32) 9248
#max_pooling2d_2 (MaxPoolin (None, 4, 4, 32) 0
# g2D)
#================================================================
#Total params: 48672 (190.12 KB)
#Trainable params: 48672 (190.12 KB)
#Non-trainable params: 0 (0.00 Byte)
initial_model = keras.Sequential(
[
keras.Input(shape=(250, 250, 3)),
layers.Conv2D(32, 5, strides=2, activation="relu"),
layers.Conv2D(32, 3, activation="relu"),
layers.Conv2D(32, 3, activation="relu"),
]
)
feature_extractor = keras.Model(
inputs=initial_model.inputs,
outputs=[layer.output for layer in initial_model.layers],
)
# Call feature extractor on test input.
x = tf.ones((1, 250, 250, 3))
features = feature_extractor(x)
initial_model = keras.Sequential(
[
keras.Input(shape=(250, 250, 3)),
layers.Conv2D(32, 5, strides=2, activation="relu"),
layers.Conv2D(32, 3, activation="relu", name="my_intermediate_layer"),
layers.Conv2D(32, 3, activation="relu"),
]
)
feature_extractor = keras.Model(
inputs=initial_model.inputs,
outputs=initial_model.get_layer(name="my_intermediate_layer").output,
)
# Call feature extractor on test input.
x = tf.ones((1, 250, 250, 3))
features = feature_extractor(x)
#model = keras.Sequential([ keras.Input(shape=(784)),
# layers.Dense(32, activation='relu'),
# layers.Dense(32, activation='relu'),
# layers.Dense(10)])
# Presumably you would want to first load pre-trained weights.
#
# Freeze all layers except the last one.
for layer in model.layers[:-1]:
layer.trainable = False
# Recompile and train (this will only update the weights of the last layer).
# Load a convolutional base with pre-trained weights
base_model = keras.applications.Xception(
weights='imagenet',
include_top=False,
pooling='avg')
# Freeze the base model
base_model.trainable = False
# Use a Sequential model to add a trainable classifier on top
model = keras.Sequential([
base_model,
layers.Dense(1000),
7.8.2024
Zusammenhang :
Hardwarevoraussetzung und Tensorflow.
Dieses Beispiel zeigt, dass bei kleineren Datenmegen
Tensorflow einwandfrei funktionieren kann.
Hier kann man den spezifischen Code sehr gut verstehen
.Gute Zeit OSWALD
Zusammenhang :
Hardwarevoraussetzung und Tensorflow.
Dieses Beispiel zeigt, dass bei kleineren Datenmegen
Tensorflow einwandfrei funktionieren kann.
Hier kann man den spezifischen Code sehr gut verstehen
.Gute Zeit OSWALD
Code: Alles auswählen
mport pandas as pd
import tensorflow as tf
print("TensorFlow version:", tf.__version__)
import tensorflow as tf
import pandas as pd
import matplotlib
from matplotlib import pyplot as plt
print("TensorFlow version:", tf.__version__)
# Set a random seed for reproducible results
tf.random.set_seed(45)
url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data'
column_names = ['MPG', 'Cylinders', 'Displacement', 'Horsepower', 'Weight',
'Acceleration', 'Model Year', 'Origin']
dataset = pd.read_csv(url, names=column_names, na_values='?', comment='\t',
sep=' ', skipinitialspace=True)
dataset = dataset.dropna()
dataset_tf = tf.convert_to_tensor(dataset, dtype=tf.float32)
dataset.tail()
dataset_shuffled = tf.random.shuffle(dataset_tf, seed=22)
train_data, test_data = dataset_shuffled[100:], dataset_shuffled[:100]
x_train, y_train = train_data[:, 1:], train_data[:, 0]
x_test, y_test = test_data[:, 1:], test_data[:, 0]
def onehot_origin(x):
origin = tf.cast(x[:, -1], tf.int32)
# Use `origin - 1` to account for 1-indexed feature
origin_oh = tf.one_hot(origin - 1, 3)
x_ohe = tf.concat([x[:, :-1], origin_oh], axis = 1)
return x_ohe
x_train_ohe, x_test_ohe = onehot_origin(x_train), onehot_origin(x_test)
x_train_ohe.numpy()
class Normalize(tf.Module):
def __init__(self, x):
# Initialize the mean and standard deviation for normalization
self.mean = tf.math.reduce_mean(x, axis=0)
self.std = tf.math.reduce_std(x, axis=0)
def norm(self, x):
# Normalize the input
return (x - self.mean)/self.std
def unnorm(self, x):
# Unnormalize the input
return (x * self.std) + self.mean
norm_x = Normalize(x_train_ohe)
norm_y = Normalize(y_train)
x_train_norm, y_train_norm = norm_x.norm(x_train_ohe), norm_y.norm(y_train)
x_test_norm, y_test_norm = norm_x.norm(x_test_ohe), norm_y.norm(y_test)
class LinearRegression(tf.Module):
def __init__(self):
self.built = False
@tf.function
def __call__(self, x):
# Initialize the model parameters on the first call
if not self.built:
# Randomly generate the weight vector and bias term
rand_w = tf.random.uniform(shape=[x.shape[-1], 1])
rand_b = tf.random.uniform(shape=[])
self.w = tf.Variable(rand_w)
self.b = tf.Variable(rand_b)
self.built = True
y = tf.add(tf.matmul(x, self.w), self.b)
return tf.squeeze(y, axis=1)
lin_reg = LinearRegression()
prediction = lin_reg(x_train_norm[:1])
prediction_unnorm = norm_y.unnorm(prediction)
prediction_unnorm.numpy()
def mse_loss(y_pred, y):
return tf.reduce_mean(tf.square(y_pred - y))
batch_size = 64
train_dataset = tf.data.Dataset.from_tensor_slices((x_train_norm, y_train_norm))
train_dataset = train_dataset.shuffle(buffer_size=x_train.shape[0]).batch(batch_size)
test_dataset = tf.data.Dataset.from_tensor_slices((x_test_norm, y_test_norm))
test_dataset = test_dataset.shuffle(buffer_size=x_test.shape[0]).batch(batch_size)
# Set training parameters
epochs = 100
learning_rate = 0.01
train_losses, test_losses = [], []
# Format training loop
for epoch in range(epochs):
batch_losses_train, batch_losses_test = [], []
# Iterate through the training data
for x_batch, y_batch in train_dataset:
with tf.GradientTape() as tape:
y_pred_batch = lin_reg(x_batch)
batch_loss = mse_loss(y_pred_batch, y_batch)
# Update parameters with respect to the gradient calculations
grads = tape.gradient(batch_loss, lin_reg.variables)
for g,v in zip(grads, lin_reg.variables):
v.assign_sub(learning_rate * g)
batch_losses_train.append(batch_loss)
# Iterate through the testing data
for x_batch, y_batch in test_dataset:
y_pred_batch = lin_reg(x_batch)
batch_loss = mse_loss(y_pred_batch, y_batch)
# Keep track of batch-level testing performance
batch_losses_test.append(batch_loss)
# Keep track of epoch-level model performance
train_loss = tf.reduce_mean(batch_losses_train)
test_loss = tf.reduce_mean(batch_losses_test)
train_losses.append(train_loss)
test_losses.append(test_loss)
if epoch % 10 == 0:
print(f'Mean squared error for step {epoch}: {train_loss.numpy():0.3f}')
# Output final losses
print(f"\nFinal train loss: {train_loss:0.3f}")
print(f"Final test loss: {test_loss:0.3f}")
matplotlib.rcParams['figure.figsize'] = [9, 6]
plt.plot(range(epochs), train_losses, label = "Training loss")
plt.plot(range(epochs), test_losses, label = "Testing loss")
plt.xlabel("Epoch")
plt.ylabel("Mean squared error loss")
plt.legend()
plt.title("MSE loss vs training iterations");
plt.show()
7.8.2024
Derzeit werde ich speziell im Bereich tensorflow tmit einem Problem konfrontiert.
Beim Start von Programmen kommt häufig die Meldung : Modul nicht gefunden.
Geht man der Meldung nach , zeigt sich, dass wieder ein Update stattgefunden hat.
Nach anschließender Neuinstallation ist alles wieder 'in Ordnung'.
Könnte man daraus zu schließen, dass die Entwicklung von Ki und Co gerade auf Hochtouren l äuft.?
Das Problem 'placeholder' ist gerade ein großes Problem für mch
OSWALD
Derzeit werde ich speziell im Bereich tensorflow tmit einem Problem konfrontiert.
Beim Start von Programmen kommt häufig die Meldung : Modul nicht gefunden.
Geht man der Meldung nach , zeigt sich, dass wieder ein Update stattgefunden hat.
Nach anschließender Neuinstallation ist alles wieder 'in Ordnung'.
Könnte man daraus zu schließen, dass die Entwicklung von Ki und Co gerade auf Hochtouren l äuft.?
Das Problem 'placeholder' ist gerade ein großes Problem für mch
OSWALD
8.8.2024
Ohne Placeholder geht in TENSOFLOW gar nichs.
Erklärungen gibt es im Netz sehr viele.
Das Thema ist sehr kompliziert.
Bisher bin ich nicht weiter gekommen wie unten gezeigt.
aber ich bemühe weiter.
OSWALD
Ohne Placeholder geht in TENSOFLOW gar nichs.
Erklärungen gibt es im Netz sehr viele.
Das Thema ist sehr kompliziert.
Bisher bin ich nicht weiter gekommen wie unten gezeigt.
aber ich bemühe weiter.
OSWALD
Code: Alles auswählen
print("Neueste Version :", tf.version.VERSION)
a= tf.compat.v1.placeholder
# creating a tensorflow graph
graph = tf.Graph()
with graph.as_default():
# creating a placeholder
a= tf.compat.v1.placeholder(tf.float64, shape=(3, 3), name='tensor1')
# creating an operation
b = a *3
# array1 will be fed into 'a'
array1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Creating a session, and running the graph
with tf.compat.v1.Session(graph=graph) as session:
# run the session until it reaches node b,
# then input an array of values into a
operation_res = session.run(b, feed_dict={a: array1})
print("after executing the operation: ")
print(operation_res)
10.8.2024
Ich zeige nun noch einen weiteren
Originalcode, der einerseits einwandfrei läuft,
aber immer wieder diese 'ominöse Warning'
in Bezug auf Paceholder bringt.
Ich glaube jetzt zu wissen,
dass für o hne CGU der Placeholder nicht darstellbar ist
und obendrei auch die Performance leidet.
Ich kann also leider sowohl tensorflow noch torch
nicht weiter erfolgreich vollenden.
Problem Placeholder ist jedenfalls gelöst
Gut eZeit OSWALD
Ich zeige nun noch einen weiteren
Originalcode, der einerseits einwandfrei läuft,
aber immer wieder diese 'ominöse Warning'
in Bezug auf Paceholder bringt.
Ich glaube jetzt zu wissen,
dass für o hne CGU der Placeholder nicht darstellbar ist
und obendrei auch die Performance leidet.
Ich kann also leider sowohl tensorflow noch torch
nicht weiter erfolgreich vollenden.
Problem Placeholder ist jedenfalls gelöst
Gut eZeit OSWALD
Code: Alles auswählen
import tensorflow as tf
x = tf.constant([[1., 2., 3.],
[4., 5., 6.]])
print(x)
print(x.shape)
print(x.dtype)
x + x
5 * x
x @ tf.transpose(x)
tf.concat([x, x, x], axis=0)
tf.nn.softmax(x, axis=-1)
tf.reduce_sum(x)
tf.convert_to_tensor([1,2,3])
tf.reduce_sum([1,2,3])
if tf.config.list_physical_devices('GPU'):
print("TensorFlow **IS** using the GPU")
else:
print("TensorFlow **IS NOT** using the GPU")
var = tf.Variable([0.0, 0.0, 0.0])
var.assign([1, 2, 3])
var.assign_add([1, 1, 1])
x = tf.Variable(1.0)
def f(x):
y = x**2 + 2*x - 5
return y
print(f(x))
#At x = 1.0, y = f(x) = (1**2 + 2*1 - 5) = -2.
with tf.GradientTape() as tape:
y = f(x)
g_x = tape.gradient(y, x) # g(x) = dy/dx
g_x
@tf.function
def my_func(x):
print('Tracing.\n')
return tf.reduce_sum(x)
x = tf.constant([1, 2, 3])
my_func(x)
x = tf.constant([10, 9, 8])
my_func(x)
x = tf.constant([10.0, 9.1, 8.2], dtype=tf.float32)
my_func(x)
class MyModule(tf.Module):
def __init__(self, value):
self.weight = tf.Variable(value)
@tf.function
def multiply(self, x):
return x * self.weight
mod = MyModule(3)
mod.multiply(tf.constant([1, 2, 3]))
save_path = './saved'
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams['figure.figsize'] = [9, 6]
x = tf.linspace(-2, 2, 201)
x = tf.cast(x, tf.float32)
def f(x):
y = x**2 + 2*x - 5
return y
y = f(x) + tf.random.normal(shape=[201])
plt.plot(x.numpy(), y.numpy(), '.', label='Data')
plt.plot(x, f(x), label='Ground truth')
plt.legend();
###################################################
class Model(tf.Module):
def __init__(self):
# Randomly generate weight and bias terms
rand_init = tf.random.uniform(shape=[3], minval=0., maxval=5., seed=22)
# Initialize model parameters
self.w_q = tf.Variable(rand_init[0])
self.w_l = tf.Variable(rand_init[1])
self.b = tf.Variable(rand_init[2])
@tf.function
def __call__(self, x):
# Quadratic Model : quadratic_weight * x^2 + linear_weight * x + bias
return self.w_q * (x**2) + self.w_l * x + self.b
quad_model = Model()
def plot_preds(x, y, f, model, title):
plt.figure()
plt.plot(x, y, '.', label='Data')
plt.plot(x, f(x), label='Ground truth')
plt.plot(x, model(x), label='Predictions')
plt.title(title)
plt.legend()
plot_preds(x, y, f, quad_model, 'Before training')
def mse_loss(y_pred, y):
return tf.reduce_mean(tf.square(y_pred - y))
batch_size = 32
dataset = tf.data.Dataset.from_tensor_slices((x, y))
dataset = dataset.shuffle(buffer_size=x.shape[0]).batch(batch_size)
# Set training parameters
epochs = 100
learning_rate = 0.01
losses = []
# Format training loop
for epoch in range(epochs):
for x_batch, y_batch in dataset:
with tf.GradientTape() as tape:
batch_loss = mse_loss(quad_model(x_batch), y_batch)
# Update parameters with respect to the gradient calculations
grads = tape.gradient(batch_loss, quad_model.variables)
for g,v in zip(grads, quad_model.variables):
v.assign_sub(learning_rate*g)
# Keep track of model loss per epoch
loss = mse_loss(quad_model(x), y)
losses.append(loss)
if epoch % 10 == 0:
print(f'Mean squared error for step {epoch}: {loss.numpy():0.3f}')
# Plot model results
print("\n")
plt.plot(range(epochs), losses)
plt.xlabel("Epoch")
plt.ylabel("Mean Squared Error (MSE)")
plt.title('MSE loss vs training iterations');
plot_preds(x, y, f, quad_model, 'After training')
new_model = tf.keras.Sequential([
tf.keras.layers.Lambda(lambda x: tf.stack([x, x**2], axis=1)),
tf.keras.layers.Dense(units=1, kernel_initializer=tf.random.normal)])
new_model.compile(
loss=tf.keras.losses.MSE,
optimizer=tf.keras.optimizers.SGD(learning_rate=0.01))
history = new_model.fit(x, y,
epochs=100,
batch_size=32,
verbose=0)
plt.plot(history.history['loss'])
plt.xlabel('Epoch')
plt.ylim([0, max(plt.ylim())])
plt.ylabel('Loss [Mean Squared Error]')
plt.title('Keras training progress');
plot_preds(x, y, f, new_model, 'After Training: Keras')
plt.show()
11.8.2024
Zur Abwechslung ein neues Thema.
NETWORKX und GRAPHVIZ.
ein erstes Beispiel
S pielend lernen.
Gute Zeit OSWALD
Zur Abwechslung ein neues Thema.
NETWORKX und GRAPHVIZ.
ein erstes Beispiel
S pielend lernen.
Gute Zeit OSWALD
Code: Alles auswählen
import matplotlib.pyplot as plt
import networkx as nx
from networkx import Graph
class PrintGraph(Graph):
"""
Example subclass of the Graph class.
Prints activity log to file or standard output.
"""
def __init__(self, data=None, name="", file=None, **attr):
super().__init__(data=data, name=name, **attr)
if file is None:
import sys
self.fh = sys.stdout
else:
self.fh = open(file, "w")
def add_node(self, n, attr_dict=None, **attr):
super().add_node(n, attr_dict=attr_dict, **attr)
self.fh.write(f"Add node: {n}\n")
def add_nodes_from(self, nodes, **attr):
for n in nodes:
self.add_node(n, **attr)
def remove_node(self, n):
super().remove_node(n)
self.fh.write(f"Remove node: {n}\n")
def remove_nodes_from(self, nodes):
for n in nodes:
self.remove_node(n)
def add_edge(self, u, v, attr_dict=None, **attr):
super().add_edge(u, v, attr_dict=attr_dict, **attr)
self.fh.write(f"Add edge: {u}-{v}\n")
def add_edges_from(self, ebunch, attr_dict=None, **attr):
for e in ebunch:
u, v = e[0:2]
self.add_edge(u, v, attr_dict=attr_dict, **attr)
def remove_edge(self, u, v):
super().remove_edge(u, v)
self.fh.write(f"Remove edge: {u}-{v}\n")
def remove_edges_from(self, ebunch):
for e in ebunch:
u, v = e[0:2]
self.remove_edge(u, v)
def clear(self):
super().clear()
self.fh.write("Clear graph\n")
G = PrintGraph()
G.add_node("foo")
G.add_nodes_from("bar", weight=18)
G.remove_node("b")
G.remove_nodes_from("ar")
print("Nodes in G: ", G.nodes(data=True))
G.add_edge(0, 1, weight=10)
print("Edges in G: ", G.edges(data=True))
G.remove_edge(0, 1)
G.add_edges_from(zip(range(3), range(1, 4)), weight=10)
print("Edges in G: ", G.edges(data=True))
G.remove_edges_from(zip(range(3), range(1, 4)))
print("Edges in G: ", G.edges(data=True))
G = PrintGraph()
nx.add_path(G, range(10))
nx.add_star(G, range(0,20)) #1 Edges, 2 Knoten)
pos = nx.spring_layout(G, seed= 225) # Seed for reproducible layout
nx.draw(G, pos)
plt.show()
Versuche mich gerade am Thema
Neuronales Netz.
Habe einen ganz einfachen Code gefunden ,
der sehr gut erklärt worum es hier geht.
Gute Zeit OSWALD
Neuronales Netz.
Habe einen ganz einfachen Code gefunden ,
der sehr gut erklärt worum es hier geht.
Gute Zeit OSWALD
Code: Alles auswählen
# neuronales netzwerk einfachste Struktur
import numpy as np
# Eingabedaten
X = np.array([[0,1, 1],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1]])
# Erwartete Ausgabedaten
y = np.array([[0],
[1],
[1],
[0]])
# Anzahl der Eingabe- und Ausgabeneuronen
input_neurons = X.shape[1]
output_neurons = y.shape[1]
# Anzahl der Neuronen in der versteckten Schicht
hidden_neurons = 10
# Definition der Aktivierungsfunktion (Sigmoid)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# Initialisierung der Gewichtungsmatrizen
# Gewichte zwischen Eingabe- und versteckter Schicht
weights_input_hidden = np.random.rand(input_neurons, hidden_neurons)
# Gewichte zwischen versteckter Schicht und Ausgabe
weights_hidden_output = np.random.rand(hidden_neurons, output_neurons)
# Anzahl der Epochen für das Training
epochs = 5 # epoch 5-5000
# Trainingschleife
for epoch in range(epochs):
# Vorwärtspropagation (Forward Propagation)
hidden_layer_input = np.dot(X, weights_input_hidden)
hidden_layer_output = sigmoid(hidden_layer_input)
print("HIDDENLAYER", hidden_layer_output)
output = sigmoid(np.dot(hidden_layer_output, weights_hidden_output))
# Berechnung des Fehlers (Error)
error = y - output
# Definition der Ableitung der Aktivierungsfunktion (Sigmoid)
def sigmoid_derivative(x):
return x * (1 - x)
# Initialisierung der Gewichtungsmatrizen
# Gewichte zwischen Eingabe- und versteckter Schicht
weights_input_hidden = np.random.rand(input_neurons, hidden_neurons)
# Gewichte zwischen versteckter Schicht und Ausgabe
weights_hidden_output = np.random.rand(hidden_neurons, output_neurons)
# Anzahl der Epochen für das Training
epochs = 5 #5 -5000
# Trainingschleife
for epoch in range(epochs):
# Vorwärtspropagation (Forward Propagation)
hidden_layer_input = np.dot(X, weights_input_hidden)
hidden_layer_output = sigmoid(hidden_layer_input)
output = sigmoid(np.dot(hidden_layer_output, weights_hidden_output))
# Berechnung des Fehlers (Error)
error = y - output
# print("Error ",error )
# Rückwärtspropagation (Backpropagation) und Gewichtsanpassung
d_weights_hidden_output = np.dot(hidden_layer_output.T, error * sigmoid_derivative(output))
d_weights_input_hidden = np.dot(X.T, np.dot(error * sigmoid_derivative(output), weights_hidden_output.T) * sigmoid_derivative(hidden_layer_output))
weights_hidden_output += d_weights_hidden_output
weights_input_hidden += d_weights_input_hidden
print(weights_input_hidden)
# Ausgabe der finalen Vorhersage
print(output)
20.8.2024
Nach Beseitigung divsrser Inkompitbilitäten
durch Neuinstallation von Modulen und
eines geeigneten Datensatzes konnte ich
den folgenden Code herunterladen.
Es andelt sch um das Thema Classifizierung.
Gute Zeit OSWALD
Nach Beseitigung divsrser Inkompitbilitäten
durch Neuinstallation von Modulen und
eines geeigneten Datensatzes konnte ich
den folgenden Code herunterladen.
Es andelt sch um das Thema Classifizierung.
Gute Zeit OSWALD
Code: Alles auswählen
mport os
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
#Prepare the Dataset
#The Cora dataset consists of 2,708 scientific papers classified into one of seven classes.
#The citation network consists of 5,429 links.
#Each paper has a binary word vector of size 1,433, indicating the presence of a corresponding word.
#Download the dataset
#The dataset has two tap-separated files: cora.cites and cora.content.
#The cora.cites includes the citation records with two columns: cited_paper_id (target) and citing_paper_id (source).
#The cora.content includes the paper content records with 1,435 columns: paper_id, subject, and 1,433 binary features.
#Let's download the dataset.
zip_file = keras.utils.get_file(
fname="cora.tgz",
origin="https://linqs-data.soe.ucsc.edu/public/lbc/cora.tgz",
extract=True,
)
data_dir = os.path.join(os.path.dirname(zip_file), "cora")
#Process and visualize the dataset
#Then we load the citations data into a Pandas DataFrame.
citations = pd.read_csv(
os.path.join(data_dir, "cora.cites"),
sep="\t",
header=None,
names=["target", "source"],
)
print("Citations shape:", citations.shape)
#Citations shape: (5429, 2)
#Now we display a sample of the citations DataFrame. The target column includes the paper ids cited by the paper ids in the source column.
citations.sample(frac=1).head()
#pers data into a Pandas DataFrame.
column_names = ["paper_id"] + [f"term_{idx}" for idx in range(1433)] + ["subject"]
papers = pd.read_csv(
os.path.join(data_dir, "cora.content"), sep="\t", header=None, names=column_names,
)
print("Papers shape:", papers.shape)
print(papers.sample(5).T)
print(papers.subject.value_counts())
class_values = sorted(papers["subject"].unique())
class_idx = {name: id for id, name in enumerate(class_values)}
paper_idx = {name: idx for idx, name in enumerate(sorted(papers["paper_id"].unique()))}
papers["paper_id"] = papers["paper_id"].apply(lambda name: paper_idx[name])
citations["source"] = citations["source"].apply(lambda name: paper_idx[name])
citations["target"] = citations["target"].apply(lambda name: paper_idx[name])
papers["subject"] = papers["subject"].apply(lambda value: class_idx[value])
#Now let's visualize the citation graph. Each node in the graph represents a paper, and the color of the node corresponds to its subject. Note that we only show a sample of the papers in the dataset.
plt.figure(figsize=(10, 10))
colors = papers["subject"].tolist()
cora_graph = nx.from_pandas_edgelist(citations.sample(n=1500))
subjects = list(papers[papers["paper_id"].isin(list(cora_graph.nodes))]["subject"])
nx.draw_spring(cora_graph, node_size=15, node_color=subjects)
plt.show()
21.8.2024
Für mich als Anfänger der Programmiersprache PYTHON
ist mein größter Feind . Der Frust.
Um diesem zu entgehen habe ich mich kurzfristig entschlossen
eines anderes Thema zu wählen, von dem ich
glaube alles besser zu verstehen.
Im Zusammenhang mit 'Neuronal' & Co bin auf matplotlib
gstossen. eine erste Frage war: Was ist die implizite pyplot-Schnittstelle.
Und gleich danach stieß ich auf die GCA-Schnittstelle.
Es geht natürlich weiter , zunächst einige Beispiele
OSWALD
Für mich als Anfänger der Programmiersprache PYTHON
ist mein größter Feind . Der Frust.
Um diesem zu entgehen habe ich mich kurzfristig entschlossen
eines anderes Thema zu wählen, von dem ich
glaube alles besser zu verstehen.
Im Zusammenhang mit 'Neuronal' & Co bin auf matplotlib
gstossen. eine erste Frage war: Was ist die implizite pyplot-Schnittstelle.
Und gleich danach stieß ich auf die GCA-Schnittstelle.
Es geht natürlich weiter , zunächst einige Beispiele
OSWALD
Code: Alles auswählen
# Die implizite pyplot-Schnittstelle
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [0, 0.5, 1, 0.2])
plt.show()
Was sich hinter CGA 'versteckt und welche
Bedeteung diese Schnittstelle für die Visualisierung hat,
kann man schnell erkennen.
Bedeteung diese Schnittstelle für die Visualisierung hat,
kann man schnell erkennen.
Code: Alles auswählen
# GPA anwenden
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-2 * np.pi, 2 * np.pi, 70, endpoint=True)
F1 = X * np.sin(X) + np.cos(X)
ax = plt.gca() # CGA
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('red')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
# Labelung der X-Achse:
plt.xticks( [-6.28, -3.14, 3.14, 6.28],
[r'$-2\pi$', r'$-\pi$', r'$+\pi$', r'$+2\pi$'])
plt.yticks([-3, -1, 0, +1, 3])
plt.plot(X, F1)
plt.show()
21.8.24
Hier ein Beispiel, bei dem man zunächst nicht erkennt,
dass auch hier CGA die Hauptrolle spielt.
Ich gjhabe herausgefunden, dass man sich bei
jeder Svhnittstelle auch in der zuständigen API
umchauen m,uss . Irgendwie kam ich zum Schluss
auf eine CGA-Code, den ich eigentlich
schon lange gesuchgt hatte.
OSWALD
Hier ein Beispiel, bei dem man zunächst nicht erkennt,
dass auch hier CGA die Hauptrolle spielt.
Ich gjhabe herausgefunden, dass man sich bei
jeder Svhnittstelle auch in der zuständigen API
umchauen m,uss . Irgendwie kam ich zum Schluss
auf eine CGA-Code, den ich eigentlich
schon lange gesuchgt hatte.
OSWALD
Code: Alles auswählen
mport matplotlib.pyplot as plt
import numpy as np
import matplotlib
import matplotlib as mpl
vegetables = ["cucumber", "tomato", "lettuce", "asparagus",
"potato", "wheat", "barley"]
farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening",
"Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."]
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
[2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
[1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
[0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
[0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
[1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
[0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])
fig, ax = plt.subplots()
im = ax.imshow(harvest)
# Show all ticks and label them with the respective list entries
ax.set_xticks(np.arange(len(farmers)), labels=farmers)
ax.set_yticks(np.arange(len(vegetables)), labels=vegetables)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
for i in range(len(vegetables)):
for j in range(len(farmers)):
text = ax.text(j, i, harvest[i, j],
ha="center", va="center", color="w")
ax.set_title("Harvest of local farmers (in tons/year)")
fig.tight_layout()
plt.show()
Durch Zufall fand ich dann mein lange gesuchtes Zielobjekt.
Die Zeichnung eines Neuronal-Netzes.
Diesen Code muss ich mir ganz genau anschauen.
Ende des Frustes.
Gute Zeit OSWALD
Die Zeichnung eines Neuronal-Netzes.
Diesen Code muss ich mir ganz genau anschauen.
Ende des Frustes.
Gute Zeit OSWALD
Code: Alles auswählen
mport os
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
zip_file = keras.utils.get_file(
fname="cora.tgz",
origin="https://linqs-data.soe.ucsc.edu/public/lbc/cora.tgz",
extract=True,
)
data_dir = os.path.join(os.path.dirname(zip_file), "cora")
#Process and visualize the dataset
#Then we load the citations data into a Pandas DataFrame.
citations = pd.read_csv(
os.path.join(data_dir, "cora.cites"),
sep="\t",
header=None,
names=["target", "source"],
)
print("Citations shape:", citations.shape)
#Citations shape: (5429, 2)
#Now we display a sample of the citations DataFrame. The target column includes the paper ids cited by the paper ids in the source column.
citations.sample(frac=1).head()
#pers data into a Pandas DataFrame.
column_names = ["paper_id"] + [f"term_{idx}" for idx in range(1433)] + ["subject"]
papers = pd.read_csv(
os.path.join(data_dir, "cora.content"), sep="\t", header=None, names=column_names,
)
print("Papers shape:", papers.shape)
print(papers.sample(5).T)
print(papers.subject.value_counts())
class_values = sorted(papers["subject"].unique())
class_idx = {name: id for id, name in enumerate(class_values)}
paper_idx = {name: idx for idx, name in enumerate(sorted(papers["paper_id"].unique()))}
papers["paper_id"] = papers["paper_id"].apply(lambda name: paper_idx[name])
citations["source"] = citations["source"].apply(lambda name: paper_idx[name])
citations["target"] = citations["target"].apply(lambda name: paper_idx[name])
papers["subject"] = papers["subject"].apply(lambda value: class_idx[value])
#Now let's visualize the citation graph. Each node in the graph represents a paper, and the color of the node corresponds to its subject. Note that we only show a sample of the papers in the dataset.
plt.figure(figsize=(10, 10))
colors = papers["subject"].tolist()
cora_graph = nx.from_pandas_edgelist(citations.sample(n=1500))
subjects = list(papers[papers["paper_id"].isin(list(cora_graph.nodes))]["subject"])
nx.draw_spring(cora_graph, node_size=15, node_color=subjects)
plt.show()
23.8.2024
Einmal mit der möglichen Struktur eines Neuronale Netze vertraut,
würde ich dieses gerne auch 'mit Leben füllen'.
Ich beginne deshalb damit ein Modell zu erstellen.
Hier stelle ich als ersten S chritt ein Modell vor.
Es ist eine 'funktionale API' , quasi als Einstieg mit
weiteren Beispielen je nach Fortschritt.
Matrix als kleiner Datensatz
Ich werde jetzt versuchen duirch Veränderung de
Matrixunterschiedlich große Datensätze zu testen.
Dam,it kann ich gleichzeitig die Kapazität meiner CPU austesten.
Gute Zeit OSWALD
Einmal mit der möglichen Struktur eines Neuronale Netze vertraut,
würde ich dieses gerne auch 'mit Leben füllen'.
Ich beginne deshalb damit ein Modell zu erstellen.
Hier stelle ich als ersten S chritt ein Modell vor.
Es ist eine 'funktionale API' , quasi als Einstieg mit
weiteren Beispielen je nach Fortschritt.
Matrix als kleiner Datensatz
Ich werde jetzt versuchen duirch Veränderung de
Matrixunterschiedlich große Datensätze zu testen.
Dam,it kann ich gleichzeitig die Kapazität meiner CPU austesten.
Gute Zeit OSWALD
Code: Alles auswählen
# Die funktionale API von Keras kann Modelle erstellen,
# die flexibler sind als die keras.SequentialAPI.
# Die funktionale API kann Modelle mit nichtlinearer Topologie,
# gemeinsam genutzte Ebenen und sogar mehrere
# Ein- oder Ausgaben verarbeiten.
import numpy as np
import keras
from keras import layers
from keras import ops
#Eingabeknoten
inputs = keras.Input(shape=(784,))
# zur Deminstration
img_inputs = keras.Input(shape=(32, 32, 3))
# Form und Datentyp
inputs.shape
inputs.dtype
#Aufruf einer Knotenebene
dense = layers.Dense(64, activation="relu")
x = dense(inputs)
# noch ein paar weitere Ebenen
x = layers.Dense(64, activation="relu")(x)
outputs = layers.Dense(10)(x)
model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model")
#Schauen wir uns an, wie die Modellzusammenfassung aussieht:
print(model.summary())