Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

variables changing after a function call in python

Ive been working on some code recently for a project in python and im confused by the output im getting from this code

def sigmoid(input_matrix):
    rows = input_matrix.shape[0]
    columns = input_matrix.shape[1]
    for i in range(0,rows):
        for j in range(0,columns):
            input_matrix[i,j] = (1 / (1 + math.exp(-(input_matrix[i,j]))))
    return input_matrix

def feed_forward(W_L_1 , A_L_0 , B_L_1):
    weighted_sum = np.add(np.dot(W_L_1,A_L_0), B_L_1)
    activation = sigmoid(weighted_sum)
    return [weighted_sum,activation]

a = np.zeros((1,1))
b = feed_forward(a,a,a)
print(b[0])
print(b[1])

when I print both b[0] and b[1] give values of .5 even though b[0] should equal 0. Also in addition to this when I place the '''weighted_sum = np.add(np.dot(W_L_1,A_L_0), B_L_1)''' again after the 'actvation' line it provides the correct result. Its as if the 'activation' line has changed the value of the weighted sum value. Was wondering if anyone could spread some light on this I can work around this but am interested as to why this is happening. Thanks!!

question from:https://stackoverflow.com/questions/65848733/variables-changing-after-a-function-call-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Inside sigmoid, you're changing the value of the matrix passed as parameter, in this line:

input_matrix[i,j] = ...

If you want to prevent this from happening, create a copy of the matrix before calling sigmoid, and call it like this: sigmoid(copy_of_weighted_sum).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...