Tensorflow.js tf.train.Optimizer class .minimize() Method - GeeksforGeeks

03 Sep, 2021Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The .minimize() method executes the given function f() and tries to minimize the scalar output of f() by computing the gradients of y with respect to the given list of trainable variables denoted by varList. If no list is provided, it compute gradients with respect to all trainable variables.Syntax:Optimizer.minimize (f, returnCost?, varList?)Parameters:f (() => tf.Scalar): It specifies the function to execute and whose output to minimize.returnCost (boolean): It specifies whether to return the scalar cost value produced by executing f() or not.varList (tf.Variable[]): It specifies the list of trainable variables.Return value: tf.Scalar | nullExample 1:JavascriptJavascript// Importing tensorflowimport tensorflow as tf   const xs = tf.tensor1d([0, 1, 2]);const ys = tf.tensor1d([1.3, 2.5, 3.7]);   const x = tf.scalar(Math.random()).variable();const y = tf.scalar(Math.random()).variable();   // Define a function f(x, y) = x + y.const f = x => x.add(y);const loss = (pred, label) =>    pred.sub(label).square().mean();   const learningRate = 0.05;   // Create adagrad optimizerconst optimizer =  tf.train.adagrad(learningRate);   // Train the model.for (let i = 0; i < 5; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`x: ${x.dataSync()}, y: ${y.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {console.log(`x: ${i}, pred: ${pred}`);});Outputx: 0.9395854473114014, y: 1.0498266220092773
x: 0, pred: 1.0498266220092773
x: 1, pred: 2.0498266220092773
x: 2, pred: 3.0498266220092773Example 2:JavascriptJavascript// Importing tensorflowimport * as tf from "@tensorflow/tfjs"   const xs = tf.tensor1d([0, 1, 2, 3]);const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);   // Choosing random coefficientsconst a = tf.scalar(Math.random()).variable();const b = tf.scalar(Math.random()).variable();const c = tf.scalar(Math.random()).variable();   // Defining function f = (a*x^2 + b*x + c)const f = x => a.mul(x.square()).add(b.mul(x)).add(c);const loss = (pred, label) => pred.sub(label).square().mean();   // Setting configurations for our optimizerconst learningRate = 0.01;const decay = 0.1;const momentum = 1;const epsilon = 0.5;const centered = true;   // Create the ptimizerconst optimizer = tf.train.rmsprop(learningRate,        decay, momentum, epsilon, centered);   // Train the model.for (let i = 0; i < 8; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`a: ${a.dataSync()},    b: ${b.dataSync()}, c: ${c.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {   console.log(`x: ${i}, pred: ${pred}`);});Outputa: 3.6799352169036865, 
    b: 4.26292610168457, c: 4.544136047363281
x: 0, pred: 4.544136047363281
x: 1, pred: 12.486997604370117
x: 2, pred: 27.789730072021484
x: 3, pred: 50.45233154296875Reference: https://js.tensorflow.org/api/latest/#tf.train.Optimizer.minimizeMy Personal Notes
arrow_drop_upSave

Like0PreviousTensorFlow.js Browser Complete ReferenceNext
Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :Difference between Class.method and Class.prototype.method12, Aug 20jQWidgets jqxMenu minimize() Method21, Oct 21How to find the parent class name with known class in jQuery ?17, Jun 19How to override the CSS properties of a class using another CSS class ?27, Sep 19Toggle class by adding the class name when element is clicked and remove when clicked outside16, Dec 20How to add a new class to an element that already has a class using jQuery ?30, Dec 20How to call base class constructor from child class in TypeScript ?14, Jun 21Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same14, Dec 21Tensorflow.js tf.Sequential class .evaluate() Method29, Jun 21Tensorflow.js tf.Tensor class .buffer() Method25, May 21Tensorflow.js tf.Sequential class .summary() Method29, Jun 21Tensorflow.js tf.LayersModel Class .evaluate() Method21, Jun 21Tensorflow.js tf.data.Dataset class .batch() Method28, May 21Tensorflow.js tf.LayersModel class .save() Method31, Aug 21Tensorflow.js tf.Sequential class .trainOnBatch() Method31, Aug 21Tensorflow.js tf.LayersModel class .fit() Method31, Aug 21Tensorflow.js tf.Sequential Class .add() Method21, Jun 21Tensorflow.js tf.TensorBuffer class .get() Method23, Jul 21Tensorflow.js tf.TensorBuffer Class .set() Method23, Jun 21How to add method to String class in JavaScript?17, Mar 20How to add class to an element without addClass() method in jQuery ?23, Apr 20Tensorflow.js tf.Tensor class .dispose() Method17, Aug 21How to call a parent method from child class in JavaScript?04, Jun 20Node.js stats.isDirectory() Method from fs.Stats Class29, Jun 20Article Contributed By :abhinavjain194@abhinavjain194Vote for difficultyEasy
Normal
Medium
Hard
ExpertImproved By :gabaa406anikakapoorArticle Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?Top 10 Projects For Beginners To Practice HTML and CSS SkillsImprove your Coding Skills with PracticeTry It!
5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.orgCompanyAbout UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks
, Some rights reserved 
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
        Privacy Policy

