Module: OpenTox::Algorithm::Neighbors

Defined in:
lib/algorithm.rb

Class Method Summary collapse

Class Method Details

.get_confidence(params) ⇒ Object

Get confidence for regression, with standard deviation of neighbor activity if conf_stdev is set. @param Required keys: :sims, :acts, :neighbors, :conf_stdev @return Confidence



623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# File 'lib/algorithm.rb', line 623

def self.get_confidence(params)
  if params[:conf_stdev]
    sim_median = params[:sims].to_scale.median
    if sim_median.nil?
      confidence = nil
    else
      standard_deviation = params[:acts].to_scale.standard_deviation_sample
      confidence = (sim_median*Math.exp(-1*standard_deviation)).abs
      if confidence.nan?
        confidence = nil
      end
    end
  else
    conf = params[:sims].inject{|sum,x| sum + x }
    confidence = conf/params[:neighbors].size
  end
  LOGGER.debug "Confidence is: '" + confidence.to_s + "'."
  return confidence
end

.get_props(params) ⇒ Object

Calculate the propositionalization matrix aka instantiation matrix (0/1 entries for features) Same for the vector describing the query compound @param neighbors. @param query compound. @param Dataset Features. @param Fingerprints of neighbors. @param p-values of Features.



663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
# File 'lib/algorithm.rb', line 663

def self.get_props (params)
  matrix = Array.new
  begin 
    params[:neighbors].each do |n|
      n = n[:compound]
      row = []
      params[:features].each do |f|
        if ! params[:fingerprints][n].nil? 
          row << (params[:fingerprints][n].include?(f) ? (params[:p_values][f] * params[:fingerprints][n][f]) : 0.0)
        else
          row << 0.0
        end
      end
      matrix << row
    end
    row = []
    params[:features].each do |f|
      if params[:nr_hits]
        compound_feature_hits = params[:compound].match_hits([f])
        row << (compound_feature_hits.size == 0 ? 0.0 : (params[:p_values][f] * compound_feature_hits[f]))
      else
        row << (params[:compound].match([f]).size == 0 ? 0.0 : params[:p_values][f])
      end
    end
  rescue Exception => e
    LOGGER.debug "get_props failed with '" + $! + "'"
  end
  [ matrix, row ]
end

.get_sizes(matrix) ⇒ Object

Get X and Y size of a nested Array (Matrix)



644
645
646
647
648
649
650
651
652
653
654
# File 'lib/algorithm.rb', line 644

def self.get_sizes(matrix)
  begin
    nr_cases = matrix.size
    nr_features = matrix[0].size
  rescue Exception => e
    LOGGER.debug "#{e.class}: #{e.message}"
    LOGGER.debug "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
  end
  #puts "NRC: #{nr_cases}, NRF: #{nr_features}"
  [ nr_cases, nr_features ]
end

.local_mlr_prop(params) ⇒ Numeric

Local multi-linear regression (MLR) prediction from neighbors. Uses propositionalized setting.

Parameters:

  • params (Hash)

    Keys ‘:neighbors,:compound,:features,:p_values,:similarity_algorithm,:prop_kernel,:value_map,:transform` are required

Returns:

  • (Numeric)

    A prediction value.



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/algorithm.rb', line 320

def self.local_mlr_prop(params)

  confidence=0.0
  prediction=nil

  if params[:neighbors].size>0
    props = params[:prop_kernel] ? get_props(params) : nil
    acts = params[:neighbors].collect { |n| act = n[:activity].to_f }
    sims = params[:neighbors].collect { |n| Algorithm.gauss(n[:similarity]) }
    LOGGER.debug "Local MLR (Propositionalization / GSL)."
    prediction = mlr( {:n_prop => props[0], :q_prop => props[1], :sims => sims, :acts => acts} )
    transformer = eval("OpenTox::Algorithm::Transform::#{params[:transform]["class"]}.new ([#{prediction}], #{params[:transform]["offset"]})")
    prediction = transformer.values[0]
    prediction = nil if prediction.infinite? || params[:prediction_min_max][1] < prediction || params[:prediction_min_max][0] > prediction  
    LOGGER.debug "Prediction is: '" + prediction.to_s + "'."
    params[:conf_stdev] = false if params[:conf_stdev].nil?
    confidence = get_confidence({:sims => sims, :acts => acts, :neighbors => params[:neighbors], :conf_stdev => params[:conf_stdev]})
    confidence = nil if prediction.nil?
  end
  {:prediction => prediction, :confidence => confidence}

end

.local_svm(acts, sims, type, params) ⇒ Numeric

Local support vector prediction from neighbors. Uses pre-defined Kernel Matrix. Not to be called directly (use local_svm_regression or local_svm_classification).

Parameters:

  • acts, (Array)

    activities for neighbors.

  • sims, (Array)

    similarities for neighbors.

  • type, (String)

    one of “nu-svr” (regression) or “C-bsvc” (classification).

  • params (Hash)

    Keys ‘:neighbors,:compound,:features,:p_values,:similarity_algorithm,:prop_kernel,:value_map,:transform` are required

