Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • how to update the list of global macro within foreach loop?

    Hello,
    I am trying to run the code below, and my ultimate goal is to draw the scatter plot of the macros AUC vs. Alpha.
    The AUC seem to be okay, but when I do ' list Alpha ' after running my code, the every value stored under the macro Alpha is 5, where as I want Alpha to be the list of same values used for `a1' (foreach a1 of numlist 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.5 5.0)

    How can I resolve this issue? I am new to Stata so I have lots of questions.

    Thank you,

    STATA Code:

    gen Alpha = .
    gen AUC = .
    local i = 1

    foreach a1 of numlist 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.5 5.0 {

    python: a = float(Macro.getLocal("a1"))

    // predict using the best value for alpha
    python: mnb = MultinomialNB(alpha = a, class_prior = None, fit_prior = True)

    // calculate probability of each class on the test set
    // '[:, 1]' at the end extracts the probability for each pharmacy to be under compliance
    python: Y_mnb_score = mnb.fit(X_train, np.ravel(Y_train)).predict_proba(X_test)[:, 1]

    // make test_compliance python variable
    python: test_compliance = Y_test['compliance']

    // transfer the python variables Y_mnb_score and test_compliance as global STATA variables
    python: Data.setObsTotal(len(Y_mnb_score))
    python: Data.addVarFloat('mnbScore')
    python: Data.store(var = 'mnbScore', obs = None, val = Y_mnb_score)

    python: Data.setObsTotal(len(test_compliance))
    python: Data.addVarFloat('testCompliance')
    python: Data.store(var = 'testCompliance', obs = None, val = test_compliance)


    roctab testCompliance mnbScore
    replace AUC = r(area) in `i'
    replace Alpha = `a1' // this line is causing a problem

    drop testCompliance mnbScore
    local i = `++i'

    }

    scatter AUC Alpha xline(bestAlpha, lcolor(blue)) //ultimate goal

  • #2
    Code:
    replace AUC = r(area) in `i'
    worked for your AUC variable, because each time it is run, it replaces the value of AUC only in one observation. That suggests that the very similar command
    Code:
    replace Alpha = `a1'
    is not working because each time it is run, it replaces the value of Alpha in every observation. Try
    Code:
    replace Alpha = `a1' in `i'

    Comment


    • #3
      Thank you!

      Comment

      Working...
      X