Got It !
Start Your Coding Journey Now!Login
Register
Tensorflow.js tf.tensor() Function
Tensorflow.js tf.scalar() Function
TenserFlow.js Tensors Creation Complete Reference
Tensorflow.js tf.Tensor class .buffer() Method
Tensorflow.js tf.Tensor class .bufferSync() Method
TensorFlow.js Tensors Classes Complete Reference
Tensorflow.js tf.booleanMaskAsync() Function
Tensorflow.js tf.concat() Function
TensorFlow.js Tensors Transformations Complete Reference
TensorFlow.js Slicing and Joining Complete Reference
Tensorflow.js tf.einsum() Function
Tensorflow.js tf.multinomial() Function
TensorFlow.js Tensor Random Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.input() Function
Tensorflow.js tf.loadGraphModel() Function
Tensorflow.js tf.io.http() Function
TensorFlow.js Models Loading Complete Reference
Tensorflow.js tf.io.copyModel() Function
Tensorflow.js tf.io.listModels() Function
Tensorflow.js tf.io.moveModel() Function
TensorFlow.js Models Management Complete Reference
Tensorflow.js tf.GraphModel Class
Tensorflow.js tf.GraphModel class .save() Method
Tensorflow.js tf.GraphModel class .predict() Method
Tensorflow.js tf.GraphModel class .execute() Method
TensorFlow.js Models Classes Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.layers.elu() Function
Tensorflow.js tf.layers.activation() Function
TensorFlow.js Layers Basic Complete Reference
Tensorflow.js tf.layers.conv1d() Function
TensorFlow.js Layers Convolutional Complete Reference
Tensorflow.js tf.layers.add() Function
TensorFlow.js Layers Merge Complete Reference
Tensorflow.js tf.layers.globalAveragePooling1d() Function
TensorFlow.js Layers Pooling Complete Reference
TensorFlow.js Layers Noise Complete Reference
Tensorflow.js tf.layers.bidirectional() Function
Tensorflow.js tf.layers.timeDistributed() Function
TensorFlow.js Layers Classes Complete Reference
Tensorflow.js tf.layers.zeroPadding2d() Function
Tensorflow.js tf.layers.masking() Function
Tensorflow.js tf.train.Optimizer class .minimize() Method
TensorFlow.js Operations Arithmetic Complete Reference
TensorFlow.js Operations Basic Math Complete Reference
TensorFlow.js Operations Matrices Complete Reference
TensorFlow.js Operations Normalization Complete Reference
TensorFlow.js Operations Images Complete Reference
TensorFlow.js Operations Logical Complete Reference
TensorFlow.js Operations Evaluation Complete Reference
Tensorflow.js tf.cumsum() Function
TensorFlow.js Operations Slicing and Joining Complete Reference
TensorFlow.js Operations Spectral Complete Reference
Tensorflow.js tf.unsortedSegmentSum() Function
Tensorflow.js tf.movingAverage() Function
Tensorflow.js tf.dropout() Function
TensorFlow.js Operations Signal Complete Reference
Tensorflow.js tf.linalg.bandPart() Function
Tensorflow.js tf.linalg.gramSchmidt() Function
Tensorflow.js tf.linalg.qr() Function
TensorFlow.js Operations Sparse Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.grad() Function
Tensorflow.js tf.grads() Function
Tensorflow.js tf.customGrad() Function
TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsTable of ContentsTensorFlow.jsTensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article

Save Article

Like Article

