24 KiB
24 KiB
In [159]:
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
import numpy as np
import structIn [160]:
x = np.array([[0.5, 0.1, 0.2, 0.8], [0.75, 0.3, 0.1, 0.9], [0.1, 0.7, 0.6, 0.2]])
Wh = np.array([
[0.1, 0.1, -0.3],
[0.1, 0.2, 0.0],
[0.0, 0.7, 0.1],
[0.2, 0.4, 0.0],
[-0.3, 0.5, 0.1]
])
Wy = np.array([
[0.7, 0.9, -0.4, 0.8, 0.1],
[0.8, 0.5, 0.3, 0.1, 0.0],
[-0.3, 0.9, 0.3, 0.1, -0.2]
])
def ReLu(x):
return np.maximum(x, 0)
def deep_neural_network(input, weights_h, weights_y):
layer_hidden_1 = np.dot(weights_h, input)
layer_hidden_1_r = ReLu(layer_hidden_1)
layer_output = np.dot(weights_y, layer_hidden_1_r)
return layer_hidden_1, layer_hidden_1_r, layer_output
layer_hidden_1, layer_hidden_1_r, layer_output = deep_neural_network(x, Wh, Wy)
print(layer_output)
[[0.376 0.082 0.053 0.49 ] [0.3765 0.133 0.067 0.465 ] [0.305 0.123 0.073 0.402 ]]
In [161]:
goal = np.array([
[0.1, 0.5, 0.1, 0.7],
[1.0, 0.2, 0.3, 0.6],
[0.1, -0.5, 0.2, 0.2],
])
alpha = 0.01
epochs = 50
def ReLu_deriv(x):
return np.where(x > 0, 1, 0)
def supervised_learning(input, weights_h, weights_y, goal, alpha, epochs):
num_neurons = goal.shape[0]
num_series = input.shape[1]
for i in range(epochs):
for j in range(num_series):
series_input = input[:, j:j + 1]
series_goal = goal[:, j:j + 1]
layer_hidden_1, layer_hidden_1_r, layer_output = deep_neural_network(series_input, weights_h, weights_y)
layer_output_delta = (2 / num_neurons) * (layer_output - series_goal)
layer_hidden_delta = np.dot(weights_y.T, layer_output_delta)
layer_hidden_delta = layer_hidden_delta * ReLu_deriv(layer_hidden_1)
layer_output_weight_delta = np.dot(layer_output_delta, layer_hidden_1_r.T)
layer_hidden_weight_delta = np.dot(layer_hidden_delta, series_input.T)
weights_h = weights_h - alpha * layer_hidden_weight_delta
weights_y = weights_y - alpha * layer_output_weight_delta
if (i == epochs - 1):
print(f"\nSeria {j + 1}:")
print(np.round(layer_output, 6))
return layer_output
output = supervised_learning(x, Wh, Wy, goal, alpha, epochs)
Seria 1: [[0.442756] [0.565494] [0.157309]] Seria 2: [[0.140418] [0.186105] [0.063895]] Seria 3: [[0.105594] [0.093659] [0.045049]] Seria 4: [[0.584537] [0.711427] [0.216373]]
In [162]:
def sigmoid(x):
x = np.clip(x, -500, 500)
return 1 / (1 + np.exp(-x))
def sigmoid_deriv(x):
return x * (1 - x)
class NeuralNewtork:
def __init__(self, n, a=0.01):
self.num_neurons = n
self.alpha = a
self.layers = {
'weights': [],
'activation_function': [],
'derivative_function': [],
}
def add_layer(self, n, activation_func):
weights = np.random.uniform(-1, 1, (n, self.num_neurons))
self.layers['weights'].append(weights)
self.num_neurons = n
if activation_func is not None:
self.layers['activation_function'].append(activation_func)
if activation_func == 'sigmoid':
self.layers['derivative_function'].append(sigmoid_deriv)
else:
self.layers['derivative_function'].append(ReLu_deriv)
else:
self.layers['activation_function'].append(None)
self.layers['derivative_function'].append(None)
def forward_propagation(self, input):
activation = []
raw_output = []
current_input = input
for i in range(len(self.layers['weights'])):
z = np.dot(self.layers['weights'][i], current_input)
raw_output.append(z)
a = self.layers['activation_function'][i](z)
activation.append(a)
current_input = a
return activation, raw_output
def back_propagation(self, activation, input, raw_output, expected_output):
N = expected_output.shape[0]
layer_output_delta = (2 * 1 / N) * (activation[-1] - expected_output)
layer_hidden_delta = np.dot(self.layers['weights'][-1].T, layer_output_delta)
layer_output_weight_delta = np.dot(layer_output_delta, activation[-2].T)
self.layers['weights'][-1] = self.layers['weights'][-1] - self.alpha * layer_output_weight_delta
for i in reversed(range(len(self.layers['weights']) - 1)):
layer_hidden_delta = layer_hidden_delta * self.layers['derivative_function'][i](raw_output[i])
wejscie_lub_aktywacja = activation[i - 1] if i > 0 else input
layer_hidden_weight_delta = np.dot(layer_hidden_delta, wejscie_lub_aktywacja.T)
self.layers['weights'][i] = self.layers['weights'][i] - self.alpha * layer_hidden_weight_delta
def fit(self, input, expected_output):
input_data = (input.copy()).reshape(1, -1).T
activation, raw_output = self.forward_propagation(input_data)
self.back_propagation(activation, input_data, raw_output, expected_output)
def predict(self, input):
input_data = (input.copy()).reshape(-1, 1)
activation, _ = self.forward_propagation(input_data)
return activation[-1]
def load_mnist_images(filename):
with open(filename, 'rb') as f:
magic, num_images, rows, cols = struct.unpack('>IIII', f.read(16))
image_data = np.frombuffer(f.read(), dtype=np.uint8)
images = image_data.reshape(num_images, rows * cols).astype(np.float32) / 255.0
return images
def load_mnist_labels(filename):
with open(filename, 'rb') as f:
magic, num_labels = struct.unpack('>II', f.read(8))
labels = np.frombuffer(f.read(), dtype=np.uint8)
return labels
def to_one_hot(label, num_classes=10):
one_hot = np.zeros((num_classes, 1))
one_hot[label] = 1.0
return one_hotIn [163]:
nn = NeuralNewtork(784)
nn.add_layer(40, ReLu)
nn.add_layer(10, ReLu)
train_image = load_mnist_images('train-images.idx3-ubyte')
train_image_labels = load_mnist_labels('train-labels.idx1-ubyte')
test_image = load_mnist_images('t10k-images.idx3-ubyte')
test_image_labels = load_mnist_labels('t10k-labels.idx1-ubyte')
epochs = 6
print("Rozpoczynam proces uczenia sieci...")
for epoch in range(epochs):
correct_train = 0
for i in range(len(train_image)):
x = train_image[i].reshape(-1, 1)
label = train_image_labels[i]
expected = to_one_hot(label)
nn.fit(x, expected)
activation = nn.predict(x)
predicted_label = np.argmax(activation)
if predicted_label == label:
correct_train += 1
train_accuracy = correct_train / len(train_image) * 100
print(f"Epoka {epoch + 1}/{epochs} zakończona. Skuteczność treningowa: {train_accuracy:.2f}%")
Rozpoczynam proces uczenia sieci... Epoka 1/6 zakończona. Skuteczność treningowa: 61.03% Epoka 2/6 zakończona. Skuteczność treningowa: 77.58% Epoka 3/6 zakończona. Skuteczność treningowa: 83.84% Epoka 4/6 zakończona. Skuteczność treningowa: 86.83% Epoka 5/6 zakończona. Skuteczność treningowa: 88.48% Epoka 6/6 zakończona. Skuteczność treningowa: 89.54%
In [164]:
print("\n--- TESTOWANIE SIECI (Zbiór testowy t10k) ---")
correct_test = 0
for i in range(len(test_image)):
x = test_image[i].reshape(-1, 1)
label = test_image_labels[i]
activation = nn.predict(x)
predicted_label = np.argmax(activation)
if predicted_label == label:
correct_test += 1
test_accuracy = correct_test / len(test_image) * 100
print(f"Skuteczność testowa modelu: {test_accuracy:.2f}%")--- TESTOWANIE SIECI (Zbiór testowy t10k) --- Skuteczność testowa modelu: 82.61%
In [165]:
data = np.loadtxt('training_colors.txt')
input = data[:, :3]
input_info = data[:, 3]
goal = np.zeros((1, 4))
color_map = {
1: [1.0, 0.0, 0.0, 0.0], # Czerwony
2: [0.0, 1.0, 0.0, 0.0], # Zielony
3: [0.0, 0.0, 1.0, 0.0], # Niebieski
4: [0.0, 0.0, 0.0, 1.0], # Żółty
}
goal_list = [color_map[int(label)] for label in input_info]
goal = np.array(goal_list)
nn = NeuralNewtork(3)
nn.add_layer(16, ReLu)
nn.add_layer(4, ReLu)
epochs = 10
print("Rozpoczynam proces uczenia sieci...")
for epoch in range(epochs):
correct_train = 0
for i in range(len(data)):
x = input[i].reshape(-1, 1)
expected = goal[i].reshape(-1, 1)
nn.fit(x, expected)
activation = nn.predict(x)
predicted_label = np.argmax(activation)
if predicted_label == int(input_info[i]) - 1:
correct_train += 1
train_accuracy = correct_train / len(data) * 100
print(f"Epoka {epoch + 1}/{epochs} zakończona. Skuteczność treningowa: {train_accuracy:.2f}%")
Rozpoczynam proces uczenia sieci... Epoka 1/10 zakończona. Skuteczność treningowa: 50.46% Epoka 2/10 zakończona. Skuteczność treningowa: 90.83% Epoka 3/10 zakończona. Skuteczność treningowa: 100.00% Epoka 4/10 zakończona. Skuteczność treningowa: 100.00% Epoka 5/10 zakończona. Skuteczność treningowa: 100.00% Epoka 6/10 zakończona. Skuteczność treningowa: 100.00% Epoka 7/10 zakończona. Skuteczność treningowa: 100.00% Epoka 8/10 zakończona. Skuteczność treningowa: 100.00% Epoka 9/10 zakończona. Skuteczność treningowa: 100.00% Epoka 10/10 zakończona. Skuteczność treningowa: 100.00%
In [166]:
test_data = np.loadtxt('test_colors.txt')
input_test = test_data[:, :3]
input_test_info = (test_data[:, 3] - 1)
print("\n--- TESTOWANIE SIECI (Zbiór testowy t10k) ---")
correct_test = 0
for i in range(len(test_data)):
x = input_test[i].reshape(-1, 1)
activation = nn.predict(x)
predicted_label = np.argmax(activation)
if predicted_label == int(input_test_info[i]):
correct_test += 1
test_accuracy = correct_test / len(test_data) * 100
print(f"Skuteczność testowa modelu: {test_accuracy:.2f}%")--- TESTOWANIE SIECI (Zbiór testowy t10k) --- Skuteczność testowa modelu: 100.00%
In [167]:
y_test = keras.utils.to_categorical(input_test_info, num_classes=4)
model = Sequential()
model.add(keras.Input(shape=(3,)))
model.add(Dense(16, use_bias=False, activation='relu'))
model.add(Dense(4, use_bias=False))
opt = SGD(learning_rate=0.01)
model.compile(opt, loss='mse', metrics=['accuracy'])
model.fit(
input,
goal,
epochs=25,
batch_size=5,
validation_data=(input_test, y_test),
verbose=1
)
test_loss, test_accuracy = model.evaluate(input_test, y_test, verbose=0)
print(f"\nSkuteczność modelu na zbiorze testowym: {test_accuracy * 100:.2f}%")Epoch 1/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 7ms/step - accuracy: 0.2294 - loss: 0.2698 - val_accuracy: 0.2231 - val_loss: 0.2566 Epoch 2/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.2294 - loss: 0.2477 - val_accuracy: 0.2615 - val_loss: 0.2374 Epoch 3/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.2294 - loss: 0.2316 - val_accuracy: 0.2923 - val_loss: 0.2229 Epoch 4/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.2661 - loss: 0.2192 - val_accuracy: 0.3308 - val_loss: 0.2115 Epoch 5/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.2661 - loss: 0.2092 - val_accuracy: 0.3385 - val_loss: 0.2021 Epoch 6/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.3028 - loss: 0.2011 - val_accuracy: 0.3308 - val_loss: 0.1944 Epoch 7/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.3028 - loss: 0.1943 - val_accuracy: 0.3231 - val_loss: 0.1877 Epoch 8/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.2936 - loss: 0.1883 - val_accuracy: 0.3154 - val_loss: 0.1820 Epoch 9/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.3394 - loss: 0.1829 - val_accuracy: 0.3615 - val_loss: 0.1768 Epoch 10/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.3670 - loss: 0.1782 - val_accuracy: 0.4154 - val_loss: 0.1720 Epoch 11/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.4037 - loss: 0.1738 - val_accuracy: 0.4538 - val_loss: 0.1678 Epoch 12/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.4312 - loss: 0.1698 - val_accuracy: 0.4923 - val_loss: 0.1638 Epoch 13/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.4679 - loss: 0.1661 - val_accuracy: 0.5154 - val_loss: 0.1601 Epoch 14/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.4679 - loss: 0.1627 - val_accuracy: 0.5538 - val_loss: 0.1567 Epoch 15/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.5046 - loss: 0.1594 - val_accuracy: 0.5615 - val_loss: 0.1533 Epoch 16/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.5046 - loss: 0.1562 - val_accuracy: 0.5538 - val_loss: 0.1501 Epoch 17/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.5229 - loss: 0.1531 - val_accuracy: 0.5846 - val_loss: 0.1470 Epoch 18/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.5505 - loss: 0.1499 - val_accuracy: 0.6231 - val_loss: 0.1439 Epoch 19/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.5780 - loss: 0.1469 - val_accuracy: 0.6615 - val_loss: 0.1410 Epoch 20/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 4ms/step - accuracy: 0.6147 - loss: 0.1438 - val_accuracy: 0.6615 - val_loss: 0.1381 Epoch 21/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.6422 - loss: 0.1410 - val_accuracy: 0.6769 - val_loss: 0.1353 Epoch 22/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.6697 - loss: 0.1382 - val_accuracy: 0.7000 - val_loss: 0.1326 Epoch 23/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.6972 - loss: 0.1354 - val_accuracy: 0.7077 - val_loss: 0.1299 Epoch 24/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.7248 - loss: 0.1327 - val_accuracy: 0.7308 - val_loss: 0.1273 Epoch 25/25 [1m22/22[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 3ms/step - accuracy: 0.7523 - loss: 0.1303 - val_accuracy: 0.7615 - val_loss: 0.1248 Skuteczność modelu na zbiorze testowym: 76.15%