computes f1, precision and recall on the entity class
346322
def classifer_metrics(label, pred):
    
    prediction = np.argmax(pred, axis=1)
    label = label.astype(int)

    pred_is_entity = prediction != not_entity_index
    label_is_entity = label != not_entity_index

    corr_pred = (prediction == label) == (pred_is_entity == True)

    #how many entities are there?
    num_entities = np.sum(label_is_entity)
    entity_preds = np.sum(pred_is_entity)

    #how many times did we correctly predict an entity?
    correct_entitites = np.sum(corr_pred[pred_is_entity])

    #precision: when we predict entity, how often are we right?
    precision = correct_entitites/entity_preds
    if entity_preds == 0:
        precision = np.nan

    #recall: of the things that were an entity, how many did we catch?
    recall = correct_entitites / num_entities
    if num_entities == 0:
        recall = np.nan
    f1 = 2 * precision * recall / (precision + recall)
    return precision, recall, f1
1250010
def _f_gen(self, c):
        
        lf_idx = self.candidate_classes.index(c.__class__)
        labels = lambda c: [(c.id, lf.__name__, lf(c)) for lf in self.lfs[lf_idx]]
        for cid, lf_key, label in labels(c):
            # Note: We assume if the LF output is an int, it is already
            # mapped correctly
            if isinstance(label, int):
                yield cid, lf_key, label
            # None is a protected LF output value corresponding to 0,
            # representing LF abstaining
            elif label is None:
                yield cid, lf_key, 0
            elif label in c.values:
                if c.cardinality > 2:
                    yield cid, lf_key, c.values.index(label) + 1
                # Note: Would be nice to not special-case here, but for
                # consistency we leave binary LF range as {-1,0,1}
                else:
                    val = 1 if c.values.index(label) == 0 else -1
                    yield cid, lf_key, val
            else:
                raise ValueError(
                    f"Can't parse label value {label} for candidate values {c.values}"
                )
605461
private static int precision(long hi, long lo){
        if(hi==0) {
            if(lo>=0) {
                return longDigitLength(lo);
            }
            return (unsignedLongCompareEq(lo, LONGLONG_TEN_POWERS_TABLE[0][1])) ? 20 : 19;
            // 0x8AC7230489E80000L  = unsigned 2^19
        }
        int r = ((128 - Long.numberOfLeadingZeros(hi) + 1) * 1233) >>> 12;
        int idx = r-19;
        return (idx >= LONGLONG_TEN_POWERS_TABLE.length || longLongCompareMagnitude(hi, lo,
                                                                                    LONGLONG_TEN_POWERS_TABLE[idx][0], LONGLONG_TEN_POWERS_TABLE[idx][1])) ? r : r + 1;
    }
217392
def precision_recall(self):
        
        return plot.precision_recall(self.y_true, self.y_score, ax=_gen_ax())
148661
function(sRole, aAssociation, aAssociationSet, bFrom) {
					var sEntitySet = jQuery(aAssociationSet).find("End[Role='" + sRole + "']").attr("EntitySet");
					var sMultiplicity = jQuery(aAssociation).find("End[Role='" + sRole + "']").attr("Multiplicity");

					var aPropRef = [];
					var aConstraint = jQuery(aAssociation).find("ReferentialConstraint > [Role='" + sRole + "']");
					if (aConstraint && aConstraint.length > 0) {
						jQuery(aConstraint[0]).children("PropertyRef").each(function(iIndex, oPropRef) {
							aPropRef.push(jQuery(oPropRef).attr("Name"));
						});
					} else {
						var oPrinDeps = (bFrom) ? oPrincipals : oDependents;
						jQuery(oPrinDeps).each(function(iIndex, oPrinDep) {
							if (sRole === (jQuery(oPrinDep).attr("Role"))) {
								jQuery(oPrinDep).children("PropertyRef").each(function(iIndex, oPropRef) {
									aPropRef.push(jQuery(oPropRef).attr("Name"));
								});
								return false;
							}
						});
					}

					return {
						"role": sRole,
						"entitySet": sEntitySet,
						"propRef": aPropRef,
						"multiplicity": sMultiplicity
					};
				}