Tensorflow.js tf.train.Optimizer class .minimize() MethodLast Updated :
03 Sep, 2021Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The .minimize() method executes the given function f() and tries to minimize the scalar output of f() by computing the gradients of y with respect to the given list of trainable variables denoted by varList. If no list is provided, it compute gradients with respect to all trainable variables.Syntax:Optimizer.minimize (f, returnCost?, varList?)Parameters:f (() => tf.Scalar): It specifies the function to execute and whose output to minimize.returnCost (boolean): It specifies whether to return the scalar cost value produced by executing f() or not.varList (tf.Variable[]): It specifies the list of trainable variables.Return value: tf.Scalar | nullExample 1:JavascriptJavascript// Importing tensorflowimport tensorflow as tf   const xs = tf.tensor1d([0, 1, 2]);const ys = tf.tensor1d([1.3, 2.5, 3.7]);   const x = tf.scalar(Math.random()).variable();const y = tf.scalar(Math.random()).variable();   // Define a function f(x, y) = x + y.const f = x => x.add(y);const loss = (pred, label) =>    pred.sub(label).square().mean();   const learningRate = 0.05;   // Create adagrad optimizerconst optimizer =  tf.train.adagrad(learningRate);   // Train the model.for (let i = 0; i < 5; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`x: ${x.dataSync()}, y: ${y.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {console.log(`x: ${i}, pred: ${pred}`);});Outputx: 0.9395854473114014, y: 1.0498266220092773
x: 0, pred: 1.0498266220092773
x: 1, pred: 2.0498266220092773
x: 2, pred: 3.0498266220092773Example 2:JavascriptJavascript// Importing tensorflowimport * as tf from "@tensorflow/tfjs"   const xs = tf.tensor1d([0, 1, 2, 3]);const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);   // Choosing random coefficientsconst a = tf.scalar(Math.random()).variable();const b = tf.scalar(Math.random()).variable();const c = tf.scalar(Math.random()).variable();   // Defining function f = (a*x^2 + b*x + c)const f = x => a.mul(x.square()).add(b.mul(x)).add(c);const loss = (pred, label) => pred.sub(label).square().mean();   // Setting configurations for our optimizerconst learningRate = 0.01;const decay = 0.1;const momentum = 1;const epsilon = 0.5;const centered = true;   // Create the ptimizerconst optimizer = tf.train.rmsprop(learningRate,        decay, momentum, epsilon, centered);   // Train the model.for (let i = 0; i < 8; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`a: ${a.dataSync()},    b: ${b.dataSync()}, c: ${c.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {   console.log(`x: ${i}, pred: ${pred}`);});Outputa: 3.6799352169036865, 
    b: 4.26292610168457, c: 4.544136047363281
x: 0, pred: 4.544136047363281
x: 1, pred: 12.486997604370117
x: 2, pred: 27.789730072021484
x: 3, pred: 50.45233154296875Reference: https://js.tensorflow.org/api/latest/#tf.train.Optimizer.minimizeMy Personal Notes
arrow_drop_upSave

Like0PreviousTensorFlow.js Browser Complete ReferenceNext
Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :Difference between Class.method and Class.prototype.method12, Aug 20jQWidgets jqxMenu minimize() Method21, Oct 21How to find the parent class name with known class in jQuery ?17, Jun 19How to override the CSS properties of a class using another CSS class ?27, Sep 19Toggle class by adding the class name when element is clicked and remove when clicked outside16, Dec 20How to add a new class to an element that already has a class using jQuery ?30, Dec 20How to call base class constructor from child class in TypeScript ?14, Jun 21Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same14, Dec 21Tensorflow.js tf.Sequential class .evaluate() Method29, Jun 21Tensorflow.js tf.Tensor class .buffer() Method25, May 21Tensorflow.js tf.Sequential class .summary() Method29, Jun 21Tensorflow.js tf.LayersModel Class .evaluate() Method21, Jun 21Tensorflow.js tf.data.Dataset class .batch() Method28, May 21Tensorflow.js tf.LayersModel class .save() Method31, Aug 21Tensorflow.js tf.Sequential class .trainOnBatch() Method31, Aug 21Tensorflow.js tf.LayersModel class .fit() Method31, Aug 21Tensorflow.js tf.Sequential Class .add() Method21, Jun 21Tensorflow.js tf.TensorBuffer class .get() Method23, Jul 21Tensorflow.js tf.TensorBuffer Class .set() Method23, Jun 21How to add method to String class in JavaScript?17, Mar 20How to add class to an element without addClass() method in jQuery ?23, Apr 20Tensorflow.js tf.Tensor class .dispose() Method17, Aug 21How to call a parent method from child class in JavaScript?04, Jun 20Node.js stats.isDirectory() Method from fs.Stats Class29, Jun 20Article Contributed By :abhinavjain194@abhinavjain194Vote for difficultyEasy
Normal
Medium
Hard
ExpertImproved By :gabaa406anikakapoorArticle Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?Top 10 Projects For Beginners To Practice HTML and CSS SkillsImprove your Coding Skills with PracticeTry It!
5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.orgCompanyAbout UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks
, Some rights reserved 
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
        Privacy Policy

