{"id":139,"date":"2024-09-13T13:59:00","date_gmt":"2024-09-13T11:59:00","guid":{"rendered":"https:\/\/codeswarm.io\/?p=139"},"modified":"2026-07-19T14:11:53","modified_gmt":"2026-07-19T12:11:53","slug":"how-to-create-neural-network-with-scala","status":"publish","type":"post","link":"https:\/\/codeswarm.io\/?p=139","title":{"rendered":"How to create neural network with Scala?"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Creating a neural network in Scala typically involves either building the network from scratch using linear algebra or leveraging libraries like <strong>Breeze<\/strong> or <strong>DeepLearning4j<\/strong> (which has Scala bindings). Here\u2019s a basic outline of how you could create a neural network in Scala:<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Dependencies<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">First, we\u2019ll need some libraries for mathematical operations. <strong>Using <code>sbt<\/code> (Simple Build Tool)<\/strong> we can add this to our <code>build.sbt<\/code> file:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"scala\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">libraryDependencies ++= Seq(\n  \"org.scalanlp\" %% \"breeze\" % \"1.2\",\n  \"org.deeplearning4j\" % \"deeplearning4j-core\" % \"1.0.0-beta7\"\n)<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Creating a neural network from scratch<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Here\u2019s a very simplified feed-forward neural network (without any optimization or training) built from scratch using Breeze for matrix operations:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Input layer, weights, and biases initialization<\/strong> \u2013 we need a way to store the weights and biases between layers.<\/li>\n\n\n\n<li><strong>Activation functions \u2013<\/strong>implement a simple activation function (e.g., sigmoid).<\/li>\n\n\n\n<li><strong>Feedforward<\/strong> \u2013 implement the feedforward process where the input data is passed through the network.<\/li>\n\n\n\n<li><strong>Backpropagation<\/strong> (if we need training).<\/li>\n<\/ul>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"scala\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import breeze.linalg._\nimport breeze.numerics._\n\/\/ Activation function (sigmoid)\ndef sigmoid(x: DenseMatrix[Double]): DenseMatrix[Double] = {\n  1.0 \/:\/ (exp(-x) + 1.0)\n}\n\/\/ Derivative of sigmoid\ndef sigmoidDerivative(x: DenseMatrix[Double]): DenseMatrix[Double] = {\n  x :* (1.0 - x)\n}\n\/\/ Feedforward step\ndef feedForward(input: DenseMatrix[Double], weights: Seq[DenseMatrix[Double]], biases: Seq[DenseMatrix[Double]]): Seq[DenseMatrix[Double]] = {\n  var activations = Seq(input)\n  for (i &lt;- weights.indices) {\n    val z = (weights(i) * activations.last) + biases(i)\n    val a = sigmoid(z)\n    activations = activations :+ a\n  }\n  activations\n}\n\/\/ Backpropagation (simplified version for gradient calculation, not full)\ndef backpropagation(expected: DenseMatrix[Double], activations: Seq[DenseMatrix[Double]], weights: Seq[DenseMatrix[Double]]): (Seq[DenseMatrix[Double]], Seq[DenseMatrix[Double]]) = {\n  val error = activations.last - expected\n  \/\/ Backpropagation steps here (update weights and biases)\n  (weights, activations)\n}\n\/\/ Example usage\nval inputLayerSize = 2\nval hiddenLayerSize = 3\nval outputLayerSize = 1\n\/\/ Initialize weights and biases randomly\nval weights1 = DenseMatrix.rand[Double](hiddenLayerSize, inputLayerSize)\nval weights2 = DenseMatrix.rand[Double](outputLayerSize, hiddenLayerSize)\nval bias1 = DenseMatrix.rand[Double](hiddenLayerSize, 1)\nval bias2 = DenseMatrix.rand[Double](outputLayerSize, 1)\n\/\/ Input data\nval X = DenseMatrix((0.0, 1.0), (1.0, 0.0)) \/\/ 2 input features\nval Y = DenseMatrix(1.0, 0.0)               \/\/ Expected output\n\/\/ Feedforward\nval weights = Seq(weights1, weights2)\nval biases = Seq(bias1, bias2)\nval activations = feedForward(X, weights, biases)\n\/\/ Print activations\nactivations.foreach(println)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The first step is importing the necessary libraries. Here, we use <strong>Breeze<\/strong>, a Scala library that provides powerful tools for numerical processing like linear algebra, which is essential for machine learning.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>breeze.linalg._<\/code><\/strong>: This gives us tools for handling matrices and vectors (like <code>DenseMatrix<\/code>, which is similar to a 2D array or matrix),<\/li>\n\n\n\n<li><strong><code>breeze.numerics._<\/code><\/strong>: This provides basic mathematical functions like <code>exp<\/code> (exponentiation).<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In this neural network, we use the <strong>sigmoid<\/strong> function as the activation function. The sigmoid squashes input values between 0 and 1, which is useful in controlling the output of each neuron in a neural network.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"scala\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def sigmoid(x: DenseMatrix[Double]): DenseMatrix[Double] = {\n  1.0 \/:\/ (exp(-x) + 1.0)\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <strong>sigmoid derivative<\/strong> is used for calculating the gradient during backpropagation. The derivative is needed to adjust weights and biases during training.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"scala\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def sigmoidDerivative(x: DenseMatrix[Double]): DenseMatrix[Double] = {\n  x :* (1.0 - x)\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <strong>feedforward<\/strong> process is where the input passes through the network layer by layer to compute the output. At each layer, we multiply the input by the weights, add the biases, and then apply the activation function (sigmoid in this case).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Steps in <code>feedForward<\/code>:<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Input<\/strong>: Start with the input as the initial activation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>For Each Layer<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>calculate the <strong>weighted sum<\/strong> (<code>z = W * a + b<\/code>), where <code>W<\/code> is the weight matrix, <code>a<\/code> is the activation from the previous layer, and <code>b<\/code> is the bias,<\/li>\n\n\n\n<li>apply the <strong>sigmoid activation function<\/strong> to <code>z<\/code> to get the next activation,<\/li>\n\n\n\n<li>add the new activation to the sequence of activations.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This is a placeholder for the <strong>backpropagation<\/strong> step. Backpropagation is a method used to calculate the gradient (partial derivatives) needed for adjusting the weights and biases during training, based on the difference between predicted and actual values.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Breakdown<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Neural Network Structure<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Input layer size<\/strong>: 2 neurons (for 2 input features).<\/li>\n\n\n\n<li><strong>Hidden layer size<\/strong>: 3 neurons.<\/li>\n\n\n\n<li><strong>Output layer size<\/strong>: 1 neuron (since we are outputting 1 value).<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Random Weights and Biases<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>weights1<\/code>: Matrix of random values for the first layer, with size <code>[3, 2]<\/code> (3 neurons, 2 inputs),<\/li>\n\n\n\n<li><code>weights2<\/code>: Matrix of random values for the second layer, with size <code>[1, 3]<\/code> (1 output, 3 neurons in the hidden layer),<\/li>\n\n\n\n<li><code>bias1<\/code> and <code>bias2<\/code>: Random biases for the layers.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Input Data<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>X<\/code> represents 2 inputs: <code>(0.0, 1.0)<\/code> and <code>(1.0, 0.0)<\/code>.<\/li>\n\n\n\n<li><code>Y<\/code> is the expected output: <code>1.0, 0.0<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Feedforward Execution<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>feedForward(X, weights, biases)<\/code> computes the activations of each layer.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Printing the Activations<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>After passing through the network, the activations of each layer are printed.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Using libraries<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If we use <strong>DeepLearning4j<\/strong> (DL4J), the code will be simpler since the library abstracts most of the math and logic. We can build a neural network like this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"scala\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import org.deeplearning4j.nn.conf._\nimport org.deeplearning4j.nn.conf.layers._\nimport org.deeplearning4j.nn.multilayer._\nimport org.nd4j.linalg.factory.Nd4j\nimport org.nd4j.linalg.dataset.api.iterator.DataSetIterator\nimport org.deeplearning4j.datasets.iterator.impl.IrisDataSetIterator\n\/\/ Build the configuration\nval conf: MultiLayerConfiguration = new NeuralNetConfiguration.Builder()\n  .seed(123)\n  .updater(new Nesterovs(0.1, 0.9))\n  .list()\n  .layer(0, new DenseLayer.Builder().nIn(4).nOut(3)\n    .activation(\"relu\")\n    .build())\n  .layer(1, new OutputLayer.Builder(LossFunctions.LossFunction.MCXENT)\n    .activation(\"softmax\")\n    .nIn(3).nOut(3)\n    .build())\n  .build()\n\/\/ Initialize the model\nval model = new MultiLayerNetwork(conf)\nmodel.init()\n\/\/ Load dataset (Iris for simplicity)\nval irisIter: DataSetIterator = new IrisDataSetIterator(150, 150)\n\/\/ Train the model\nfor (i &lt;- 0 until 1000) {\n  model.fit(irisIter)\n}\n\/\/ Evaluate or test model<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This code demonstrates how to build a simple neural network using the basic principles of feedforward and (partially) backpropagation. Here\u2019s what happens:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>The input data<\/strong> is passed through the network, layer by layer, with weights and biases applied.<\/li>\n\n\n\n<li><strong>The sigmoid<\/strong> activation function ensures the values are normalized between 0 and 1.<\/li>\n\n\n\n<li>Although the<strong> backpropagation <\/strong>logic is not fully implemented, this structure would allow for training once it is in place.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This example is highly simplified, but it provides a foundation for building more complex networks with multiple hidden layers, different activation functions, and learning algorithms.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Creating a neural network in Scala typically involves either building the network from scratch using linear algebra or leveraging libraries like Breeze or DeepLearning4j (which has Scala bindings). Here\u2019s a basic outline of how you could create a neural network in Scala: Dependencies First, we\u2019ll need some libraries for mathematical operations. Using sbt (Simple Build &hellip; <a href=\"https:\/\/codeswarm.io\/?p=139\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">How to create neural network with Scala?<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27,23],"tags":[19],"class_list":["post-139","post","type-post","status-publish","format-standard","hentry","category-ai","category-programming","tag-scala"],"_links":{"self":[{"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/posts\/139","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeswarm.io\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=139"}],"version-history":[{"count":6,"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/posts\/139\/revisions"}],"predecessor-version":[{"id":145,"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/posts\/139\/revisions\/145"}],"wp:attachment":[{"href":"https:\/\/codeswarm.io\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=139"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeswarm.io\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=139"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeswarm.io\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=139"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}