{"ast":null,"code":"/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { ENGINE } from '../engine';\nimport { keep, tidy } from '../globals';\nimport { add } from '../ops/add';\nimport { mul } from '../ops/mul';\nimport { scalar } from '../ops/scalar';\nimport { registerClass } from '../serialization';\nimport { Optimizer } from './optimizer';\n/** @doclink Optimizer */\n\nexport class SGDOptimizer extends Optimizer {\n  constructor(learningRate) {\n    super();\n    this.learningRate = learningRate;\n    this.setLearningRate(learningRate);\n  }\n\n  applyGradients(variableGradients) {\n    const varNames = Array.isArray(variableGradients) ? variableGradients.map(v => v.name) : Object.keys(variableGradients);\n    varNames.forEach((name, i) => {\n      const gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];\n\n      if (gradient == null) {\n        return;\n      }\n\n      const value = ENGINE.registeredVariables[name];\n      tidy(() => {\n        const newValue = add(mul(this.c, gradient), value);\n        value.assign(newValue);\n      });\n    });\n    this.incrementIterations();\n  }\n  /**\n   * Sets the learning rate of the optimizer.\n   */\n\n\n  setLearningRate(learningRate) {\n    this.learningRate = learningRate;\n\n    if (this.c != null) {\n      this.c.dispose();\n    }\n\n    this.c = keep(scalar(-learningRate));\n  }\n\n  dispose() {\n    this.c.dispose();\n  }\n\n  async getWeights() {\n    return [await this.saveIterations()];\n  }\n\n  async setWeights(weightValues) {\n    weightValues = await this.extractIterations(weightValues);\n\n    if (weightValues.length !== 0) {\n      throw new Error('SGD optimizer does not have settable weights.');\n    }\n  }\n\n  getConfig() {\n    return {\n      'learningRate': this.learningRate\n    };\n  }\n  /** @nocollapse */\n\n\n  static fromConfig(cls, config) {\n    return new cls(config['learningRate']);\n  }\n\n}\n/** @nocollapse */\n\nSGDOptimizer.className = 'SGD'; // Note: Name matters for Python compatibility.\n\nregisterClass(SGDOptimizer);","map":null,"metadata":{},"sourceType":"module"}