Got It !
Start Your Coding Journey Now!Login
Register
Tensorflow.js tf.train.momentum() Function
Tensorflow.js tf.train.adagrad() Function
TensorFlow.js Training Optimizers Complete Reference
Tensorflow.js tf.losses.absoluteDifference() Function
Tensorflow.js tf.losses.computeWeightedLoss() Function
Tensorflow.js tf.losses.cosineDistance() Function
TensorFlow.js Training Losses Complete Reference
Tensorflow.js tf.train.Optimizer Class
Tensorflow.js tf.train.Optimizer class .minimize() Method
TensorFlow.js Training Classes Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.time() Function
Tensorflow.js tf.nextFrame() Function
Tensorflow.js tf.profile() Function
TensorFlow.js Performance Memory Complete Reference
Tensorflow.js tf.disposeVariables() Function
Tensorflow.js tf.enableDebugMode() Function
Tensorflow.js tf.enableProdMode() Function
Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics
TensorFlow.js Environment Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.metrics.binaryAccuracy() Function
Tensorflow.js tf.metrics.binaryCrossentropy() Function
Tensorflow.js tf.metrics.categoricalAccuracy() Function
Tensorflow.js tf.metrics.categoricalCrossentropy() Function
Tensorflow.js tf.metrics.cosineProximity() Function
Tensorflow.js tf.metrics.meanSquaredError() Function
Tensorflow.js tf.metrics.precision() Function
Tensorflow.js tf.metrics.recall() Function
Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function
TensorFlow.js Metrics Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.initializers.Initializer Class
Tensorflow.js tf.initializers.constant() Method
Tensorflow.js tf.initializers.glorotNormal() Function
Tensorflow.js tf.initializers.glorotUniform() Function
Tensorflow.js tf.initializers.heNormal() Function
Tensorflow.js tf.initializers.heUniform() Function
TensorFlow.js Initializers Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.regularizers.l1() Function
Tensorflow.js tf.regularizers.l1l2() Function
Tensorflow.js tf.regularizers.l2() Function
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.data.csv() Function
Tensorflow.js tf.data.generator() Function
Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics
TensorFlow.js Data Creation Complete Reference
Tensorflow.js tf.data.zip() Function
Tensorflow.js tf.data.Dataset class .batch() Method
TensorFlow.js Data Classes Complete References
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.util.assert() Function
Tensorflow.js tf.util.createShuffledIndices() Function
Tensorflow.js tf.decodeString() Function
Tensorflow.js tf.encodeString() Function
Tensorflow.js tf.fetch() Function
Tensorflow.js tf.util.flatten() Function
Tensorflow.js tf.util.now() Function
Tensorflow.js tf.util.shuffle() Function
Tensorflow.js tf.util.shuffleCombo() Function
Tensorflow.js tf.browser.fromPixels() Function
Tensorflow.js tf.browser.fromPixelsAsync() Function
Tensorflow.js tf.browser.toPixels() Function
TensorFlow.js Browser Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.backend() Function
Tensorflow.js tf.getBackend() Function
Tensorflow.js tf.ready() Function
Tensorflow.js tf.registerBackend() Function
Tensorflow.js tf.removeBackend() Function
Tensorflow.js tf.setBackend() Function
Tensorflow.js tf.callbacks.earlyStopping() Function
TensorFlow.js
Tensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article

Save Article

Like Article

Tensorflow.js tf.train.Optimizer class .minimize() MethodLast Updated :
03 Sep, 2021Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The .minimize() method executes the given function f() and tries to minimize the scalar output of f() by computing the gradients of y with respect to the given list of trainable variables denoted by varList. If no list is provided, it compute gradients with respect to all trainable variables.Syntax:Optimizer.minimize (f, returnCost?, varList?)Parameters:f (() => tf.Scalar): It specifies the function to execute and whose output to minimize.returnCost (boolean): It specifies whether to return the scalar cost value produced by executing f() or not.varList (tf.Variable[]): It specifies the list of trainable variables.Return value: tf.Scalar | nullExample 1:JavascriptJavascript// Importing tensorflowimport tensorflow as tf   const xs = tf.tensor1d([0, 1, 2]);const ys = tf.tensor1d([1.3, 2.5, 3.7]);   const x = tf.scalar(Math.random()).variable();const y = tf.scalar(Math.random()).variable();   // Define a function f(x, y) = x + y.const f = x => x.add(y);const loss = (pred, label) =>    pred.sub(label).square().mean();   const learningRate = 0.05;   // Create adagrad optimizerconst optimizer =  tf.train.adagrad(learningRate);   // Train the model.for (let i = 0; i < 5; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`x: ${x.dataSync()}, y: ${y.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {console.log(`x: ${i}, pred: ${pred}`);});Outputx: 0.9395854473114014, y: 1.0498266220092773
x: 0, pred: 1.0498266220092773
x: 1, pred: 2.0498266220092773
x: 2, pred: 3.0498266220092773Example 2:JavascriptJavascript// Importing tensorflowimport * as tf from "@tensorflow/tfjs"   const xs = tf.tensor1d([0, 1, 2, 3]);const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);   // Choosing random coefficientsconst a = tf.scalar(Math.random()).variable();const b = tf.scalar(Math.random()).variable();const c = tf.scalar(Math.random()).variable();   // Defining function f = (a*x^2 + b*x + c)const f = x => a.mul(x.square()).add(b.mul(x)).add(c);const loss = (pred, label) => pred.sub(label).square().mean();   // Setting configurations for our optimizerconst learningRate = 0.01;const decay = 0.1;const momentum = 1;const epsilon = 0.5;const centered = true;   // Create the ptimizerconst optimizer = tf.train.rmsprop(learningRate,        decay, momentum, epsilon, centered);   // Train the model.for (let i = 0; i < 8; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`a: ${a.dataSync()},    b: ${b.dataSync()}, c: ${c.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {   console.log(`x: ${i}, pred: ${pred}`);});Outputa: 3.6799352169036865, 
    b: 4.26292610168457, c: 4.544136047363281