296245
def characterize(cls, record):
        
        classes = list(cls.__subclasses__())
        if not isabstract(cls):
            classes.append(cls)
        for subclass in classes:
            entity = subclass(record)
            if entity.is_valid():
                return entity
        raise RuntimeError("could not find the type for '{}'".format(record.id))
1214594
def _parse_entities(self):
        
        entities = list()

        for result in self._data:
            entity = dict()
            char_fragment = result.get('charFragment')
            start = char_fragment.get('start')
            end = char_fragment.get('end')
            entity['start'] = start
            entity['end'] = end
            entity['text'] = self._text[start: end+1]
            if sys.version < '3' and isinstance(entity['text'], str):
                entity['text'] = entity['test'].decode('utf-8')
            entity['isEntity'] = True
            for key, value in result.items():
                entity[key] = value
            entities.append(entity)
        self._entities = entities
532968
def _get_value(self, entity):
    """"""
    value = super(_ClassKeyProperty, self)._get_value(entity)
    if not value:
      value = entity._class_key()
      self._store_value(entity, value)
    return value
1249747
private void process() {
    Entity entity = entityClass.getAnnotation(Entity.class);
    ProjectedEntity projectedEntity = entityClass.getAnnotation(ProjectedEntity.class);
    if (entity != null) {
      initEntityMetadata(entity);
    } else if (projectedEntity != null) {
      initEntityMetadata(projectedEntity);
    } else {
      String message = String.format("Class %s must either have %s or %s annotation",
          entityClass.getName(), Entity.class.getName(), ProjectedEntity.class.getName());
      throw new EntityManagerException(message);
    }

    processPropertyOverrides();

    processFields();
    // If we did not find valid Identifier...
    if (entityMetadata.getIdentifierMetadata() == null) {
      throw new EntityManagerException(
          String.format("Class %s requires a field with annotation of %s", entityClass.getName(),
              Identifier.class.getName()));
    }
    entityMetadata.setEntityListenersMetadata(EntityListenersIntrospector.introspect(entityClass));
    entityMetadata.ensureUniqueProperties();
    entityMetadata.cleanup();
  }
1038037
def _validate_entity_cls(self, entity_cls):
        """"""
        # Import here to avoid cyclic dependency
        from protean.core.entity import Entity

        if not issubclass(entity_cls, Entity):
            raise AssertionError(
                f'Entity {entity_cls.__name__} must be subclass of `Entity`')

        if entity_cls.meta_.abstract is True:
            raise NotSupportedError(
                f'{entity_cls.__name__} class has been marked abstract'
                f' and cannot be instantiated')
27737
def rounding_sequence_accuracy(predictions,
                               labels,
                               weights_fn=common_layers.weights_nonzero):
  """"""
  outputs = tf.squeeze(tf.to_int32(predictions), axis=-1)
  weights = weights_fn(labels)
  labels = tf.to_int32(labels)
  not_correct = tf.to_float(tf.not_equal(outputs, labels)) * weights
  axis = list(range(1, len(outputs.get_shape())))
  correct_seq = 1.0 - tf.minimum(1.0, tf.reduce_sum(not_correct, axis=axis))
  return correct_seq, tf.constant(1.0)
581516
private void computeDefaultSerializableFields(DocEnv env,
                                                  ClassSymbol def,
                                                  ClassDocImpl cd) {
        for (Scope.Entry e = def.members().elems; e != null; e = e.sibling) {
            if (e.sym != null && e.sym.kind == Kinds.VAR) {
                VarSymbol f = (VarSymbol)e.sym;
                if ((f.flags() & Flags.STATIC) == 0 &&
                    (f.flags() & Flags.TRANSIENT) == 0) {
                    //### No modifier filtering applied here.
                    FieldDocImpl fd = env.getFieldDoc(f);
                    //### Add to beginning.
                    //### Preserve order used by old 'javadoc'.
                    fields.prepend(fd);
                }
            }
        }
    }
954394
def accuracy(logits, labels):
  """"""
  is_correct = tf.nn.in_top_k(logits, labels, 1)
  correct = tf.reduce_sum(tf.cast(is_correct, tf.int32))
  incorrect = tf.reduce_sum(tf.cast(tf.logical_not(is_correct), tf.int32))
  correct_count = tf.Variable(0, False)
  incorrect_count = tf.Variable(0, False)
  correct_count_update = tf.assign_add(correct_count, correct)
  incorrect_count_update = tf.assign_add(incorrect_count, incorrect)
  accuracy_op = tf.cast(correct_count, tf.float32) / tf.cast(
      correct_count + incorrect_count, tf.float32)
  return [correct_count_update, incorrect_count_update], accuracy_op
620023
protected double computePLOFs(Relation<O> relation, KNNQuery<O> knn, WritableDoubleDataStore pdists, WritableDoubleDataStore plofs) {
    FiniteProgress progressPLOFs = LOG.isVerbose() ? new FiniteProgress("PLOFs for objects", relation.size(), LOG) : null;
    double nplof = 0.;
    for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
      final KNNList neighbors = knn.getKNNForDBID(iditer, kcomp + 1); // + query
                                                                      // point
      // use first kref neighbors as comparison set.
      int ks = 0;
      double sum = 0.;
      for(DBIDIter neighbor = neighbors.iter(); neighbor.valid() && ks < kcomp; neighbor.advance()) {
        if(DBIDUtil.equal(neighbor, iditer)) {
          continue;
        }
        sum += pdists.doubleValue(neighbor);
        ks++;
      }
      double plof = MathUtil.max(pdists.doubleValue(iditer) * ks / sum, 1.0);
      if(Double.isNaN(plof) || Double.isInfinite(plof)) {
        plof = 1.0;
      }
      plofs.putDouble(iditer, plof);
      nplof += (plof - 1.0) * (plof - 1.0);

      LOG.incrementProcessed(progressPLOFs);
    }
    LOG.ensureCompleted(progressPLOFs);

    nplof = lambda * FastMath.sqrt(nplof / relation.size());
    if(LOG.isDebuggingFine()) {
      LOG.debugFine("nplof normalization factor is " + nplof);
    }
    return nplof > 0. ? nplof : 1.;
  }
769770
protected void computeEntityViaColumns(EntityMetadata m, boolean isRelation, List<String> relations,
        List<Object> entities, Map<ByteBuffer, List<Column>> qResults) {
        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());

        EntityType entityType = metaModel.entity(m.getEntityClazz());

        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

        for (ByteBuffer key : qResults.keySet()) {
            onColumn(m, isRelation, relations, entities, qResults.get(key), subManagedType, key);
        }
    }
774009
def fc(self, output_nodes, keep_prob=1, activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0, bn=True,
           trainable=True):
        
        self.count['fc'] += 1
        scope = 'fc_' + str(self.count['fc'])
        with tf.variable_scope(scope):

            # Flatten if necessary
            if len(self.input.get_shape()) == 4:
                input_nodes = tf.Dimension(
                    self.input.get_shape()[1] * self.input.get_shape()[2] * self.input.get_shape()[3])
                output_shape = tf.stack([-1, input_nodes])
                self.input = tf.reshape(self.input, output_shape)

            # Matrix Multiplication Function
            input_nodes = self.input.get_shape()[1]
            output_shape = [input_nodes, output_nodes]
            w = self.weight_variable(name='weights', shape=output_shape, trainable=trainable)
            self.input = tf.matmul(self.input, w)

            if bn is True:  # batch normalization
                self.input = self.batch_norm(self.input, 'fc')
            if b_value is not None:  # bias value
                b = self.const_variable(name='bias', shape=[output_nodes], value=b_value, trainable=trainable)
                self.input = tf.add(self.input, b)
            if s_value is not None:  # scale value
                s = self.const_variable(name='scale', shape=[output_nodes], value=s_value, trainable=trainable)
                self.input = tf.multiply(self.input, s)
            if activation_fn is not None:  # activation function
                self.input = activation_fn(self.input)
            if keep_prob != 1:  # dropout function
                self.input = tf.nn.dropout(self.input, keep_prob=keep_prob)
        print(scope + ' output: ' + str(self.input.get_shape()))
749233
private function computeF1Score(float $precision, float $recall): float
    {
        if (0 == ($divider = $precision + $recall)) {
            return 0.0;
        }

        return 2.0 * (($precision * $recall) / $divider);
    }