0

I am creating a machine learning algorithm in python. Say I have:

alg = DecisionTreeClassifier(random_state=1)

then I create a function fit

def fit(X,Y,alg):
  alg.fit(X,Y)

and in my main I call

fit(X, Y, alg)
Y_pred = alg.predict(X_test)

Will this work? Or alg is never really changed outside fit?

I have read this question How do I pass a variable by reference? but it is confusing since I do not know how my variable alg is changed.

Thanks for your help.

Community
  • 1
  • 1
user
  • 2,015
  • 6
  • 22
  • 39

1 Answers1

4

Yes, the model object you pass to that function is mutable and is mutated by the fit method. Python's evaluation strategy is call-by-sharing, so the changes will be reflected in the caller.

Call by sharing (also referred to as call by object or call by object-sharing) is an evaluation strategy first named by Barbara Liskov et al. for the language CLU in 1974.[5] It is used by languages such as Python,[6] Iota,[7] Java (for object references), Ruby, JavaScript, Scheme, OCaml, AppleScript, and many others. However, the term "call by sharing" is not in common use; the terminology is inconsistent across different sources. For example, in the Java community, they say that Java is call by value. Call by sharing implies that values in the language are based on objects rather than primitive types, i.e. that all values are "boxed".

The semantics of call by sharing differ from call by reference in that assignments to function arguments within the function aren't visible to the caller (unlike by reference semantics)[citation needed], so e.g. if a variable was passed, it is not possible to simulate an assignment on that variable in the caller's scope. However, since the function has access to the same object as the caller (no copy is made), mutations to those objects, if the objects are mutable, within the function are visible to the caller, which may appear to differ from call by value semantics. Mutations of a mutable object within the function are visible to the caller because the object is not copied or cloned — it is shared.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172