页面简介
Kivy is a Python library that facilitates the creation of cross-platform applications. Let us develop an android ml app with kivymd.
正文摘录
India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder d : h : m : s Get Details Interview PrepCareerGenAIPrompt EnggChatGPTLLMLangchainRAGAI AgentsMachine LearningDeep LearningGenAI ToolsLLMOpsPythonNLPSQLAIML Projects Reading list Introduction to Deep LearningWhat is Deep Learning?DL vs ML vs AIWhy Deep Learning is So Popular? Feed Forward NetworksApplications of Deep LearningMulti Layer PerceptronVisualizing the Neural NetworkUnderstanding Decision BoundaryForward and Backward Propagation Intuition Gradient DescentGradient Descent AlgorithmVariants of Gradient Descent Algorithm Loss FunctionIntroduction to Loss FunctionBinary and Categorical Cross Entropy Activation FunctionsWhy Do We Need Activation Functions?Linear Activation FunctionSigmoid and Tanh FunctionSoftmaxHow to Select Right Activation Function? Introduction to Neural networksPerceptronWeights in PerceptronIntroduction to Artificial Neural Network Forward and Backward PropagationUnderstanding Forward Propagation MathematicallyUnderstand Backward Propagation MathematicallyImplementing Neural Networks in Python OptimizersProblems with Gradient DescentGradient Descent with MomentumAdagrad and Adadelta Learning Rate SchedulersIntroduction to Learning Rate Schedulers NN on Structured DataOverview of Deep Learning FrameworksImplementing Neural Networks using KerasFunctional API in KerasImplementing Neural Networks using KerasHyperparameter Tuning of MLP in Keras Improving the Deep Learning ModelUnderstanding Early stoppingUnderstanding DropoutVanishing and Exploding GradientsWeights Initialization TechniquesImplementing Weight Initializing TechniquesBatch NormalizationImage Augmentation TechniquesImage Generator and Fit GeneratorModel CheckpointingImplementing Model CheckpointingDealing with Class ImbalanceEnsemble Deep Learning Deep Learning Model OptimizationIntroduction to GPU and TPUTensorRT Unsupervised Deep LearningIntroduction to Unsupervised LearningHow to Solve Unsupervised Learning Problems?Introduction to AutoencodersImplementing Autoencoders AutoDLA Beginners Guide to Codeless Deep Learning Model DeploymentTensorFlow ServingBuild Deep Learning Models for Android Introduction to PyTorchIntroduction to PyTorch and TensorsMathematical and Matrix Operations in PyTorchImportant PyTorch ModulesImplement CNN in PyTorchTransfer Learning in PyTorchWorking with Text Data in PyTorchBuilding a RNN model in PyTorchAutoencoders in PyTorch Creating Android Machine Learning Apps Using KivyMD Kaustubh Gupta Last Updated : 06 Jul, 2021 9 min read This article was published as a part of the Data Science Blogathon Introduction Android Apps have truly captured our lives. Almost every day we use some of the other android apps to accomplish our task. Be it social media apps like WhatsApp, Twitter, or networking apps like LinkedIn, Android apps have a major impact on our lives. In this article, we will look at: What is Kivy and KivyMD Installation A Simple app Important Components Stitching our ML App Convert the Python file to APK! Image by Author (Made in Canva) Before I proceed with the article, here is a quick demo of the android app running on my device: What is Kivy and KivyMD? Kivy is a Python library that facilitates the creation of cross-platform applications that can run on Windows, Linux, Android, OSX, iOS, and Raspberry pi too. It is a popular package for creating GUI in Python and in recent years, it is gaining a lot of popularity due to its easy-to-use nature, good community support, and easy integration of different components. KivyMD is built on the top of the Kivy library, It is a collection of Material Design widgets to be used with Kivy. It offers more elegant-looking components and the code is almost the same. Currently, we use KivyMD components for creating the UI (User Interface) of the application and Kivy for all the core functionalities such as internet access and building the app. The best part about these packages is that the code is structured in object-oriented format from the beginning itself and we will see in the upcoming sections how it makes the development process easy. Installation For installing the Python packages, you can use the pip package manager. I would suggest creating a virtual environment for this development. It will be helpful to manage the packages more easily. First, install the Kivy Package: pip install kivy Now you can install the KivyMD package too: pip install kivymd Note: Some of the required dependencies may be left out of installation. You can use the following installation commands to fix this error. pip install kivy-deps.angle pip install kivy-deps.glew pip install kivy-deps.gstreamer pip install kivy-deps.sdl2 A Simple App To get you started with the app development using these packages, we will create an app that just displays some text, with no functions ahead. The code for this app is: from kivymd.app import MDApp from kivy.lang.builder import Builder from kivy.uix.screenmanager import Screen, ScreenManager Builder_string = ''' ScreenManager: Main: <Main>: name: 'main' MDLabel: text: 'Hello Analytics Vidhya Readers!' halign: 'center' ''' class Main(Screen): pass sm = ScreenManager() sm.add_widget(Main(name='main')) class App(MDApp): def build(self): self.help_string = Builder.load_string(Builder_string) return self.help_string App().run() Let’s break it down: First thing first, we have imported some essential packages. Every KivyMD application needs to be built on top of the base app provided as “MDApp” by KivyMD. This app class contains all the basic initializations and the code required to boot up the app. We have inherited this class and override the “build” function with our code. Next is the Kivy builder function that helps in setting up the frontend for our app. The front-end components are created using the YAML format Builder string or KV lang in hierarchical style. This defines what components will be used in the app, their properties, attributes, and callbacks. All these things are defined by the builder string. The YAML format makes it easy to write the specifications of the components. For instance, the “MDLabel” component, which is used for displaying text, has been placed under the “Main” screen component. Its text and position are defined one level after the declaration. In the inherited MDApp class, the function build is loading the builder sting and returning it This is how a KivyMD app is structured and you can consider this as a boilerplate code for future apps. Important Components There are many components supported by KivyMD to make your apps interactive. You can add text, images, icons, dropdowns, navigation bars, tables, and literally anything that the native android app development offers. The developers of this library are constantly adding new features. Here I am describing only a few of them which will be used to stitch our android applications. Screen and ScreeenManager The screen is the component where other components would be placed. It can also be called the playground for components. The screens are also similar to website pages where different pages have different elements. Each component in the screen is placed one position lower to maintain the hierarchy. We usually assign a name to the screen so that we can access the components of that screen. The screen manager manages all these screens. Any screen can be accessed via this screen manager. Declaration syntax for this: Builder_string = ''' ScreenManager: Main: <Main>: name : 'main' . . ''' class Main(Screen): pass sm = ScreenManager() sm.add_widget(Main(name='main')) MDLabel This component is used to display any type of text on the application screen. The title of the application, any form field, or other text can be displayed using this component. As I have already used this component in the basic app code, let me add some more properties: You can control the size of the text using “font_style”. HTML heading level, “Subtitle1”, “Subtitle2”, “Body1” and many more are available. Changing the color of the text is done by using the “text_color” parameter. It takes in the RGB value (percentage-wise, not absolute). “halign” and “valign” are used to align the text horizontally and vertically. The “pos_hint” parameter is used to define the exact location. It takes a dictionary of center_y and center_x “id” parameter defines the id of the label component The example below shows these implementations (I have provided Builder string here because there is no change in the logic): Builder_string = ''' ScreenManager: Main: <Main>: name: 'main' MDLabel: text: 'Analytics Vidhya' halign: 'center' pos_hint: {'center_y':0.9} font_style: 'H4' MDLabel: text: 'Blogathon' halign: 'center' pos_hint: {'center_y':0.7} text_color: (1, 0.2, 0.3, 1) font_style: 'H5' theme_text_color: 'Custom' ''' MDTextField These are components that help in getting the value from the user and pass it to the logic. It means that the area where the user enters the values asked are the text fields. It is also similar to the input fields used in web development. Generally, a text field has a placeholder text, some text below the field, and icons too. For the scope of this article, I am not explaining all the properties of all the components. To create a basic text field, you need to define the helper text and its id: Builder_string = ''' ScreenManager: Main: <Main>: MDTextField: id: input hint_text: 'Enter some text' width: 100 size_hint_x: None pos_hint: {'center_y':0.61, 'center_x':0.5} ''' Make sure to define the id of these text fields. I will explain how to access these inputs when binded with a button to do some activity. MDButton Buttons are used to perform some action. On the android application, whenever you do some task and tap on some icons, that’s also one of the kinds of buttons. Buttons can trigger activity to some business logic dependent or independent of the inputs. For instance, if an app fetches an image with the click of a