Pagina 1 di 3

Problema con rete neurale BProp legge foto

MessaggioInviato: 24 mar 2025, 20:55
da alien75
Salve ho scaricato da internet una RNA BackPropagation che utilizzo per leggere 4 foto.
Codice: Seleziona tutto
import numpy as np
import cv2
import cv2 as cv
import sys


class NeuralNetwork:
    def __init__(self, input_size, hidden_size, output_size):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size

        self.weights_input_hidden = np.random.randn(self.input_size, self.hidden_size)
        self.weights_hidden_output = np.random.randn(self.hidden_size, self.output_size)

        self.bias_hidden = np.zeros((1, self.hidden_size))
        self.bias_output = np.zeros((1, self.output_size))

    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def sigmoid_derivative(self, x):
        return x * (1 - x)

    def feedforward(self, X):
        self.hidden_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
        self.hidden_output = self.sigmoid(self.hidden_activation)

        self.output_activation = np.dot(self.hidden_output, self.weights_hidden_output) + self.bias_output
        self.predicted_output = self.sigmoid(self.output_activation)

        return self.predicted_output

    def backward(self, X, y, learning_rate):
        output_error = y - self.predicted_output
        output_delta = output_error * self.sigmoid_derivative(self.predicted_output)

        hidden_error = np.dot(output_delta, self.weights_hidden_output.T)
        hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_output)

        self.weights_hidden_output += np.dot(self.hidden_output.T, output_delta) * learning_rate
        self.bias_output += np.sum(output_delta, axis=0, keepdims=True) * learning_rate
        self.weights_input_hidden += np.dot(X.T, hidden_delta) * learning_rate
        self.bias_hidden += np.sum(hidden_delta, axis=0, keepdims=True) * learning_rate

    def train(self, X, y, epochs, learning_rate):
        for epoch in range(epochs):
            output = self.feedforward(X)
            self.backward(X, y, learning_rate)
            if epoch % 4000 == 0:
                loss = np.mean(np.square(y - output))
                print(f"Epoch {epoch}, Loss:{loss}")

IMAGE1 = 'day_open.jpg'
IMAGE2 = 'day_closed.jpg'
IMAGE3 = 'night_open.jpg'
IMAGE4 = 'night_closed.jpg'

image1 = cv2.imread(IMAGE1)
image2 = cv2.imread(IMAGE2)
image3 = cv2.imread(IMAGE3)
image4 = cv2.imread(IMAGE4)


gray_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
res1 = cv.resize(gray_image1,(100, 100), interpolation = cv.INTER_CUBIC)
gray_image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
res2 = cv.resize(gray_image2,(100, 100), interpolation = cv.INTER_CUBIC)
gray_image3 = cv2.cvtColor(image3, cv2.COLOR_BGR2GRAY)
res3 = cv.resize(gray_image3,(100, 100), interpolation = cv.INTER_CUBIC)
gray_image4 = cv2.cvtColor(image4, cv2.COLOR_BGR2GRAY)
res4 = cv.resize(gray_image4,(100, 100), interpolation = cv.INTER_CUBIC)
res1 = res1 / 255
res2 = res2 / 255
res3 = res3 / 255
res4 = res4 / 255



X = np.array([[res1], [res2], [res3], [res4]])
y = np.array([[0,0], [0,1], [1,0], [1,1]])


nn = NeuralNetwork(input_size=10000, hidden_size=500, output_size=2)
nn.train(X, y, epochs=20000, learning_rate=1)

output = nn.feedforward(X)
print("Predictions after training:")
print(X)
print(output)


Mi succede che mi da errore con l'immagine ridimensionata a 10000 pixel.
Se invece imposto la rete a 2 ingressi con relativi array impostati su
nn = NeuralNetwork(input_size=2, hidden_size=500, output_size=2)
la RNA funziona normalmente.
perché se inserisco in ingresso i pixel delle immagini mi da problemi invece con due ingressi funziona?
Aiutatemi per favore.
Messaggio di errore:
Codice: Seleziona tutto
Traceback (most recent call last):
  File "/home/fabio/Scrivania/backpropagation.py", line 85, in <module>
    nn.train(X, y, epochs=20000, learning_rate=1)
  File "/home/fabio/Scrivania/backpropagation.py", line 48, in train
    output = self.feedforward(X)
  File "/home/fabio/Scrivania/backpropagation.py", line 26, in feedforward
    self.hidden_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
