Logistic Regression: Ignore cases with missing dependent variables.
[pspp] / src / language / stats / logistic.c
index 7171563032e396b37ec2a83df8bf94fd6c15a347..2c214516b711dc05d79e2bff025053871a1e1c0e 100644 (file)
@@ -135,7 +135,8 @@ struct lr_spec
   /* What results should be presented */
   unsigned int print;
 
-  double cut_point;
+  /* Inverse logit of the cut point */
+  double ilogit_cut_point;
 };
 
 
@@ -172,6 +173,10 @@ struct lr_result
 
   /* The estimates of the predictor coefficients */
   gsl_vector *beta_hat;
+
+  /* The predicted classifications: 
+     True Negative, True Positive, False Negative, False Positive */
+  double tn, tp, fn, fp;
 };
 
 
@@ -197,6 +202,7 @@ map_dependent_var (const struct lr_spec *cmd, const struct lr_result *res, const
   return SYSMIS;
 }
 
+static void output_classification_table (const struct lr_spec *cmd, const struct lr_result *res);
 
 static void output_categories (const struct lr_spec *cmd, const struct lr_result *res);
 
@@ -328,7 +334,9 @@ hessian (const struct lr_spec *cmd,
    y is the vector of observed independent variables
    pi is the vector of estimates for y
 
-   As a side effect, the likelihood is stored in LIKELIHOOD
+   Side effects:
+     the likelihood is stored in LIKELIHOOD;
+     the predicted values are placed in the respective tn, fn, tp fp values in RES
 */
 static gsl_vector *
 xt_times_y_pi (const struct lr_spec *cmd,
@@ -336,16 +344,18 @@ xt_times_y_pi (const struct lr_spec *cmd,
               struct casereader *input,
               const struct variable **x, size_t n_x,
               const struct variable *y_var,
-              double *likelihood)
+              double *llikelihood)
 {
   struct casereader *reader;
   struct ccase *c;
   gsl_vector *output = gsl_vector_calloc (res->beta_hat->size);
 
-  *likelihood = 1.0;
+  *llikelihood = 0.0;
+  res->tn = res->tp = res->fn = res->fp = 0;
   for (reader = casereader_clone (input);
        (c = casereader_read (reader)) != NULL; case_unref (c))
     {
+      double pred_y = 0;
       int v0;
       double pi = pi_hat (cmd, res, x, n_x, c);
       double weight = dict_get_case_weight (cmd->dict, c, &res->warn_bad_weight);
@@ -353,13 +363,31 @@ xt_times_y_pi (const struct lr_spec *cmd,
 
       double y = map_dependent_var (cmd, res, case_data (c, y_var));
 
-      *likelihood *= pow (pi, weight * y) * pow (1 - pi, weight * (1 - y));
+      *llikelihood += (weight * y) * log (pi) + log (1 - pi) * weight * (1 - y);
 
       for (v0 = 0; v0 < res->beta_hat->size; ++v0)
        {
          double in0 = predictor_value (c, x, n_x, res->cats, v0);
          double *o = gsl_vector_ptr (output, v0);
          *o += in0 * (y - pi) * weight;
+         pred_y += gsl_vector_get (res->beta_hat, v0) * in0;
+       }
+
+      /* Count the number of cases which would be correctly/incorrectly classified by this
+        estimated model */
+      if (pred_y <= cmd->ilogit_cut_point)
+       {
+         if (y == 0)
+           res->tn += weight;
+         else
+           res->fn += weight;
+       }
+      else
+       {
+         if (y == 0)
+           res->fp += weight;
+         else
+           res->tp += weight;
        }
     }
 
@@ -450,6 +478,11 @@ initial_pass (const struct lr_spec *cmd, struct lr_result *res, struct casereade
       double weight = dict_get_case_weight (cmd->dict, c, &res->warn_bad_weight);
       const union value *depval = case_data (c, cmd->dep_var);
 
+      if (var_is_value_missing (cmd->dep_var, depval, cmd->exclude))
+       {
+         missing = true;
+       }
+      else 
       for (v = 0; v < cmd->n_indep_vars; ++v)
        {
          const union value *val = case_data (c, cmd->indep_vars[v]);
@@ -550,10 +583,10 @@ run_lr (const struct lr_spec *cmd, struct casereader *input,
 
   bool converged = false;
 
-  /* Set the likelihoods to a negative sentinel value */
-  double likelihood = -1;
-  double prev_likelihood = -1;
-  double initial_likelihood = -1;
+  /* Set the log likelihoods to a sentinel value */
+  double log_likelihood = SYSMIS;
+  double prev_log_likelihood = SYSMIS;
+  double initial_log_likelihood = SYSMIS;
 
   struct lr_result work;
   work.n_missing = 0;
@@ -595,6 +628,12 @@ run_lr (const struct lr_spec *cmd, struct casereader *input,
                                            NULL,
                                            NULL);
 
+  input = casereader_create_filter_missing (input,
+                                           &cmd->dep_var,
+                                           1,
+                                           cmd->exclude,
+                                           NULL,
+                                           NULL);
 
   work.hessian = gsl_matrix_calloc (work.beta_hat->size, work.beta_hat->size);
 
@@ -615,7 +654,7 @@ run_lr (const struct lr_spec *cmd, struct casereader *input,
       v = xt_times_y_pi (cmd, &work, input,
                         cmd->predictor_vars, cmd->n_predictor_vars,
                         cmd->dep_var,
-                        &likelihood);
+                        &log_likelihood);
 
       {
        /* delta = M.v */
@@ -638,33 +677,34 @@ run_lr (const struct lr_spec *cmd, struct casereader *input,
        gsl_vector_free (delta);
       }
 
-      if ( prev_likelihood >= 0)
+      if (i > 0)
        {
-         if (-log (likelihood) > -(1.0 - cmd->lcon) * log (prev_likelihood))
+         if (-log_likelihood > -(1.0 - cmd->lcon) * prev_log_likelihood)
            {
              msg (MN, _("Estimation terminated at iteration number %d because Log Likelihood decreased by less than %g%%"), i + 1, 100 * cmd->lcon);
              converged = true;
            }
        }
       if (i == 0)
-       initial_likelihood = likelihood;
-      prev_likelihood = likelihood;
+       initial_log_likelihood = log_likelihood;
+      prev_log_likelihood = log_likelihood;
 
       if (converged)
        break;
     }
   casereader_destroy (input);
-  assert (initial_likelihood >= 0);
+
 
   if ( ! converged) 
     msg (MW, _("Estimation terminated at iteration number %d because maximum iterations has been reached"), i );
 
 
-  output_model_summary (&work, initial_likelihood, likelihood);
+  output_model_summary (&work, initial_log_likelihood, log_likelihood);
 
   if (work.cats)
     output_categories (cmd, &work);
 
+  output_classification_table (cmd, &work);
   output_variables (cmd, &work);
 
   gsl_matrix_free (work.hessian);
@@ -705,6 +745,7 @@ cmd_logistic (struct lexer *lexer, struct dataset *ds)
      These may or may not include the categorical predictors */
   const struct variable **pred_vars;
   size_t n_pred_vars;
+  double cp = 0.5;
 
   int v, x;
   struct lr_spec lr;
@@ -717,7 +758,6 @@ cmd_logistic (struct lexer *lexer, struct dataset *ds)
   lr.lcon = 0.0000;
   lr.bcon = 0.001;
   lr.min_epsilon = 0.00000001;
-  lr.cut_point = 0.5;
   lr.constant = true;
   lr.confidence = 95;
   lr.print = PRINT_DEFAULT;
@@ -928,6 +968,30 @@ cmd_logistic (struct lexer *lexer, struct dataset *ds)
                        }
                    }
                }
+             else if (lex_match_id (lexer, "CUT"))
+               {
+                 if (lex_force_match (lexer, T_LPAREN))
+                   {
+                     if (! lex_force_num (lexer))
+                       {
+                         lex_error (lexer, NULL);
+                         goto error;
+                       }
+                     cp = lex_number (lexer);
+                     
+                     if (cp < 0 || cp > 1.0)
+                       {
+                         msg (ME, _("Cut point value must be in the range [0,1]"));
+                         goto error;
+                       }
+                     lex_get (lexer);
+                     if ( ! lex_force_match (lexer, T_RPAREN))
+                       {
+                         lex_error (lexer, NULL);
+                         goto error;
+                       }
+                   }
+               }
              else
                {
                  lex_error (lexer, NULL);
@@ -942,11 +1006,13 @@ cmd_logistic (struct lexer *lexer, struct dataset *ds)
        }
     }
 
+  lr.ilogit_cut_point = - log (1/cp - 1);
+  
+
   /* Copy the predictor variables from the temporary location into the 
      final one, dropping any categorical variables which appear there.
      FIXME: This is O(NxM).
   */
-
   {
   struct variable_node *vn, *next;
   struct hmap allvars;
@@ -1234,10 +1300,14 @@ output_variables (const struct lr_spec *cmd,
 
       if (cmd->print & PRINT_CI)
        {
+         int last_ci = nr;
          double wc = gsl_cdf_ugaussian_Pinv (0.5 + cmd->confidence / 200.0);
          wc *= sqrt (sigma2);
 
-         if (idx < cmd->n_predictor_vars)
+         if (cmd->constant)
+           last_ci--;
+
+         if (row < last_ci)
            {
              tab_double (t, 8, row, 0, exp (b - wc), 0);
              tab_double (t, 9, row, 0, exp (b + wc), 0);
@@ -1252,7 +1322,7 @@ output_variables (const struct lr_spec *cmd,
 /* Show the model summary box */
 static void
 output_model_summary (const struct lr_result *res,
-                     double initial_likelihood, double likelihood)
+                     double initial_log_likelihood, double log_likelihood)
 {
   const int heading_columns = 0;
   const int heading_rows = 1;
@@ -1274,15 +1344,15 @@ output_model_summary (const struct lr_result *res,
 
   tab_text (t,  0, 0, TAB_LEFT | TAT_TITLE, _("Step 1"));
   tab_text (t,  1, 0, TAB_CENTER | TAT_TITLE, _("-2 Log likelihood"));
-  tab_double (t,  1, 1, 0, -2 * log (likelihood), 0);
+  tab_double (t,  1, 1, 0, -2 * log_likelihood, 0);
 
 
   tab_text (t,  2, 0, TAB_CENTER | TAT_TITLE, _("Cox & Snell R Square"));
-  cox =  1.0 - pow (initial_likelihood /likelihood, 2 / res->cc);
+  cox =  1.0 - exp((initial_log_likelihood - log_likelihood) * (2 / res->cc));
   tab_double (t,  2, 1, 0, cox, 0);
 
   tab_text (t,  3, 0, TAB_CENTER | TAT_TITLE, _("Nagelkerke R Square"));
-  tab_double (t,  3, 1, 0, cox / ( 1.0 - pow (initial_likelihood, 2 / res->cc)), 0);
+  tab_double (t,  3, 1, 0, cox / ( 1.0 - exp(initial_log_likelihood * (2 / res->cc))), 0);
 
 
   tab_submit (t);
@@ -1436,3 +1506,86 @@ output_categories (const struct lr_spec *cmd, const struct lr_result *res)
   tab_submit (t);
 
 }
+
+
+static void 
+output_classification_table (const struct lr_spec *cmd, const struct lr_result *res)
+{
+  const struct fmt_spec *wfmt =
+    cmd->wv ? var_get_print_format (cmd->wv) : &F_8_0;
+
+  const int heading_columns = 3;
+  const int heading_rows = 3;
+
+  struct string sv0, sv1;
+
+  const int nc = heading_columns + 3;
+  const int nr = heading_rows + 3;
+
+  struct tab_table *t = tab_create (nc, nr);
+
+  ds_init_empty (&sv0);
+  ds_init_empty (&sv1);
+
+  tab_title (t, _("Classification Table"));
+
+  tab_headers (t, heading_columns, 0, heading_rows, 0);
+
+  tab_box (t, TAL_2, TAL_2, -1, -1, 0, 0, nc - 1, nr - 1);
+  tab_box (t, -1, -1, -1, TAL_1, heading_columns, 0, nc - 1, nr - 1);
+
+  tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
+  tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
+
+  tab_text (t,  0, heading_rows, TAB_CENTER | TAT_TITLE, _("Step 1"));
+
+
+  tab_joint_text (t, heading_columns, 0, nc - 1, 0,
+                 TAB_CENTER | TAT_TITLE, _("Predicted"));
+
+  tab_joint_text (t, heading_columns, 1, heading_columns + 1, 1, 
+                 0, var_to_string (cmd->dep_var) );
+
+  tab_joint_text (t, 1, 2, 2, 2,
+                 TAB_LEFT | TAT_TITLE, _("Observed"));
+
+  tab_text (t, 1, 3, TAB_LEFT, var_to_string (cmd->dep_var) );
+
+
+  tab_joint_text (t, nc - 1, 1, nc - 1, 2,
+                 TAB_CENTER | TAT_TITLE, _("Percentage\nCorrect"));
+
+
+  tab_joint_text (t, 1, nr - 1, 2, nr - 1,
+                 TAB_LEFT | TAT_TITLE, _("Overall Percentage"));
+
+
+  tab_hline (t, TAL_1, 1, nc - 1, nr - 1);
+
+  var_append_value_name (cmd->dep_var, &res->y0, &sv0);
+  var_append_value_name (cmd->dep_var, &res->y1, &sv1);
+
+  tab_text (t, 2, heading_rows,     TAB_LEFT,  ds_cstr (&sv0));
+  tab_text (t, 2, heading_rows + 1, TAB_LEFT,  ds_cstr (&sv1));
+
+  tab_text (t, heading_columns,     2, 0,  ds_cstr (&sv0));
+  tab_text (t, heading_columns + 1, 2, 0,  ds_cstr (&sv1));
+
+  ds_destroy (&sv0);
+  ds_destroy (&sv1);
+
+  tab_double (t, heading_columns, 3,     0, res->tn, wfmt);
+  tab_double (t, heading_columns + 1, 4, 0, res->tp, wfmt);
+
+  tab_double (t, heading_columns + 1, 3, 0, res->fp, wfmt);
+  tab_double (t, heading_columns,     4, 0, res->fn, wfmt);
+
+  tab_double (t, heading_columns + 2, 3, 0, 100 * res->tn / (res->tn + res->fp), 0);
+  tab_double (t, heading_columns + 2, 4, 0, 100 * res->tp / (res->tp + res->fn), 0);
+
+  tab_double (t, heading_columns + 2, 5, 0, 
+             100 * (res->tp + res->tn) / (res->tp  + res->tn + res->fp + res->fn), 0);
+
+
+  tab_submit (t);
+}