I am trying to make a use of the Python-Stata interface in Stata foreach loop. My loop is shown below:
Code:
foreach a1 of local alphaGrid { python: a = float(Macro.getLocal("a1")) // predict using the best value for alpha python: mnb = MultinomialNB(alpha = a, class_prior = None, fit_prior = True) // model Accuracy, how often is the MultinomialNB classifier correct? python: Y_mnb_pred = mnb.fit(X_train, np.ravel(Y_train)).predict(X.iloc[:, :-1]) // right now Y_mnb_best_pred is a numpy array; so change it into a list python: Y_mnb_pred = Y_mnb_pred.tolist() // transfer the python variable Y_mnb_best_pred as the Stata variable 'yBestPred' python: Data.setObsTotal(nobs) python: Data.addVarFloat('yPred') python: Data.store(var = 'yPred', obs = None, val = Y_mnb_pred) generate correct yPred == category tabulate correct summarize correct `accuracy' = r(mean) replace Accuracy = `accuracy' in `i' replace Alpha = `a1' in `i' // update the counter i local i = `++i' drop yPred }
I thought I would be fine with this since I am doing -drop yPred- at the end of the loop?
How can I fix this error?
Thank you,
0 Response to variable already defined error in the foreach loop
Post a Comment