Cos'è ElectroYou | Login Iscriviti

ElectroYou - la comunità dei professionisti del mondo elettrico

Problema con rete neurale BProp legge foto

Linguaggi e sistemi

Moderatori: Foto UtentePaolino, Foto Utentefairyvilje

0
voti

[1] Problema con rete neurale BProp legge foto

Messaggioda Foto Utentealien75 » 24 mar 2025, 20:55

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)
Avatar utente
Foto Utentealien75
1 1 4 8
Sostenitore
Sostenitore
 
Messaggi: 588
Iscritto il: 31 lug 2011, 14:08

0
voti

[2] Re: Problema con rete neurale BProp legge foto

Messaggioda Foto Utentegvee » 24 mar 2025, 22:57

Non ho visto il codice ma dall'errore sembra che le dimensioni non coincidono..
Avatar utente
Foto Utentegvee
1.475 5 7
Sostenitore
Sostenitore
 
Messaggi: 525
Iscritto il: 11 feb 2018, 20:34

0
voti

[3] Re: Problema con rete neurale BProp legge foto

Messaggioda Foto Utentealien75 » 25 mar 2025, 18:16

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.
Avatar utente
Foto Utentealien75
1 1 4 8
Sostenitore
Sostenitore
 
Messaggi: 588
Iscritto il: 31 lug 2011, 14:08

0
voti

[4] Re: Problema con rete neurale BProp legge foto

Messaggioda Foto Utentelelerelele » 25 mar 2025, 20:11

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.
Avatar utente
Foto Utentelelerelele
4.899 3 7 9
Master
Master
 
Messaggi: 5505
Iscritto il: 8 giu 2011, 8:57
Località: Reggio Emilia

0
voti

[5] Re: Problema con rete neurale BProp legge foto

Messaggioda Foto Utentegvee » 25 mar 2025, 21:55

La funzione size di numpy

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

Che valori ritorna per ogni matrice/immagine?
Avatar utente
Foto Utentegvee
1.475 5 7
Sostenitore
Sostenitore
 
Messaggi: 525
Iscritto il: 11 feb 2018, 20:34

0
voti

[6] Re: Problema con rete neurale BProp legge foto

Messaggioda Foto Utentealien75 » 26 mar 2025, 13:43

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:")
Avatar utente
Foto Utentealien75
1 1 4 8
Sostenitore
Sostenitore
 
Messaggi: 588
Iscritto il: 31 lug 2011, 14:08

0
voti

[7] Re: Problema con rete neurale BProp legge foto

Messaggioda Foto Utentegvee » 26 mar 2025, 14:29

Allora non è quella la funzione da usare che pensavo io, prova con la funzione cv.shape:

https://www.tutorialkart.com/opencv/pyt ... mage-size/
Avatar utente
Foto Utentegvee
1.475 5 7
Sostenitore
Sostenitore
 
Messaggi: 525
Iscritto il: 11 feb 2018, 20:34

0
voti

[8] Re: Problema con rete neurale BProp legge foto

Messaggioda Foto UtenteGioArca67 » 26 mar 2025, 16:36

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?
Avatar utente
Foto UtenteGioArca67
4.565 4 6 9
Master EY
Master EY
 
Messaggi: 4589
Iscritto il: 12 mar 2021, 9:36

0
voti

[9] Re: Problema con rete neurale BProp legge foto

Messaggioda Foto Utentealien75 » 26 mar 2025, 18:29

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)
Avatar utente
Foto Utentealien75
1 1 4 8
Sostenitore
Sostenitore
 
Messaggi: 588
Iscritto il: 31 lug 2011, 14:08

0
voti

[10] Re: Problema con rete neurale BProp legge foto

Messaggioda Foto Utentealien75 » 26 mar 2025, 18:33

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.
Avatar utente
Foto Utentealien75
1 1 4 8
Sostenitore
Sostenitore
 
Messaggi: 588
Iscritto il: 31 lug 2011, 14:08

Prossimo

Torna a PC e informatica

Chi c’è in linea

Visitano il forum: Nessuno e 20 ospiti