Logistic Regression in Psychopy/JS

A bit of a longshot, but we are hoping to run an experiment where we run a logistic regression on subject choices in the 1st block, and adapt options in the second block based on the regression results of the first block.

I don’t think we can import any libraries that are helpful with implementation.

Does anyone have any leads on how to best implement this?

Thanks so much in advance,
Levi

I believe if it can be done in JavaScript in theory it is possible through a JS code component - are there any libraries in particular you’re trying to use?

Becca

I found a solution that works for me


// sigmoid function
function sigmoid(x) {
  return 1 / (1 + Math.exp(-x));
}

// logistic regression function
function logisticRegression(features, labels, iterations, learningRate) {
  // add intercept column of 1s to features
  features = features.map(feature => [1, feature]);

  // initialize weights
  let weights = Array(features[0].length).fill(0);

  for (let i = 0; i < iterations; i++) {
    // calculate predictions
    const predictions = features.map(point => sigmoid(dotProduct(point, weights)));

    // calculate errors
    const errors = labels.map((label, index) => label - predictions[index]);

    // calculate gradients
    const gradients = features.map(
      (point, index) => point.map(value => value * errors[index])
    );

    // calculate mean gradients
    const meanGradients = gradients.reduce(
      (accumulator, currentValue) =>
        accumulator.map((value, index) => value + currentValue[index])
    ).map(value => value * (1 / features.length));

    // update weights
    weights = weights.map(
      (weight, index) => weight + learningRate * meanGradients[index]
    );
  }

  return weights;
}

// dot product function
function dotProduct(a, b) {
  return a.reduce((accumulator, currentValue, currentIndex) =>
    accumulator + currentValue * b[currentIndex],
    0
  );
}

numIterations = 120000;
learningRate = 0.01;
//features and labels need to be an input 
weight = logisticRegression(features, labels, numIterations, learningRate);
1 Like