Skip to content

Instantly share code, notes, and snippets.

@TerrorJack
Last active August 28, 2017 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TerrorJack/cdd9cc5adc82fc86abf8b4c72cd26e76 to your computer and use it in GitHub Desktop.
Save TerrorJack/cdd9cc5adc82fc86abf8b4c72cd26e76 to your computer and use it in GitHub Desktop.
CNN.sc
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CNN\n",
"\n",
"This plugin provides a standalone implementation of a Convolutional Neural Network."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import $ivy.`com.thoughtworks.each::each:3.3.1`\n",
"import $ivy.`com.thoughtworks.deeplearning::plugins-builtins:2.0.0`\n",
"\n",
"import scala.concurrent.ExecutionContext.Implicits.global\n",
"import org.nd4j.linalg.api.ndarray.INDArray\n",
"import org.nd4j.linalg.convolution.Convolution\n",
"import org.nd4j.linalg.util.ArrayUtil\n",
"import org.nd4j.linalg.factory.Nd4j\n",
"import org.nd4j.linalg.api.ops.impl.transforms.IsMax\n",
"import scalaz.syntax.all._\n",
"import com.thoughtworks.raii.shared._\n",
"import com.thoughtworks.raii.asynchronous._\n",
"import com.thoughtworks.feature.ImplicitApply\n",
"import com.thoughtworks.each.Monadic._\n",
"import com.thoughtworks.feature.Factory\n",
"import com.thoughtworks.deeplearning.DeepLearning\n",
"import com.thoughtworks.deeplearning.plugins.ImplicitsSingleton\n",
"import com.thoughtworks.deeplearning.plugins.INDArrayLayers\n",
"import com.thoughtworks.deeplearning.plugins.Operators\n",
"import com.thoughtworks.deeplearning.plugins.Training\n",
"import com.thoughtworks.deeplearning.plugins.Builtins"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"interp.load(scala.io.Source.fromURL(new java.net.URL(\"https://gist.githubusercontent.com/TerrorJack/cdd9cc5adc82fc86abf8b4c72cd26e76/raw/1f15523ee4b5a7fcc7e7317ae34ba09be207a62a/CNN.sc\")).mkString)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"interp.load(\"\"\"\n",
" val hyperparameters = Factory[Builtins with CNNs].newInstance()\n",
"\"\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### For sbt projects"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"// build.sbt\n",
"libraryDependencies += \"com.thoughtworks.deeplearning\" %% \"plugins-builtins\" % \"latest.release\"\n",
"\n",
"addCompilerPlugin(\"com.thoughtworks.import\" %% \"import\" % \"latest.release\")\n",
"\n",
"// XXX.scala\n",
"import $exec.`https://gist.githubusercontent.com/TerrorJack/cdd9cc5adc82fc86abf8b4c72cd26e76/raw/1f15523ee4b5a7fcc7e7317ae34ba09be207a62a/CNN.sc`\n",
"\n",
"import scala.concurrent.ExecutionContext.Implicits.global\n",
"import org.nd4j.linalg.api.ndarray.INDArray\n",
"import org.nd4j.linalg.convolution.Convolution\n",
"import org.nd4j.linalg.util.ArrayUtil\n",
"import org.nd4j.linalg.factory.Nd4j\n",
"import org.nd4j.linalg.api.ops.impl.transforms.IsMax\n",
"import scalaz.syntax.all._\n",
"import com.thoughtworks.raii.shared._\n",
"import com.thoughtworks.raii.asynchronous._\n",
"import com.thoughtworks.feature.ImplicitApply\n",
"import com.thoughtworks.each.Monadic._\n",
"import com.thoughtworks.feature.Factory\n",
"import com.thoughtworks.deeplearning.DeepLearning\n",
"import com.thoughtworks.deeplearning.plugins.ImplicitsSingleton\n",
"import com.thoughtworks.deeplearning.plugins.INDArrayLayers\n",
"import com.thoughtworks.deeplearning.plugins.Operators\n",
"import com.thoughtworks.deeplearning.plugins.Training\n",
"import com.thoughtworks.deeplearning.plugins.Builtins\n",
" \n",
"val hyperparameters = Factory[Builtins with CNNs].newInstance()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Scala",
"language": "scala",
"name": "scala"
},
"language_info": {
"codemirror_mode": "text/x-scala",
"file_extension": ".scala",
"mimetype": "text/x-scala",
"name": "scala211",
"nbconvert_exporter": "script",
"pygments_lexer": "scala",
"version": "2.11.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
trait CNNs extends INDArrayLayers with ImplicitsSingleton with Training with Operators {
trait ImplicitsApi
extends super[INDArrayLayers].ImplicitsApi
with super[Training].ImplicitsApi
with super[Operators].ImplicitsApi
type Implicits <: ImplicitsApi
private def toArray(tuple2: (Int, Int)): Array[Int] = {
val (one, two) = tuple2
Array(one, two)
}
def im2col[Operand0, Out <: INDArrayLayer](operand0: Operand0,
kernel: (Int, Int),
stride: (Int, Int),
padding: (Int, Int))(
implicit deepLearning: DeepLearning.Aux[Operand0, INDArray, INDArray],
layerImplicits: ImplicitApply.Aux[indArrayPartialApplyRawForward.Rest, Out]): Out = {
INDArrayLayer.unary(operand0) { data0: INDArray =>
val shape0 = data0.shape
val strideArray = toArray(stride)
val paddingArray = toArray(padding)
val outputData = Convolution.im2col(data0, toArray(kernel), strideArray, paddingArray)
val delta0 = { outputDelta: INDArray =>
Convolution.col2im(outputDelta, strideArray, paddingArray, shape0(2), shape0(3))
}
(outputData, delta0)
}
}
@inline
def conv2d[Input, Weight, Bias, Out <: INDArrayLayer](input: Input,
weight: Weight,
bias: Bias,
kernel: (Int, Int),
stride: (Int, Int),
padding: (Int, Int))(
implicit inputDeepLearning: DeepLearning.Aux[Input, INDArray, INDArray],
weightDeepLearning: DeepLearning.Aux[Weight, INDArray, INDArray],
biasDeepLearning: DeepLearning.Aux[Bias, INDArray, INDArray],
layerImplicits: ImplicitApply.Aux[indArrayPartialApplyRawForward.Rest, Out]): Out = {
import implicits._
INDArrayLayer(monadic[Do] {
val inputShape = input.forward.each.data.shape
val numberOfImages = inputShape(0)
val depth = inputShape(1)
val height = inputShape(2)
val width = inputShape(3)
val numberOfKernels = weight.forward.each.data.shape.head
val col = im2col(input, kernel, stride, padding)
val permutedCol = col.permute(0, 4, 5, 1, 2, 3)
val depthKernelKernel = depth * kernel._1 * kernel._2
val operandCol2d = permutedCol.reshape(numberOfImages * height * width, depthKernelKernel)
val reshapedWeight = weight.reshape(numberOfKernels, depthKernelKernel)
val permutedWeight = reshapedWeight.permute(1, 0)
val dotResult = operandCol2d dot permutedWeight
val plusResult = dotResult + bias
val reshapeResult = plusResult.reshape(numberOfImages, height, width, numberOfKernels)
reshapeResult.permute(0, 3, 1, 2).forward.each
})
}
@inline
def maxPool[Operand0, Out <: INDArrayLayer](operand0: Operand0, poolSize: (Int, Int))(
implicit deepLearning: DeepLearning.Aux[Operand0, INDArray, INDArray],
layerImplicits: ImplicitApply.Aux[indArrayPartialApplyRawForward.Rest, Out]): Out = {
INDArrayLayer.unary(operand0) { data0: INDArray =>
val shape0 = data0.shape
val kernelAndStrideSize: Array[Int] = toArray(poolSize)
val preMaxPool: INDArray =
Convolution
.im2col(data0, kernelAndStrideSize, kernelAndStrideSize, Array(0, 0))
.permute(0, 1, 4, 5, 2, 3)
val preShape: Seq[Int] = preMaxPool.shape().toSeq
val lastDimensionSize: Int = preShape.takeRight(2).product
val reshapedPreMaxPool: INDArray = preMaxPool
.reshape(preShape.take(preShape.length - 2) :+ lastDimensionSize: _*)
val outputData = reshapedPreMaxPool.max(4)
val delta0 = { outputDelta: INDArray =>
val a = reshapedPreMaxPool
val upStreamDup = a.dup()
val rows = ArrayUtil.prod(a.length())
val isMax: INDArray = Nd4j.getExecutioner
.execAndReturn(new IsMax(upStreamDup, 4))
.reshape(preShape.take(preShape.length - 2) :+ poolSize._2 :+ poolSize._1: _*)
.permute(0, 1, 2, 4, 3, 5)
.reshape('c', rows, 1)
val outputDelta1d = {
outputDelta
.repeat(-1, poolSize._1)
.permute(1, 0, 3, 2)
.repeat(-1, poolSize._2)
.permute(1, 0, 3, 2)
.reshape('c', shape0.product, 1)
}
isMax
.muliColumnVector(outputDelta1d)
.reshape(shape0: _*)
}
(outputData, delta0)
}
}
}
MIT License
Copyright (c) 2017 ThoughtWorks Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment