KotlinDL - High-level Deep Learning Framework written in Kotlin and inspired by Keras

Overview

Оригинальный репозиторий
https://github.com/JetBrains/KotlinDL

KotlinDL: High-level Deep Learning API in Kotlin official JetBrains project

Kotlin Slack channel

KotlinDL is a high-level Deep Learning API written in Kotlin and inspired by Keras. Under the hood, it uses TensorFlow Java API and ONNX Runtime API for Java. KotlinDL offers simple APIs for training deep learning models from scratch, importing existing Keras and ONNX models for inference, and leveraging transfer learning for tailoring existing pre-trained models to your tasks.

This project aims to make Deep Learning easier for JVM developers and simplify deploying deep learning models in JVM production environments.

Here's an example of what a classic convolutional neural network LeNet would look like in KotlinDL:

private const val EPOCHS = 3
private const val TRAINING_BATCH_SIZE = 1000
private const val NUM_CHANNELS = 1L
private const val IMAGE_SIZE = 28L
private const val SEED = 12L
private const val TEST_BATCH_SIZE = 1000

private val lenet5Classic = Sequential.of(
    Input(
        IMAGE_SIZE,
        IMAGE_SIZE,
        NUM_CHANNELS
    ),
    Conv2D(
        filters = 6,
        kernelSize = intArrayOf(5, 5),
        strides = intArrayOf(1, 1, 1, 1),
        activation = Activations.Tanh,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Zeros(),
        padding = ConvPadding.SAME
    ),
    AvgPool2D(
        poolSize = intArrayOf(1, 2, 2, 1),
        strides = intArrayOf(1, 2, 2, 1),
        padding = ConvPadding.VALID
    ),
    Conv2D(
        filters = 16,
        kernelSize = intArrayOf(5, 5),
        strides = intArrayOf(1, 1, 1, 1),
        activation = Activations.Tanh,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Zeros(),
        padding = ConvPadding.SAME
    ),
    AvgPool2D(
        poolSize = intArrayOf(1, 2, 2, 1),
        strides = intArrayOf(1, 2, 2, 1),
        padding = ConvPadding.VALID
    ),
    Flatten(), // 3136
    Dense(
        outputSize = 120,
        activation = Activations.Tanh,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Constant(0.1f)
    ),
    Dense(
        outputSize = 84,
        activation = Activations.Tanh,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Constant(0.1f)
    ),
    Dense(
        outputSize = NUMBER_OF_CLASSES,
        activation = Activations.Linear,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Constant(0.1f)
    )
)


fun main() {
    val (train, test) = mnist()
    
    lenet5Classic.use {
        it.compile(
            optimizer = Adam(clipGradient = ClipGradientByValue(0.1f)),
            loss = Losses.SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS,
            metric = Metrics.ACCURACY
        )
    
        it.logSummary()
    
        it.fit(dataset = train, epochs = EPOCHS, batchSize = TRAINING_BATCH_SIZE)
    
        val accuracy = it.evaluate(dataset = test, batchSize = TEST_BATCH_SIZE).metrics[Metrics.ACCURACY]
    
        println("Accuracy: $accuracy")
    }
}

Table of Contents

TensorFlow Engine

KotlinDL is built on top of the TensorFlow 1.15 Java API. The Java API for TensorFlow 2.+ has recently had its first public release, and this project will be switching to it in the nearest future. This, however, does not affect the high-level API.

How to configure KotlinDL in your project

To use the full power of KotlinDL (including the onnx and visualization modules) in your project, add the following dependencies to your build.gradle file:

   repositories {
      mavenCentral()
   }
   
   dependencies {
       implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-api:[KOTLIN-DL-VERSION]'
       implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-onnx:[KOTLIN-DL-VERSION]'
       implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-visualization:[KOTLIN-DL-VERSION]'
   }

Or add just one dependency if you don’t need ONNX and visualization:

   repositories {
      mavenCentral()
   }
   
   dependencies {
       implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-api:[KOTLIN-DL-VERSION]'
   }

The latest KotlinDL version is 0.3.0. The latest stable KotlinDL version is 0.3.0.

For more details, as well as for pom.xml and build.gradle.kts examples, please refer to the Quick Start Guide.

Working with KotlinDL in Jupyter Notebook

You can work with KotlinDL interactively in Jupyter Notebook with the Kotlin kernel. To do so, add the following dependency in your notebook:

   @file:DependsOn("org.jetbrains.kotlinx:kotlin-deeplearning-api:[KOTLIN-DL-VERSION]")

For more details on installing Jupyter Notebook and adding the Kotlin kernel, check out the Quick Start Guide.

Documentation

Examples and tutorials

You do not need to have any prior deep learning experience to start using KotlinDL. We are working on including extensive documentation to help you get started. At this point, please feel free to check out the following tutorials we have prepared:

For more inspiration, take a look at the code examples in this repo.

Running KotlinDL on GPU

To enable the training and inference on a GPU, please read this TensorFlow GPU Support page and install the CUDA framework to enable calculations on a GPU device.

Note that only NVIDIA devices are supported.

You will also need to add the following dependencies in your project if you wish to leverage a GPU:

  compile 'org.tensorflow:libtensorflow:1.15.0'_
  compile 'org.tensorflow:libtensorflow_jni_gpu:1.15.0'_

On Windows, the following distributions are required:

Logging

By default, the API module uses the kotlin-logging library to organize the logging process separately from the specific logger implementation.

You could use any widely known JVM logging library with a Simple Logging Facade for Java (SLF4J) implementation such as Logback or Log4j/Log4j2.

You will also need to add the following dependencies and configuration file log4j2.xml to the src/resource folder in your project if you wish to use log4j2:

  implementation 'org.apache.logging.log4j:log4j-api:2.16.0'
  implementation 'org.apache.logging.log4j:log4j-core:2.16.0'
  implementation 'org.apache.logging.log4j:log4j-slf4j-impl:2.16.0'
<Configuration status="WARN">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="STDOUT" level="DEBUG"/>
        </Root>
        <Logger name="io.jhdf" level="off" additivity="true">
            <appender-ref ref="STDOUT" />
        </Logger>
    </Loggers>
</Configuration>

If you wish to use Logback, include the following dependency and configuration file logback.xml to src/resource folder in your project

  compile 'ch.qos.logback:logback-classic:1.2.3'
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

These configuration files can be found in the examples module.

Fat Jar issue

There is a known Stack Overflow question and TensorFlow issue with Fat Jar creation and execution on Amazon EC2 instances.

java.lang.UnsatisfiedLinkError: /tmp/tensorflow_native_libraries-1562914806051-0/libtensorflow_jni.so: libtensorflow_framework.so.1: cannot open shared object file: No such file or directory

Despite the fact that the bug describing this problem was closed in the release of TensorFlow 1.14, it was not fully fixed and required an additional line in the build script.

One simple solution is to add a TensorFlow version specification to the Jar's Manifest. Below you can find an example of a Gradle build task for Fat Jar creation.

// build.gradle

task fatJar(type: Jar) {
    manifest {
        attributes 'Implementation-Version': '1.15'
    }
    classifier = 'all'
    from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}
// build.gradle.kts

plugins {
    kotlin("jvm") version "1.5.31"
    id("com.github.johnrengelman.shadow") version "7.0.0"
}

tasks{
    shadowJar {
        manifest {
            attributes(Pair("Main-Class", "MainKt"))
            attributes(Pair("Implementation-Version", "1.15"))
        }
    }
}

Limitations

Currently, only a limited set of deep learning architectures are supported. Here's the list of available layers:

  • Input
  • Flatten
  • Dense
  • Dropout
  • Conv2D
  • MaxPool2D
  • AvgPool2D
  • BatchNorm
  • ActivationLayer
  • DepthwiseConv2D
  • SeparableConv2D
  • Merge layers (Add, Subtract, Multiply, Average, Concatenate, Maximum, Minimum)
  • GlobalAvgPool2D
  • GlobalMaxPool2D
  • Cropping2D
  • UpSampling2D
  • ZeroPadding2D
  • Reshape
  • Permute
  • RepeatVector
  • Softmax
  • LeakyReLU
  • PReLU
  • ELU
  • ThresholdedReLU
  • Conv1D
  • MaxPooling1D
  • AveragePooling1D
  • GlobalMaxPooling1D
  • GlobalAveragePooling1D
  • UpSampling1D
  • Cropping1D
  • Conv3D
  • MaxPooling3D
  • AveragePooling3D
  • GlobalAveragePooling3D
  • GlobalMaxPool3D
  • Cropping3D

KotlinDL supports model inference in JVM backend applications. Android support is coming in later releases.

Contributing

Read the Contributing Guidelines.

Reporting issues/Support

Please use GitHub issues for filing feature requests and bug reports. You are also welcome to join the #kotlindl channel in the Kotlin Slack.

Code of Conduct

This project and the corresponding community are governed by the JetBrains Open Source and Community Code of Conduct. Please make sure you read it.

License

KotlinDL is licensed under the Apache 2.0 License.

You might also like...
an open source algorithmic trading framework written in Kotlin for anyone serious about algo-trading
an open source algorithmic trading framework written in Kotlin for anyone serious about algo-trading

Roboquant Roboquant is an algorithmic trading platform that is fast and flexible while at the same time strives to be easy to use. It is fully open so

LittleKt - An OpenGL game framework written in Kotlin

