1

I have a function LogReg, which is as follows: (using justmarkham's code as inspiration)

def LogReg(self):
      formulA = "class ~"
      print self.frame #dataframe used
      print self.columnNames[:-1]
      for a in self.columnNames[:-1]:
         formulA += " {0} +".format(a)
      formula = formulA[:-2] #there is always a \n behind, we don't want that
      print "formula = " + formula
      Y,X = dmatrices(formula, self.frame, return_type="dataframe")
      Y = np.ravel(Y) #flatten Y to a 1D list
      model = LogisticRegression() #from sklearn.linear_model
      model = model.fit(X, Y)
      print model.score(X, Y)

with the following outcome:

         a0 a1  a2  a3 class
picture1  1  2   3  67     1
picture2  6  7  45  61     3
picture3  8  7   6   5     2
picture4  1  2   4   3     0
['a0', 'a1', 'a2', 'a3']
formula = class ~ a0 + a1 + a2 + a3
Traceback (most recent call last):
  File "classification.py", line 80, in <module>
    c.LogReg()
  File "classification.py", line 61, in LogReg
    Y,X = dmatrices(formula, self.frame, return_type="dataframe")
  File "/<path>/python2.7/site-packages/patsy/highlevel.py", line 297, in dmatrices
    NA_action, return_type)
  File "/<path>/python2.7/site-packages/patsy/highlevel.py", line 152, in _do_highlevel_design
    NA_action)
  File "/<path>/python2.7/site-packages/patsy/highlevel.py", line 57, in _try_incr_builders
    NA_action)
  File "/<path>/python2.7/site-packages/patsy/build.py", line 660, in design_matrix_builders
    NA_action)
  File "/<path>/python2.7/site-packages/patsy/build.py", line 424, in _examine_factor_types
    value = factor.eval(factor_states[factor], data)
  File "/<path>/python2.7/site-packages/patsy/eval.py", line 485, in eval
    return self._eval(memorize_state["eval_code"], memorize_state, data)
  File "/<path>/python2.7/site-packages/patsy/eval.py", line 468, in _eval
    code, inner_namespace=inner_namespace)
  File "/<path>/python2.7/site-packages/patsy/compat.py", line 117, in call_and_wrap_exc
    return f(*args, **kwargs)
  File "/<path>/python2.7/site-packages/patsy/eval.py", line 125, in eval
    code = compile(expr, source_name, "eval", self.flags, False)
  File "<string>", line 1
    class
        ^
SyntaxError: unexpected EOF while parsing

I do not see what goes wrong here, as the string does by my knowledge not contain the EOF character, nor does the Python code seem erroneous. Therefore, the question: Where does it go wrong (and preferably: , and how to fix it)?

P.S.: The software used are all the most recent stable packages as available on 04/09/2015.

4

1 回答 1

2

嗯,那很快。通过问这个问题,我突然在代码中有颜色标记,通知我'class'是一个受保护的名称,不应该用作变量。Nano 不提供这些颜色,让我失明。

经验教训:孩子们,不要把课堂当作变量。

于 2015-04-12T11:11:49.103 回答