ValueError: shapes (4,1,100,100) and (10000,500) not aligned: 100 (dim 3) != 10000 (dim 0)

Re: Problema con rete neurale BProp legge foto

MessaggioInviato: 24 mar 2025, 22:57
da gvee
Non ho visto il codice ma dall'errore sembra che le dimensioni non coincidono..

Re: Problema con rete neurale BProp legge foto

MessaggioInviato: 25 mar 2025, 18:16
da alien75
Se osservi i parametri che ho messo nell' ultima parte del codice ho messo 10000 come unità di ingresso che coincidono con res1 = cv.resize(gray_image1,(100, 100), interpolation = cv.INTER_CUBIC) (100X100 pixel).
A casa mia 100x100 pixel corrispondono con 10000 ingressi quindi non capisco perché non coincidono secondo l'interprete.
Inizio a non capirci niente.
res1 è un array di 10000 pixel in scala di grigi quindi un unico canale non tre.

Re: Problema con rete neurale BProp legge foto

MessaggioInviato: 25 mar 2025, 20:11
da lelerelele
alien75 ha scritto:res1 è un array di 10000 pixel in scala di grigi quindi un unico canale non tre.


magari il formato del file foto può non essere corretto? bmp, jpg, png, ecc.
modalità colore, tavolozza?
anche la foto è in scala di grigi ad 8bit/pixel, 16bit, 32bit? il tuo res1 è un array a 8-16-32 bit?

le mie sono riflessioni non sapendo di cosa si tratta.

saluti.

Re: Problema con rete neurale BProp legge foto

MessaggioInviato: 25 mar 2025, 21:55
da gvee
La funzione size di numpy

https://numpy.org/doc/stable/reference/ ... .size.html

Che valori ritorna per ogni matrice/immagine?

Re: Problema con rete neurale BProp legge foto

MessaggioInviato: 26 mar 2025, 13:43
da alien75
Ritorna questi valori:
Codice: Seleziona tutto
[[[[0.25490196 0.25098039 0.24313725 ... 0.32941176 0.29019608
    0.18039216]
   [0.25882353 0.24313725 0.23921569 ... 0.31372549 0.16470588
    0.16862745]
   [0.24313725 0.25098039 0.2627451  ... 0.28627451 0.15294118
    0.14901961]
   ...
   [0.67843137 0.6745098  0.68235294 ... 0.42745098 0.47058824
    0.75686275]
   [0.6745098  0.6627451  0.65490196 ... 0.45882353 0.90980392
    0.9254902 ]
   [0.60784314 0.61960784 0.61960784 ... 0.39607843 0.91372549
    0.93333333]]]


[[[0.41960784 0.40392157 0.42352941 ... 0.63137255 0.63529412
    0.66666667]
   [0.44705882 0.42352941 0.41568627 ... 0.64705882 0.63529412
    0.64313725]
   [0.45098039 0.41960784 0.43921569 ... 0.64705882 0.64313725
    0.65490196]
   ...
   [0.70196078 0.70980392 0.7254902  ... 0.38431373 0.37647059
    0.35686275]
   [0.70196078 0.69019608 0.70980392 ... 0.34901961 0.36078431
    0.36078431]
   [0.69411765 0.70588235 0.70588235 ... 0.38431373 0.39215686
    0.37647059]]]


[[[0.04705882 0.03529412 0.05490196 ... 0.0627451  0.07058824
    0.30196078]
   [0.05490196 0.02352941 0.03137255 ... 0.06666667 0.13333333
    0.3254902 ]
   [0.03529412 0.03529412 0.05490196 ... 0.05098039 0.18823529
    0.31764706]
   ...
   [0.03137255 0.04313725 0.03921569 ... 0.00784314 0.00784314
    0.03529412]
   [0.01568627 0.02352941 0.02745098 ... 0.01568627 0.01568627
    0.00784314]
   [0.01960784 0.02745098 0.03137255 ... 0.01960784 0.00784314
    0.02352941]]]


[[[0.19607843 0.19607843 0.19215686 ... 0.07843137 0.0745098
    0.08235294]
   [0.21176471 0.19215686 0.21176471 ... 0.0745098  0.07058824
    0.0745098 ]
   [0.21568627 0.21176471 0.21568627 ... 0.08235294 0.10196078
    0.09411765]
   ...
   [0.05098039 0.05490196 0.03921569 ... 0.00784314 0.01960784
    0.01960784]
   [0.02745098 0.05098039 0.04705882 ... 0.01568627 0.01960784
    0.01960784]
   [0.03921569 0.02745098 0.03137255 ... 0.01960784 0.01568627
    0.00392157]]]]


