🏠 back to Observable

Unable to use a function from an npm library ml-levenberg-marquardt

I want to reproduce the example in the npm library ml-levenberg-marquardt in an Observable notebook. I run the following in a cell and a block:

fit_data = {
  let data = {
    x: [0, 1, 2],
    y: [1, 1, 1]
  return data
    const LM = require('ml-levenberg-marquardt@2.1.1/lib/index.js').catch(() => window["_interopDefault"]);
    function sinFunction([a, b]) {
    return (t) => a * Math.sin(b * t);

  const options = {
    damping: 1.5,
    gradientDifference: 10e-2,
    maxIterations: 100,
    errorTolerance: 10e-3

  let fittedParams = LM(fit_data, sinFunction, options);
  return fittedParams

and I get the error message TypeError: LM is not a function. I could be importing this function completely incorrectly.

I am importing the library by following this guide.

Try adding ‘await’ to the require. Change

const LM = require('ml-levenberg-marquardt@2.1.1/lib/index.js').catch(() => window["_interopDefault"]);`


const LM = await require('ml-levenberg-marquardt@2.1.1/lib/index.js').catch(() => window["_interopDefault"]);`

or you could put the require in its own cell (outside the code block), since a cell has an implicit await. I hope that helps!

1 Like

@Cobus Thanks for the reply. Importing in a cell worked, but I am still unable to use the functions I want. On the guide it said that:

There may be multiple variables attached to the window that way, so for completeness, here are all of them: _interopDefault , isArray , mlMatrix , errorCalculation , gradientFunction , matrixFunction , step , levenbergMarquardt .

What does this mean, and how do I start using these functions?

Looking at the file your trying to “require” it has not been packaged correctly for browser usage: https://cdn.jsdelivr.net/npm/ml-levenberg-marquardt@2.1.1/lib/index.js

Typically that library would be run through a tool like RollupJS or WebPack which wraps it in a layer that is compatible with browser and NodeJS usage (and will also pull in dependencies as needed)

One way around this is to just extract the functions into individual cells in your notebook (instead of requiring it from npm).

Here is an example: https://observablehq.com/d/98f3b940a1389dc4

I would include the license from the NPM package in the notebook to make it clear that you copied it from there…

1 Like