LittleKt - A 2D game framework written in Kotlin Currently in development. Littl

🎓 Learning Kotlin Coroutines for Android by example. 🚀 Sample implementations for real-world Android use cases. 🛠 Unit tests included!
🎓 Learning Kotlin Coroutines for Android by example. 🚀 Sample implementations for real-world Android use cases. 🛠 Unit tests included!

Kotlin Coroutines - Use Cases on Android 🎓 Learning Kotlin Coroutines for Android by example. 🚀 Sample implementations for real-world Android use ca

A learning project which focuses on designing an OTP flow and use of various components of Android efficiently
A learning project which focuses on designing an OTP flow and use of various components of Android efficiently

Otp Demo A learning project which focuses on designing an OTP flow using Firebase. Article: https://saurabhpant.medium.com/otp-login-using-firebase-hi

Spring boot cloud tool usage trail and learning project

Spring boot cloud tool usage trail and learning project Todo Maven based multi-p

Kendo is like a long night, and learning is similar

Sword Come 🌈 For English vocabulary analysis and sentence analysis in natural language, model training, intelligent response and emotion analysis rea

EduApp is a mini e-learning platform based on udemy's public api. It has 4 main navigation destinations (Home, Search, Wishlist, Cart). Users can search courses from different categories and get real-time results from the api using Chips for a smooth filtering experience. It has different theme for dark mode. Collection of code samples for learning Android Fundamentals.
Collection of code samples for learning Android Fundamentals.

Android Tutorials Collection of code samples for learning Android Fundamentals and lessons in KOTLIN from YOUTUBE. The layout of Android Applications

WordGuess - A portuguese game inspired in the world fever wordle game
WordGuess - A portuguese game inspired in the world fever wordle game

WordGuess WordGuess is a portuguese game inspired in the world fever wordle game

Owner
Temur Yunusov
Temur Yunusov, skype timur9996
Temur Yunusov
A deep learning based mobile application for the multi-class classification of pneumonia into three categories via Chest X-rays

PneumoniaClassifier A deep learning based mobile application for the multi-class classification of pneumonia into three categories via Chest X-rays. W

Timilehin Aregbesola 2 Dec 15, 2021
An investigation and comparison between Kotlin and Java on an engineering level

An investigation and comparison between Kotlin and Java on an engineering level. Since beauty is in the eye of the beholder, this repository is not meant to evaluate Java or Kotlin on an aesthetic level.

João Filipe Sabino Esperancinha 13 Dec 3, 2022
Examples for using Kotlin at a basic level for Android application development.

Kotlin Android Jetpack Basics Ejemplos para usar Kotlin a nivel básico para el desarrollo de aplicaciones Android. Kotlin Android Jetpack Basics Acerc

José Luis González Sánchez 2 Jun 28, 2022
High performance and fully asynchronous pulsar client with Kotlin and Vert.x

pulsarkt High performance pulsar client with Kotlin and Vert.x Features Basic Producer/Consumer API Partitioned topics Batching Chunking Compression T

null 1 Nov 5, 2021
Service exposes sensitive administration APIs to initialize and set lower level of Slurpanize infrastructure

slurpanize-baker Project This project uses Quarkus, the Supersonic Subatomic Java Framework. If you want to learn more about Quarkus, please visit its

Slurpanize by Tetracube RED 0 Nov 25, 2021
An IoT based automatic alerting device that consists of laser and a precise Light Dependent Resistor to detect the laser which is employed to constantly monitor the fluid level

An IoT based automatic alerting device that consists of laser and a precise Light Dependent Resistor to detect the laser which is employed to constantly monitor the fluid level. When the fluid level is below the critical level which will be defined by laser, it will alert the patient through buzzer, nurses and doctors through mobile app and the …

null 0 Feb 12, 2022
A high performance dex deobfuscator library.

DexKit-Android README|中文文档 This repository update has been terminated, Please use DexKit in the future, it's easier to use. A high performance dex deo

null 39 Oct 9, 2022
Spring-kotlin - Learning API Rest with Kotlin, Spring and PostgreSQL

Kotlin, Spring, PostgreSQL and Liquibase Database Migrations Learning Kotlin for

Andre L S Ferreira 2 Feb 14, 2022
Learn-kotlin - Learning more about Kotlin in various content

Kotlin study roadmap https://kotlinlang.org/docs/reference/ Getting Started Basi

Danilo Silva 0 Jan 7, 2022
Learning Project (Story App) For Applying Android Architecture Components And Clean Architecture Using MVVM With Kotlin

Learning Project (Story App) For Applying Android Architecture Components And Clean Architecture Using MVVM With Kotlin. Implemented by Clean Architecture, Hilt, MVVM, LiveData, Coroutines, Retrofit2, Glide

Samad Talukder 4 Sep 27, 2022