Tutti valori da 0 a 1 float.
Forse non accetta float ma non credo sia quello il proiblema.

Poi do:
Codice: Seleziona tutto
len(res1)


e mi da:
Codice: Seleziona tutto
Traceback (most recent call last):
  File "/home/fabio/Scrivania/backpropagation.py", line 85, in <module>
    nn.train(X, y, epochs=20000, learning_rate=1)
  File "/home/fabio/Scrivania/backpropagation.py", line 48, in train
    output = self.feedforward(X)
  File "/home/fabio/Scrivania/backpropagation.py", line 26, in feedforward
    self.hidden_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
ValueError: shapes (4,1,100,100) and (10000,500) not aligned: 100 (dim 3) != 10000 (dim 0)


Non mi da la lunghezza di res1, riporto tutto il codice:
Codice: Seleziona tutto
import numpy as np
import cv2
import cv2 as cv
import sys


class NeuralNetwork:
    def __init__(self, input_size, hidden_size, output_size):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size

        self.weights_input_hidden = np.random.randn(self.input_size, self.hidden_size)
        self.weights_hidden_output = np.random.randn(self.hidden_size, self.output_size)

        self.bias_hidden = np.zeros((1, self.hidden_size))
        self.bias_output = np.zeros((1, self.output_size))
       
    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def sigmoid_derivative(self, x):
        return x * (1 - x)

    def feedforward(self, X):
        self.hidden_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
        self.hidden_output = self.sigmoid(self.hidden_activation)

        self.output_activation = np.dot(self.hidden_output, self.weights_hidden_output) + self.bias_output
        self.predicted_output = self.sigmoid(self.output_activation)

        return self.predicted_output

    def backward(self, X, y, learning_rate):
        output_error = y - self.predicted_output
        output_delta = output_error * self.sigmoid_derivative(self.predicted_output)

        hidden_error = np.dot(output_delta, self.weights_hidden_output.T)
        hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_output)

        self.weights_hidden_output += np.dot(self.hidden_output.T, output_delta) * learning_rate
        self.bias_output += np.sum(output_delta, axis=0, keepdims=True) * learning_rate
        self.weights_input_hidden += np.dot(X.T, hidden_delta) * learning_rate
        self.bias_hidden += np.sum(hidden_delta, axis=0, keepdims=True) * learning_rate

    def train(self, X, y, epochs, learning_rate):
        for epoch in range(epochs):
            output = self.feedforward(X)
            self.backward(X, y, learning_rate)
            if epoch % 4000 == 0:
                loss = np.mean(np.square(y - output))
                print(f"Epoch {epoch}, Loss:{loss}")

IMAGE1 = 'day_open.jpg'
IMAGE2 = 'day_closed.jpg'
IMAGE3 = 'night_open.jpg'
IMAGE4 = 'night_closed.jpg'

image1 = cv2.imread(IMAGE1)
image2 = cv2.imread(IMAGE2)
image3 = cv2.imread(IMAGE3)
image4 = cv2.imread(IMAGE4)


gray_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
res1 = cv.resize(gray_image1,(100, 100), interpolation = cv.INTER_CUBIC)
gray_image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
res2 = cv.resize(gray_image2,(100, 100), interpolation = cv.INTER_CUBIC)
gray_image3 = cv2.cvtColor(image3, cv2.COLOR_BGR2GRAY)
res3 = cv.resize(gray_image3,(100, 100), interpolation = cv.INTER_CUBIC)
gray_image4 = cv2.cvtColor(image4, cv2.COLOR_BGR2GRAY)
res4 = cv.resize(gray_image4,(100, 100), interpolation = cv.INTER_CUBIC)
res1 = res1 / 255
res2 = res2 / 255
res3 = res3 / 255
res4 = res4 / 255

len(res1)
X = np.array([[res1], [res2], [res3], [res4]])
y = np.array([[0,0], [0,1], [1,0], [1,1]])



nn = NeuralNetwork(input_size=10000, hidden_size=500, output_size=2)
nn.train(X, y, epochs=20000, learning_rate=1)
output = nn.feedforward(X)
print("Predictions after training:")

Re: Problema con rete neurale BProp legge foto

MessaggioInviato: 26 mar 2025, 14:29
da gvee
Allora non è quella la funzione da usare che pensavo io, prova con la funzione cv.shape:

https://www.tutorialkart.com/opencv/pyt ... mage-size/

Re: Problema con rete neurale BProp legge foto

MessaggioInviato: 26 mar 2025, 16:36
da GioArca67
Se al posto di
Codice: Seleziona tutto
nn.train(X, y, epochs=20000, learning_rate=1)

metti
Codice: Seleziona tutto
nn.train(res1, [0,0], epochs=20000, learning_rate=1)

che errore ti da?

Re: Problema con rete neurale BProp legge foto

MessaggioInviato: 26 mar 2025, 18:29
da alien75
gvee ha scritto:Allora non è quella la funzione da usare che pensavo io, prova con la funzione cv.shape:

https://www.tutorialkart.com/opencv/pyt ... mage-size/


codice completo:
Codice: Seleziona tutto
import numpy as np
import cv2
import cv2 as cv
import sys


class NeuralNetwork:
    def __init__(self, input_size, hidden_size, output_size):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size

        self.weights_input_hidden = np.random.randn(self.input_size, self.hidden_size)
        self.weights_hidden_output = np.random.randn(self.hidden_size, self.output_size)

        self.bias_hidden = np.zeros((1, self.hidden_size))
        self.bias_output = np.zeros((1, self.output_size))
       
    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def sigmoid_derivative(self, x):
        return x * (1 - x)

    def feedforward(self, X):
        self.hidden_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
        self.hidden_output = self.sigmoid(self.hidden_activation)

        self.output_activation = np.dot(self.hidden_output, self.weights_hidden_output) + self.bias_output
        self.predicted_output = self.sigmoid(self.output_activation)

        return self.predicted_output

    def backward(self, X, y, learning_rate):
        output_error = y - self.predicted_output
        output_delta = output_error * self.sigmoid_derivative(self.predicted_output)

        hidden_error = np.dot(output_delta, self.weights_hidden_output.T)
        hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_output)

        self.weights_hidden_output += np.dot(self.hidden_output.T, output_delta) * learning_rate
        self.bias_output += np.sum(output_delta, axis=0, keepdims=True) * learning_rate
        self.weights_input_hidden += np.dot(X.T, hidden_delta) * learning_rate
        self.bias_hidden += np.sum(hidden_delta, axis=0, keepdims=True) * learning_rate

    def train(self, X, y, epochs, learning_rate):
        for epoch in range(epochs):
            output = self.feedforward(X)
            self.backward(X, y, learning_rate)
            if epoch % 4000 == 0:
                loss = np.mean(np.square(y - output))
                print(f"Epoch {epoch}, Loss:{loss}")

IMAGE1 = 'day_open.jpg'
IMAGE2 = 'day_closed.jpg'
IMAGE3 = 'night_open.jpg'
IMAGE4 = 'night_closed.jpg'

image1 = cv2.imread(IMAGE1)
image2 = cv2.imread(IMAGE2)
image3 = cv2.imread(IMAGE3)
image4 = cv2.imread(IMAGE4)


gray_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
res1 = cv.resize(gray_image1,(100, 100), interpolation = cv.INTER_CUBIC)
gray_image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
res2 = cv.resize(gray_image2,(100, 100), interpolation = cv.INTER_CUBIC)
gray_image3 = cv2.cvtColor(image3, cv2.COLOR_BGR2GRAY)
res3 = cv.resize(gray_image3,(100, 100), interpolation = cv.INTER_CUBIC)
gray_image4 = cv2.cvtColor(image4, cv2.COLOR_BGR2GRAY)
res4 = cv.resize(gray_image4,(100, 100), interpolation = cv.INTER_CUBIC)
res1 = res1 / 255
res2 = res2 / 255
res3 = res3 / 255
res4 = res4 / 255

print(res1.shape)

X = np.array([[res1], [res2], [res3], [res4]])
y= np.array([[0,0], [0,1], [1,0], [1,1]])
print(len(X))


nn = NeuralNetwork(input_size=10000, hidden_size=500, output_size=2)
nn.train(res1[0,0], y, epochs=20000, learning_rate=1)
output = nn.feedforward(X)
print("Predictions after training:")


risultato:
Codice: Seleziona tutto
(100, 100)
4
Traceback (most recent call last):
  File "/home/fabio/Scrivania/backpropagation.py", line 86, in <module>
    nn.train(res1[0,0], y, epochs=20000, learning_rate=1)
  File "/home/fabio/Scrivania/backpropagation.py", line 49, in train
    self.backward(X, y, learning_rate)
  File "/home/fabio/Scrivania/backpropagation.py", line 35, in backward
    output_error = y - self.predicted_output
ValueError: operands could not be broadcast together with shapes (4,2) (10000,2)

Re: Problema con rete neurale BProp legge foto

MessaggioInviato: 26 mar 2025, 18:33
da alien75
GioArca67 ha scritto:Se al posto di
Codice: Seleziona tutto
nn.train(X, y, epochs=20000, learning_rate=1)

metti
Codice: Seleziona tutto
nn.train(res1, [0,0], epochs=20000, learning_rate=1)

che errore ti da?


Codice: Seleziona tutto
nn.train(res1, [0,0], epochs=20000, learning_rate=1)


errore:
Codice: Seleziona tutto
(100, 100)
4
Traceback (most recent call last):
  File "/home/fabio/Scrivania/backpropagation.py", line 86, in <module>
    nn.train(res1, [0,0], epochs=20000, learning_rate=1)
  File "/home/fabio/Scrivania/backpropagation.py", line 48, in train
    output = self.feedforward(X)
  File "/home/fabio/Scrivania/backpropagation.py", line 26, in feedforward
    self.hidden_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
ValueError: shapes (100,100) and (10000,500) not aligned: 100 (dim 1) != 10000 (dim 0)


perché mi da tale errore?

So che il python vede l'immagine res1 fatta da 100 valori e non 10000 e non capisco il perché, il problema non è dell RNA ma d icv.resize() che la dimensiona a 100 e non 10000.
E' questo il problema secondo me: quindi se do in "pasto" alla rete 100 elementi a 10000 ingressi il python si incazza e mi chiede perché gli do solo 100 quando gli input sono 10000.
Il problema secondo me è solo questo.

Con questo codice:
Codice: Seleziona tutto
print(res1.shape)

X = np.array([[res1], [res2], [res3], [res4]])
y= np.array([[0,0], [0,1], [1,0], [1,1]])



nn = NeuralNetwork(input_size=10000, hidden_size=500, output_size=2)
nn.train(res1, y[0], epochs=20000, learning_rate=1)
output = nn.feedforward(X[0])
print("Predictions after training:")


ho questo errore alla riga 26:
Codice: Seleziona tutto
File "/home/fabio/Scrivania/backpropagation.py", line 26, in feedforward
    self.hidden_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
ValueError: shapes (100,100) and (10000,500) not aligned: 100 (dim 1) != 10000 (


lui sostanzialmente mi dice "guarda che un'immagine da 100 elemnti è diversa da un input da 10000" quindi la mia intuizione era giusta-
Non so però come impostare res1--4 a 10000, questo è il dunque.