388033 (1) [Avatar] Offline
#1
On page 25 of Grokking_Deep_Learning_v10_MEAP.pdf there is the following code:

weight = 0.1
def neural_network(input, weight):
prediction = input * weight
return prediction

number_of_toes = [8.5, 9.5, 10, 9]
input = number_of_toes[0]
pred = neural_network(input,weight) print(pred)

I was wondering why the weight variable is a global variable and also a parameter variable in the function named neural_network?
Ravi Annaswamy (7) [Avatar] Offline
#2
1. Even though weight is defined outside (just above) the function, in python no variable is global unless it is explicitly defined as:

global weight


2. In this snippet, the author is just defining a most minimalist network that takes input and weight as inputs to a function.
So technically you can understand the code by moving the weight=0.1 line *below* the function definition section, to just above the function call. (this is how python interpreter will look at the code and run it...)

 def neural_network(input, weight): 
      prediction = input * weight 
      return prediction 

 number_of_toes = [8.5, 9.5, 10, 9] 
 input = number_of_toes[0] 
 weight = 0.1 
 pred = neural_network(input,weight) print(pred) 

He is first defining the function. Then *independently* he sets an input and weight and calls the function by passing them in.

Does this make sense?

Ravi
Val (3) [Avatar] Offline
#3
Ravi Annaswamy wrote:1. Even though weight is defined outside (just above) the function, in python no variable is global unless it is explicitly defined as:
global weight


That's incorrect. Any object defined in the module's scope (i.e. the leftmost side of the file) is by definition global.
You are confusing this with the global keyword which is used inside inner scopes (like functions) to indicate the use of a global variable.

Here's an example:

books = 12

def print_books():
    print(books)  # prints 12


def print_books_2():
    global books  # tells Python we're referencing the global books variable
    books = books + 8  # modifies the global variable itself
    print(books)  # prints 20


def print_books_3(books):
    books = 55  # uses the local books variable/argument. Has no effect on the global books variable.
    global books  # will cause an error because we already have "books" defined in the function's scope.

Ravi Annaswamy (7) [Avatar] Offline
#4
Thank you I stand corrected on my point 1.

I think my point 2 is still valid (by moving weight statement down, you can understand
the intent of the code better.) Thoughts?
Val (3) [Avatar] Offline
#5
Yes, Ravi, your second point is correct and I think your solution is also more readable.
I think this needs to be fixed by the author since placing the declaration of weight before the
function definition (which has an argument with the same name) is confusing and feels out of place.

I suggest you open an errata so they can incorporate your fix. Well done smilie