Week2 Programming Assignment Ex 6: Optimise Function


In the Optimise Function of Logistic Regression assignment, there is a pre-written part of the code which is:
w = copy.deepcopy(w)
b = copy.deepcopy(b)

Since, I was unaware of this Pyhton method, I searched in python documentation and found out that the method w = copy.copy() creates a shallow copy while the method w = copy.deepcopy(w) creates a
deepcopy of w. I didn’t get the difference between the two from Python documentation. Can someone please explain it in a simpler way?

Python assignment, or shallow copy, doesn’t fully copy compound objects. Instead, it creates a new reference to the original. If you manipulate (mutate) the value of the new reference, the value of the original is changed, too. Deep copy makes an entirely new object, disconnected from its original. If you change the value of the deep copy, the value of the original remains unchanged.

import copy

a = [[4,5,6], [7,8,9]]
b = copy.copy(a)

print('a = ' + str(a))
print('b = ' + str(b))

a[0][0] = 1
print('a = ' + str(a))
print('b = ' + str(b))
#with a shallow copy, changing a[0][0] also changes b[0][0]

a = [[4, 5, 6], [7, 8, 9]]
b = [[4, 5, 6], [7, 8, 9]]
a = [[1, 5, 6], [7, 8, 9]]
b = [[1, 5, 6], [7, 8, 9]]

c = [[4,5,6], [7,8,9]]
d = copy.deepcopy(c)

print('c = ' + str(c))
print('d = ' + str(d))

c[0][0] = 1
print('c = ' + str(c))
print('d = ' + str(d))
#with a deep copy, changing c[0][0] does not change d[0][0]

c = [[4, 5, 6], [7, 8, 9]]
d = [[4, 5, 6], [7, 8, 9]]
c = [[1, 5, 6], [7, 8, 9]]
d = [[4, 5, 6], [7, 8, 9]]
2 Likes

And the reason the copy is done in the first place is that objects are passed “by reference” on function calls in python. So the w down in optimize is a reference to the same global w that was passed in, unless you do the copy to break that link. Having a subroutine modify global data is something you only want to do “on purpose”, not “by accident”. It would be a pretty nasty surprise if that’s not what you were intending.

Here’s a thread which discusses this general issue as it relates to the “update parameters” routines in Weeks 3 and 4.

2 Likes

Thanks for clarifying the doubt.

Thanks for helping !