x: 0, pred: 4.544136047363281
x: 1, pred: 12.486997604370117
x: 2, pred: 27.789730072021484
x: 3, pred: 50.45233154296875Reference: https://js.tensorflow.org/api/latest/#tf.train.Optimizer.minimizeMy Personal Notes
arrow_drop_upSave

Like0PreviousTensorFlow.js Browser Complete ReferenceNext
Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :Difference between Class.method and Class.prototype.method12, Aug 20jQWidgets jqxMenu minimize() Method21, Oct 21How to find the parent class name with known class in jQuery ?17, Jun 19How to override the CSS properties of a class using another CSS class ?27, Sep 19Toggle class by adding the class name when element is clicked and remove when clicked outside16, Dec 20How to add a new class to an element that already has a class using jQuery ?30, Dec 20How to call base class constructor from child class in TypeScript ?14, Jun 21Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same14, Dec 21Tensorflow.js tf.Sequential class .evaluate() Method29, Jun 21Tensorflow.js tf.Tensor class .buffer() Method25, May 21Tensorflow.js tf.Sequential class .summary() Method29, Jun 21Tensorflow.js tf.LayersModel Class .evaluate() Method21, Jun 21Tensorflow.js tf.data.Dataset class .batch() Method28, May 21Tensorflow.js tf.LayersModel class .save() Method31, Aug 21Tensorflow.js tf.Sequential class .trainOnBatch() Method31, Aug 21Tensorflow.js tf.LayersModel class .fit() Method31, Aug 21Tensorflow.js tf.Sequential Class .add() Method21, Jun 21Tensorflow.js tf.TensorBuffer class .get() Method23, Jul 21Tensorflow.js tf.TensorBuffer Class .set() Method23, Jun 21How to add method to String class in JavaScript?17, Mar 20How to add class to an element without addClass() method in jQuery ?23, Apr 20Tensorflow.js tf.Tensor class .dispose() Method17, Aug 21How to call a parent method from child class in JavaScript?04, Jun 20Node.js stats.isDirectory() Method from fs.Stats Class29, Jun 20Article Contributed By :abhinavjain194@abhinavjain194Vote for difficultyEasy
Normal
Medium
Hard
ExpertImproved By :gabaa406anikakapoorArticle Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?Top 10 Projects For Beginners To Practice HTML and CSS Skills
Tensorflow.js tf.tensor() Function
Tensorflow.js tf.scalar() Function
TenserFlow.js Tensors Creation Complete Reference
Tensorflow.js tf.Tensor class .buffer() Method
Tensorflow.js tf.Tensor class .bufferSync() Method
TensorFlow.js Tensors Classes Complete Reference
Tensorflow.js tf.booleanMaskAsync() Function
Tensorflow.js tf.concat() Function
TensorFlow.js Tensors Transformations Complete Reference
TensorFlow.js Slicing and Joining Complete Reference
Tensorflow.js tf.einsum() Function
Tensorflow.js tf.multinomial() Function
TensorFlow.js Tensor Random Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.input() Function
Tensorflow.js tf.loadGraphModel() Function
Tensorflow.js tf.io.http() Function
TensorFlow.js Models Loading Complete Reference
Tensorflow.js tf.io.copyModel() Function
Tensorflow.js tf.io.listModels() Function
Tensorflow.js tf.io.moveModel() Function
TensorFlow.js Models Management Complete Reference
Tensorflow.js tf.GraphModel Class
Tensorflow.js tf.GraphModel class .save() Method
Tensorflow.js tf.GraphModel class .predict() Method
Tensorflow.js tf.GraphModel class .execute() Method
TensorFlow.js Models Classes Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.layers.elu() Function
Tensorflow.js tf.layers.activation() Function
TensorFlow.js Layers Basic Complete Reference
Tensorflow.js tf.layers.conv1d() Function
TensorFlow.js Layers Convolutional Complete Reference
Tensorflow.js tf.layers.add() Function
TensorFlow.js Layers Merge Complete Reference
Tensorflow.js tf.layers.globalAveragePooling1d() Function
TensorFlow.js Layers Pooling Complete Reference
TensorFlow.js Layers Noise Complete Reference
Tensorflow.js tf.layers.bidirectional() Function
Tensorflow.js tf.layers.timeDistributed() Function
TensorFlow.js Layers Classes Complete Reference
Tensorflow.js tf.layers.zeroPadding2d() Function
Tensorflow.js tf.layers.masking() Function
Tensorflow.js tf.train.Optimizer class .minimize() Method
TensorFlow.js Operations Arithmetic Complete Reference
TensorFlow.js Operations Basic Math Complete Reference
TensorFlow.js Operations Matrices Complete Reference
TensorFlow.js Operations Normalization Complete Reference
TensorFlow.js Operations Images Complete Reference
TensorFlow.js Operations Logical Complete Reference
TensorFlow.js Operations Evaluation Complete Reference
Tensorflow.js tf.cumsum() Function
TensorFlow.js Operations Slicing and Joining Complete Reference
TensorFlow.js Operations Spectral Complete Reference
Tensorflow.js tf.unsortedSegmentSum() Function
Tensorflow.js tf.movingAverage() Function
Tensorflow.js tf.dropout() Function
TensorFlow.js Operations Signal Complete Reference
Tensorflow.js tf.linalg.bandPart() Function
Tensorflow.js tf.linalg.gramSchmidt() Function
Tensorflow.js tf.linalg.qr() Function
TensorFlow.js Operations Sparse Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.grad() Function
Tensorflow.js tf.grads() Function
Tensorflow.js tf.customGrad() Function
TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article

Save Article

Like Article

Tensorflow.js tf.train.Optimizer class .minimize() MethodLast Updated :
03 Sep, 2021Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The .minimize() method executes the given function f() and tries to minimize the scalar output of f() by computing the gradients of y with respect to the given list of trainable variables denoted by varList. If no list is provided, it compute gradients with respect to all trainable variables.Syntax:Optimizer.minimize (f, returnCost?, varList?)Parameters:f (() => tf.Scalar): It specifies the function to execute and whose output to minimize.returnCost (boolean): It specifies whether to return the scalar cost value produced by executing f() or not.varList (tf.Variable[]): It specifies the list of trainable variables.Return value: tf.Scalar | nullExample 1:JavascriptJavascript// Importing tensorflowimport tensorflow as tf   const xs = tf.tensor1d([0, 1, 2]);const ys = tf.tensor1d([1.3, 2.5, 3.7]);   const x = tf.scalar(Math.random()).variable();const y = tf.scalar(Math.random()).variable();   // Define a function f(x, y) = x + y.const f = x => x.add(y);const loss = (pred, label) =>    pred.sub(label).square().mean();   const learningRate = 0.05;   // Create adagrad optimizerconst optimizer =  tf.train.adagrad(learningRate);   // Train the model.for (let i = 0; i < 5; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`x: ${x.dataSync()}, y: ${y.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {console.log(`x: ${i}, pred: ${pred}`);});Outputx: 0.9395854473114014, y: 1.0498266220092773
x: 0, pred: 1.0498266220092773
x: 1, pred: 2.0498266220092773
x: 2, pred: 3.0498266220092773Example 2:JavascriptJavascript// Importing tensorflowimport * as tf from "@tensorflow/tfjs"   const xs = tf.tensor1d([0, 1, 2, 3]);const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);   // Choosing random coefficientsconst a = tf.scalar(Math.random()).variable();const b = tf.scalar(Math.random()).variable();const c = tf.scalar(Math.random()).variable();   // Defining function f = (a*x^2 + b*x + c)const f = x => a.mul(x.square()).add(b.mul(x)).add(c);const loss = (pred, label) => pred.sub(label).square().mean();   // Setting configurations for our optimizerconst learningRate = 0.01;const decay = 0.1;const momentum = 1;const epsilon = 0.5;const centered = true;   // Create the ptimizerconst optimizer = tf.train.rmsprop(learningRate,        decay, momentum, epsilon, centered);   // Train the model.for (let i = 0; i < 8; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`a: ${a.dataSync()},    b: ${b.dataSync()}, c: ${c.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {   console.log(`x: ${i}, pred: ${pred}`);});Outputa: 3.6799352169036865, 
    b: 4.26292610168457, c: 4.544136047363281