Returns:

  • (Numeric)

    A prediction value.



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# File 'lib/algorithm.rb', line 485

def self.local_svm(acts, sims, type, params)
  LOGGER.debug "Local SVM (Weighted Tanimoto Kernel)."
  neighbor_matches = params[:neighbors].collect{ |n| n[:features] } # URIs of matches
  gram_matrix = [] # square matrix of similarities between neighbors; implements weighted tanimoto kernel

  prediction = nil
  if Algorithm::zero_variance? acts
    prediction = acts[0]
  else
    # gram matrix
    (0..(neighbor_matches.length-1)).each do |i|
      neighbor_i_hits = params[:fingerprints][params[:neighbors][i][:compound]]
      gram_matrix[i] = [] unless gram_matrix[i]
      # upper triangle
      ((i+1)..(neighbor_matches.length-1)).each do |j|
        neighbor_j_hits= params[:fingerprints][params[:neighbors][j][:compound]]
        sim_params = {}
        if params[:nr_hits]
          sim_params[:nr_hits] = true
          sim_params[:compound_features_hits] = neighbor_i_hits
          sim_params[:training_compound_features_hits] = neighbor_j_hits
        end
        sim = eval("#{params[:similarity_algorithm]}(neighbor_matches[i], neighbor_matches[j], params[:p_values], sim_params)")
        gram_matrix[i][j] = Algorithm.gauss(sim)
        gram_matrix[j] = [] unless gram_matrix[j] 
        gram_matrix[j][i] = gram_matrix[i][j] # lower triangle
      end
      gram_matrix[i][i] = 1.0
    end


    #LOGGER.debug gram_matrix.to_yaml
    @r = RinRuby.new(false,false) # global R instance leads to Socket errors after a large number of requests
    @r.eval "library('kernlab')" # this requires R package "kernlab" to be installed
    LOGGER.debug "Setting R data ..."
    # set data
    @r.gram_matrix = gram_matrix.flatten
    @r.n = neighbor_matches.size
    @r.y = acts
    @r.sims = sims

    begin
      LOGGER.debug "Preparing R data ..."
      # prepare data
      @r.eval "y<-as.vector(y)"
      @r.eval "gram_matrix<-as.kernelMatrix(matrix(gram_matrix,n,n))"
      @r.eval "sims<-as.vector(sims)"
      
      # model + support vectors
      LOGGER.debug "Creating SVM model ..."
      @r.eval "model<-ksvm(gram_matrix, y, kernel=matrix, type=\"#{type}\", nu=0.5)"
      @r.eval "sv<-as.vector(SVindex(model))"
      @r.eval "sims<-sims[sv]"
      @r.eval "sims<-as.kernelMatrix(matrix(sims,1))"
      LOGGER.debug "Predicting ..."
      if type == "nu-svr" 
        @r.eval "p<-predict(model,sims)[1,1]"
      elsif type == "C-bsvc"
        @r.eval "p<-predict(model,sims)"
      end
      if type == "nu-svr"
        prediction = @r.p
      elsif type == "C-bsvc"
        #prediction = (@r.p.to_f == 1.0 ? true : false)
        prediction = @r.p
      end
      @r.quit # free R
    rescue Exception => e
      LOGGER.debug "#{e.class}: #{e.message}"
      LOGGER.debug "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
    end

  end
  prediction
end

.local_svm_classification(params) ⇒ Numeric

Local support vector classification from neighbors

Parameters:

  • params (Hash)

    Keys ‘:neighbors,:compound,:features,:p_values,:similarity_algorithm,:prop_kernel,:value_map,:transform` are required

Returns:

  • (Numeric)

    A prediction value.



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/algorithm.rb', line 459

def self.local_svm_classification(params)

  confidence = 0.0
  prediction = nil
  if params[:neighbors].size>0
    props = params[:prop_kernel] ? get_props(params) : nil
    acts = params[:neighbors].collect { |n| act = n[:activity] }
    sims = params[:neighbors].collect{ |n| Algorithm.gauss(n[:similarity]) } # similarity values btwn q and nbors
    prediction = props.nil? ? local_svm(acts, sims, "C-bsvc", params) : local_svm_prop(props, acts, "C-bsvc")
    LOGGER.debug "Prediction is: '" + prediction.to_s + "'."
    params[:conf_stdev] = false if params[:conf_stdev].nil?
    confidence = get_confidence({:sims => sims, :acts => acts, :neighbors => params[:neighbors], :conf_stdev => params[:conf_stdev]})
  end
  {:prediction => prediction, :confidence => confidence}
  
end

.local_svm_prop(props, acts, type) ⇒ Numeric

Local support vector prediction from neighbors. Uses propositionalized setting. Not to be called directly (use local_svm_regression or local_svm_classification).

Parameters:

  • props, (Array)

    propositionalization of neighbors and query structure e.g. [ Array_for_q, two-nested-Arrays_for_n ]

  • acts, (Array)

    activities for neighbors.

  • type, (String)

    one of “nu-svr” (regression) or “C-bsvc” (classification).

Returns:

  • (Numeric)

    A prediction value.



568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'lib/algorithm.rb', line 568

def self.local_svm_prop(props, acts, type)

    LOGGER.debug "Local SVM (Propositionalization / Kernlab Kernel)."
    n_prop = props[0] # is a matrix, i.e. two nested Arrays.
    q_prop = props[1] # is an Array.

    prediction = nil
    if Algorithm::zero_variance? acts
      prediction = acts[0]
    else
      #LOGGER.debug gram_matrix.to_yaml
      @r = RinRuby.new(false,false) # global R instance leads to Socket errors after a large number of requests
      @r.eval "library('kernlab')" # this requires R package "kernlab" to be installed
      LOGGER.debug "Setting R data ..."
      # set data
      @r.n_prop = n_prop.flatten
      @r.n_prop_x_size = n_prop.size
      @r.n_prop_y_size = n_prop[0].size
      @r.y = acts
      @r.q_prop = q_prop

      begin
        LOGGER.debug "Preparing R data ..."
        # prepare data
        @r.eval "y<-matrix(y)"
        @r.eval "prop_matrix<-matrix(n_prop, n_prop_x_size, n_prop_y_size, byrow=TRUE)"
        @r.eval "q_prop<-matrix(q_prop, 1, n_prop_y_size, byrow=TRUE)"
        
        # model + support vectors
        LOGGER.debug "Creating SVM model ..."
        @r.eval "model<-ksvm(prop_matrix, y, type=\"#{type}\", nu=0.5)"
        LOGGER.debug "Predicting ..."
        if type == "nu-svr" 
          @r.eval "p<-predict(model,q_prop)[1,1]"
        elsif type == "C-bsvc"
          @r.eval "p<-predict(model,q_prop)"
        end
        if type == "nu-svr"
          prediction = @r.p
        elsif type == "C-bsvc"
          #prediction = (@r.p.to_f == 1.0 ? true : false)
          prediction = @r.p
        end
        @r.quit # free R
      rescue Exception => e
        LOGGER.debug "#{e.class}: #{e.message}"
        LOGGER.debug "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
      end
    end
    prediction
end

.local_svm_regression(params) ⇒ Numeric

Local support vector regression from neighbors

Parameters:

  • params (Hash)

    Keys ‘:neighbors,:compound,:features,:p_values,:similarity_algorithm,:prop_kernel,:value_map,:transform` are required

Returns:

  • (Numeric)

    A prediction value.



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/algorithm.rb', line 435

def self.local_svm_regression(params)

  confidence = 0.0
  prediction = nil
  if params[:neighbors].size>0
    props = params[:prop_kernel] ? get_props(params) : nil
    acts = params[:neighbors].collect{ |n| n[:activity].to_f }
    sims = params[:neighbors].collect{ |n| Algorithm.gauss(n[:similarity]) }
    prediction = props.nil? ? local_svm(acts, sims, "nu-svr", params) : local_svm_prop(props, acts, "nu-svr")
    transformer = eval("OpenTox::Algorithm::Transform::#{params[:transform]["class"]}.new ([#{prediction}], #{params[:transform]["offset"]})")
    prediction = transformer.values[0]
    prediction = nil if prediction.infinite? || params[:prediction_min_max][1] < prediction || params[:prediction_min_max][0] > prediction  
    LOGGER.debug "Prediction is: '" + prediction.to_s + "'."
    params[:conf_stdev] = false if params[:conf_stdev].nil?
    confidence = get_confidence({:sims => sims, :acts => acts, :neighbors => params[:neighbors], :conf_stdev => params[:conf_stdev]})
    confidence = nil if prediction.nil?
  end
  {:prediction => prediction, :confidence => confidence}
  
end

.mlr(params) ⇒ Numeric

Multi-linear regression weighted by similarity. Objective Feature Selection, Principal Components Analysis, Scaling of Axes.

Parameters:

  • params (Hash)

    Keys ‘:n_prop, :q_prop, :sims, :acts` are required

Returns:

  • (Numeric)

    A prediction value.



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/algorithm.rb', line 347

def self.mlr(params)

  # GSL matrix operations: 
  # to_a : row-wise conversion to nested array
  #
  # Statsample operations (build on GSL):
  # to_scale: convert into Statsample format

  begin
    n_prop = params[:n_prop].collect { |v| v }
    q_prop = params[:q_prop].collect { |v| v }
    n_prop << q_prop # attach q_prop
    nr_cases, nr_features = get_sizes n_prop
    data_matrix = GSL::Matrix.alloc(n_prop.flatten, nr_cases, nr_features)

    # Principal Components Analysis
    LOGGER.debug "PCA..."
    pca = OpenTox::Algorithm::Transform::PCA.new(data_matrix)
    data_matrix = pca.data_transformed_matrix

    # Attach intercept column to data
    intercept = GSL::Matrix.alloc(Array.new(nr_cases,1.0),nr_cases,1)
    data_matrix = data_matrix.horzcat(intercept)
    (0..data_matrix.size2-2).each { |i|
      autoscaler = OpenTox::Algorithm::Transform::AutoScale.new(data_matrix.col(i))
      data_matrix.col(i)[0..data_matrix.size1-1] = autoscaler.scaled_values
    }

    # Detach query instance
    n_prop = data_matrix.to_a
    q_prop = n_prop.pop 
    nr_cases, nr_features = get_sizes n_prop
    data_matrix = GSL::Matrix.alloc(n_prop.flatten, nr_cases, nr_features)

    # model + support vectors
    LOGGER.debug "Creating MLR model ..."
    c, cov, chisq, status = GSL::MultiFit::wlinear(data_matrix, params[:sims].to_scale.to_gsl, params[:acts].to_scale.to_gsl)
    GSL::MultiFit::linear_est(q_prop.to_scale.to_gsl, c, cov)[0]
  rescue Exception => e
    LOGGER.debug "#{e.class}: #{e.message}"
  end

end

.weighted_majority_vote(params) ⇒ Numeric

Classification with majority vote from neighbors weighted by similarity

Parameters:

  • params (Hash)

    Keys ‘:neighbors,:compound,:features,:p_values,:similarity_algorithm,:prop_kernel,:value_map,:transform` are required

Returns:

  • (Numeric)

    A prediction value.



394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/algorithm.rb', line 394

def self.weighted_majority_vote(params)

  neighbor_contribution = 0.0
  confidence_sum = 0.0
  confidence = 0.0
  prediction = nil

  params[:neighbors].each do |neighbor|
    neighbor_weight = Algorithm.gauss(neighbor[:similarity]).to_f
    neighbor_contribution += neighbor[:activity].to_f * neighbor_weight

    if params[:value_map].size == 2 # AM: provide compat to binary classification: 1=>false 2=>true
      case neighbor[:activity]
      when 1
        confidence_sum -= neighbor_weight
      when 2
        confidence_sum += neighbor_weight
      end
    else
      confidence_sum += neighbor_weight
    end
  end

  if params[:value_map].size == 2 
    if confidence_sum >= 0.0
      prediction = 2 unless params[:neighbors].size==0
    elsif confidence_sum < 0.0
      prediction = 1 unless params[:neighbors].size==0
    end
  else 
    prediction = (neighbor_contribution/confidence_sum).round  unless params[:neighbors].size==0  # AM: new multinomial prediction
  end 
  LOGGER.debug "Prediction is: '" + prediction.to_s + "'." unless prediction.nil?
  confidence = confidence_sum/params[:neighbors].size if params[:neighbors].size > 0
  LOGGER.debug "Confidence is: '" + confidence.to_s + "'." unless prediction.nil?
  return {:prediction => prediction, :confidence => confidence.abs}
end