x: 0, pred: 4.544136047363281
x: 1, pred: 12.486997604370117
x: 2, pred: 27.789730072021484
x: 3, pred: 50.45233154296875Reference: https://js.tensorflow.org/api/latest/#tf.train.Optimizer.minimizeMy Personal Notes
arrow_drop_upSave

Like0PreviousTensorFlow.js Browser Complete ReferenceNext
Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :Difference between Class.method and Class.prototype.method12, Aug 20jQWidgets jqxMenu minimize() Method21, Oct 21How to find the parent class name with known class in jQuery ?17, Jun 19How to override the CSS properties of a class using another CSS class ?27, Sep 19Toggle class by adding the class name when element is clicked and remove when clicked outside16, Dec 20How to add a new class to an element that already has a class using jQuery ?30, Dec 20How to call base class constructor from child class in TypeScript ?14, Jun 21Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same14, Dec 21Tensorflow.js tf.Sequential class .evaluate() Method29, Jun 21Tensorflow.js tf.Tensor class .buffer() Method25, May 21Tensorflow.js tf.Sequential class .summary() Method29, Jun 21Tensorflow.js tf.LayersModel Class .evaluate() Method21, Jun 21Tensorflow.js tf.data.Dataset class .batch() Method28, May 21Tensorflow.js tf.LayersModel class .save() Method31, Aug 21Tensorflow.js tf.Sequential class .trainOnBatch() Method31, Aug 21Tensorflow.js tf.LayersModel class .fit() Method31, Aug 21Tensorflow.js tf.Sequential Class .add() Method21, Jun 21Tensorflow.js tf.TensorBuffer class .get() Method23, Jul 21Tensorflow.js tf.TensorBuffer Class .set() Method23, Jun 21How to add method to String class in JavaScript?17, Mar 20How to add class to an element without addClass() method in jQuery ?23, Apr 20Tensorflow.js tf.Tensor class .dispose() Method17, Aug 21How to call a parent method from child class in JavaScript?04, Jun 20Node.js stats.isDirectory() Method from fs.Stats Class29, Jun 20Article Contributed By :abhinavjain194@abhinavjain194Vote for difficultyEasy
Normal
Medium
Hard
ExpertImproved By :gabaa406anikakapoorArticle Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?Top 10 Projects For Beginners To Practice HTML and CSS Skills
Tensorflow.js tf.train.momentum() Function
Tensorflow.js tf.train.adagrad() Function
TensorFlow.js Training Optimizers Complete Reference
Tensorflow.js tf.losses.absoluteDifference() Function
Tensorflow.js tf.losses.computeWeightedLoss() Function
Tensorflow.js tf.losses.cosineDistance() Function
TensorFlow.js Training Losses Complete Reference
Tensorflow.js tf.train.Optimizer Class
Tensorflow.js tf.train.Optimizer class .minimize() Method
TensorFlow.js Training Classes Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.time() Function
Tensorflow.js tf.nextFrame() Function
Tensorflow.js tf.profile() Function
TensorFlow.js Performance Memory Complete Reference
Tensorflow.js tf.disposeVariables() Function
Tensorflow.js tf.enableDebugMode() Function
Tensorflow.js tf.enableProdMode() Function
Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics
TensorFlow.js Environment Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.metrics.binaryAccuracy() Function
Tensorflow.js tf.metrics.binaryCrossentropy() Function
Tensorflow.js tf.metrics.categoricalAccuracy() Function
Tensorflow.js tf.metrics.categoricalCrossentropy() Function
Tensorflow.js tf.metrics.cosineProximity() Function
Tensorflow.js tf.metrics.meanSquaredError() Function
Tensorflow.js tf.metrics.precision() Function
Tensorflow.js tf.metrics.recall() Function
Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function
TensorFlow.js Metrics Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.initializers.Initializer Class
Tensorflow.js tf.initializers.constant() Method
Tensorflow.js tf.initializers.glorotNormal() Function
Tensorflow.js tf.initializers.glorotUniform() Function
Tensorflow.js tf.initializers.heNormal() Function
Tensorflow.js tf.initializers.heUniform() Function
TensorFlow.js Initializers Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.regularizers.l1() Function
Tensorflow.js tf.regularizers.l1l2() Function
Tensorflow.js tf.regularizers.l2() Function
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.data.csv() Function
Tensorflow.js tf.data.generator() Function
Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.train.Optimizer class .minimize() MethodTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics
TensorFlow.js Data Creation Complete Reference
Tensorflow.js tf.data.zip() Function
Tensorflow.js tf.data.Dataset class .batch() Method
TensorFlow.js Data Classes Complete References
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.util.assert() Function
Tensorflow.js tf.util.createShuffledIndices() Function
Tensorflow.js tf.decodeString() Function
Tensorflow.js tf.encodeString() Function
Tensorflow.js tf.fetch() Function
Tensorflow.js tf.util.flatten() Function
Tensorflow.js tf.util.now() Function
Tensorflow.js tf.util.shuffle() Function
Tensorflow.js tf.util.shuffleCombo() Function
Tensorflow.js tf.browser.fromPixels() Function
Tensorflow.js tf.browser.fromPixelsAsync() Function
Tensorflow.js tf.browser.toPixels() Function
TensorFlow.js Browser Complete Reference
Tensorflow.js tf.train.Optimizer class .minimize() Method
Tensorflow.js tf.backend() Function
Tensorflow.js tf.getBackend() Function
Tensorflow.js tf.ready() Function
Tensorflow.js tf.registerBackend() Function
Tensorflow.js tf.removeBackend() Function
Tensorflow.js tf.setBackend() Function
Tensorflow.js tf.callbacks.earlyStopping() Function
Last Updated :
03 Sep, 2021
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.
The .minimize() method executes the given function f() and tries to minimize the scalar output of f() by computing the gradients of y with respect to the given list of trainable variables denoted by varList. If no list is provided, it compute gradients with respect to all trainable variables.
Syntax:
Optimizer.minimize (f, returnCost?, varList?)
Parameters:
f (() => tf.Scalar): It specifies the function to execute and whose output to minimize.
returnCost (boolean): It specifies whether to return the scalar cost value produced by executing f() or not.
varList (tf.Variable[]): It specifies the list of trainable variables.
Return value: tf.Scalar | null
Example 1:
Javascript
// Importing tensorflowimport tensorflow as tf   const xs = tf.tensor1d([0, 1, 2]);const ys = tf.tensor1d([1.3, 2.5, 3.7]);   const x = tf.scalar(Math.random()).variable();const y = tf.scalar(Math.random()).variable();   // Define a function f(x, y) = x + y.const f = x => x.add(y);const loss = (pred, label) =>    pred.sub(label).square().mean();   const learningRate = 0.05;   // Create adagrad optimizerconst optimizer =  tf.train.adagrad(learningRate);   // Train the model.for (let i = 0; i < 5; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`x: ${x.dataSync()}, y: ${y.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {console.log(`x: ${i}, pred: ${pred}`);});
Output
x: 0.9395854473114014, y: 1.0498266220092773
x: 0, pred: 1.0498266220092773
x: 1, pred: 2.0498266220092773
x: 2, pred: 3.0498266220092773
Example 2:
Javascript
// Importing tensorflowimport * as tf from "@tensorflow/tfjs"   const xs = tf.tensor1d([0, 1, 2, 3]);const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);   // Choosing random coefficientsconst a = tf.scalar(Math.random()).variable();const b = tf.scalar(Math.random()).variable();const c = tf.scalar(Math.random()).variable();   // Defining function f = (a*x^2 + b*x + c)const f = x => a.mul(x.square()).add(b.mul(x)).add(c);const loss = (pred, label) => pred.sub(label).square().mean();   // Setting configurations for our optimizerconst learningRate = 0.01;const decay = 0.1;const momentum = 1;const epsilon = 0.5;const centered = true;   // Create the ptimizerconst optimizer = tf.train.rmsprop(learningRate,        decay, momentum, epsilon, centered);   // Train the model.for (let i = 0; i < 8; i++) {   optimizer.minimize(() => loss(f(xs), ys));}   // Make predictions.console.log(`a: ${a.dataSync()},    b: ${b.dataSync()}, c: ${c.dataSync()}`);const preds = f(xs).dataSync();preds.forEach((pred, i) => {   console.log(`x: ${i}, pred: ${pred}`);});
Output
a: 3.6799352169036865, 
    b: 4.26292610168457, c: 4.544136047363281
x: 0, pred: 4.544136047363281
x: 1, pred: 12.486997604370117
x: 2, pred: 27.789730072021484
x: 3, pred: 50.45233154296875
Reference: https://js.tensorflow.org/api/latest/#tf.train.Optimizer.minimize
gabaa406
anikakapoor
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills