- Tutorial: Create a Windows Machine Learning Desktop application (C++)
- Prerequisites
- Create the project
- Load the model
- Load the image
- Bind the input and output
- Evaluate the model
- Next steps
- See also
- Learn .NET
- Get Started
- Console
- In-browser Tutorial
- Mobile
- Desktop
- Game Development
- Machine Learning
- Internet of Things
- .NET 101 video series
- Microsoft Learn
- LinkedIn Learning
- Learning Materials
- Новые пути обучения Azure
- Сертификация
- Обучение под руководством инструктора
- сертификационный экзамен
- Знакомство с Microsoft Learn
- Keeping pace with today’s technical skills with Microsoft Role-based Certification
- Идите в ногу с современными техническими навыками благодаря ролевой сертификации от Microsoft
- Что вы хотите изучать?
- Раскройте свой профессиональный потенциал
- Индивидуальная подготовка для Microsoft 365
- Учитесь у экспертов
- Office 365
- Windows Server
- C#/XAML
- Веб-разработка
- Windows
- SQL Server
- Анализ данных
- How to Learn Programming?
- Table of Contents
- Introduction
- How to Learn to Code
- Learn Programming Fundamentals
- 1. Through Interactive Websites
- 2. Through Video Tutorials
- Focus on Learning Programming Basics
- Build your First Project
- How Should I Choose a Project?
- 1. Choose What Interests You
- 2. Start With Something Simple
- 3. Build Something Useful for Yourself and the Community
- Few Ideas to Get Started
- Feeling Stuck?
- 1. Learn to Google the Error Correctly
- 2. Popular Websites to Guide You
- 3. Events and Meetups
- Get a Job or an Internship
- Computer Science Degrees or Bootcamps: Which is beneficial to learn to program?
- Conclusion
- Simran Kaur Arora
Tutorial: Create a Windows Machine Learning Desktop application (C++)
Windows ML APIs can be leveraged to easily interact with machine learning models within C++ desktop (Win32) applications. Using the three steps of loading, binding, and evaluating, your application can benefit from the power of machine learning.
Bind -> Evaluate» data-linktype=»relative-path»/>
We will be creating a somewhat simplified version of the SqueezeNet Object Detection sample, which is available on GitHub. You can download the complete sample if you want to see what it will be like when you finish.
We’ll be using C++/WinRT to access the WinML APIs. See C++/WinRT for more information.
In this tutorial, you’ll learn how to:
- Load a machine learning model
- Load an image as a VideoFrame
- Bind the model’s inputs and outputs
- Evaluate the model and print meaningful results
Prerequisites
- Visual Studio 2019 (or Visual Studio 2017, version 15.7.4 or later)
- Windows 10, version 1809 or later
- Windows SDK, build 17763 or later
- Visual Studio extension for C++/WinRT
- In Visual Studio, select Tools > Extensions and Updates.
- Select Online in the left pane and search for «WinRT» using the search box on the right.
- Select C++/WinRT, click Download, and close Visual Studio.
- Follow the installation instructions, then re-open Visual Studio.
- Windows-Machine-Learning Github repo (you can either download it as a ZIP file or clone to your machine)
Create the project
First, we will create the project in Visual Studio:
- Select File > New > Project to open the New Project window.
- In the left pane, select Installed > Visual C++ > Windows Desktop, and in the middle, select Windows Console Application (C++/WinRT).
- Give your project a Name and Location, then click OK.
- In the New Universal Windows Platform Project window, set the Target and Minimum Versions both to build 17763 or later, and click OK.
- Make sure the dropdown menus in the top toolbar are set to Debug and either x64 or x86 depending on your computer’s architecture.
- Press Ctrl+F5 to run the program without debugging. A terminal should open with some «Hello world» text. Press any key to close it.
Load the model
Next, we’ll load the ONNX model into our program using LearningModel.LoadFromFilePath:
In pch.h (in the Header Files folder), add the following include statements (these give us access to all the APIs that we’ll need):
In main.cpp (in the Source Files folder), add the following using statements:
Add the following variable declarations after the using statements:
Add the following forward declarations after your global variables:
In main.cpp, remove the «Hello world» code (everything in the main function after init_apartment ).
Find the SqueezeNet.onnx file in your local clone of the Windows-Machine-Learning repo. It should be located in \Windows-Machine-Learning\SharedContent\models.
Copy the file path and assign it to your modelPath variable where we defined it at the top. Remember to prefix the string with an L to make it a wide character string so that it works properly with hstring , and to escape any backslashes ( \ ) with an extra backslash. For example:
First, we’ll implement the LoadModel method. Add the following method after the main method. This method loads the model and outputs how long it took:
Finally, call this method from the main method:
Run your program without debugging. You should see that your model loads successfully!
Load the image
Next, we’ll load the image file into our program:
Add the following method. This method will load the image from the given path and create a VideoFrame from it:
Add a call to this method in the main method:
Find the media folder in your local clone of the Windows-Machine-Learning repo. It should be located at \Windows-Machine-Learning\SharedContent\media.
Choose one of the images in that folder, and assign its file path to the imagePath variable where we defined it at the top. Remember to prefix it with an L to make it a wide character string, and to escape any backslashes with another backslash. For example:
Run the program without debugging. You should see the image loaded successfully!
Bind the input and output
Next, we’ll create a session based on the model and bind the input and output from the session using LearningModelBinding.Bind. For more information on binding, see Bind a model.
Implement the BindModel method. This creates a session based on the model and device, and a binding based on that session. We then bind the inputs and outputs to variables we’ve created using their names. We happen to know ahead of time that the input feature is named «data_0» and the output feature is named «softmaxout_1». You can see these properties for any model by opening them in Netron, an online model visualization tool.
Add a call to BindModel from the main method:
Run the program without debugging. The model’s inputs and outputs should be bound successfully. We’re almost there!
Evaluate the model
We’re now on the last step in the diagram at the beginning of this tutorial, Evaluate. We’ll evaluate the model using LearningModelSession.Evaluate:
Implement the EvaluateModel method. This method takes our session and evaluates it using our binding and a correlation ID. The correlation ID is something we could possibly use later to match a particular evaluation call to the output results. Again, we know ahead of time that the output’s name is «softmaxout_1».
Now let’s implement PrintResults . This method gets the top three probabilities for what object could be in the image, and prints them:
We also need to implement LoadLabels . This method opens the labels file that contains all of the different objects that the model can recognize, and parses it:
Locate the Labels.txt file in your local clone of the Windows-Machine-Learning repo. It should be in \Windows-Machine-Learning\Samples\SqueezeNetObjectDetection\Desktop\cpp.
Assign this file path to the labelsFilePath variable where we defined it at the top. Make sure to escape any backslashes with another backslash. For example:
Add a call to EvaluateModel in the main method:
Run the program without debugging. It should now correctly recognize what’s in the image! Here is an example of what it might output:
Next steps
Hooray, you’ve got object detection working in a C++ desktop application! Next, you can try using command line arguments to input the model and image files rather than hardcoding them, similar to what the sample on GitHub does. You could also try running the evaluation on a different device, like the GPU, to see how the performance differs.
Play around with the other samples on GitHub and extend them however you like!
See also
Use the following resources for help with Windows ML:
- To ask or answer technical questions about Windows ML, please use the windows-machine-learning tag on Stack Overflow.
- To report a bug, please file an issue on our GitHub.
- To request a feature, please head over to Windows Developer Feedback.
Learn .NET
Free tutorials, videos, courses, and more for beginner through advanced .NET developers.
Get Started
New to .NET and don’t know where to start? You can try .NET in your browser, at the console on your machine, or by building the app of your choice.
Console
Build a simple text-based application that runs in the console/terminal
In-browser Tutorial
Try .NET in your browser, without installing anything on your computer
Create a web app that runs on Windows, Linux, macOS, and Docker
Mobile
Build an app that dials numbers on iOS, Android, and Windows devices
Desktop
Develop an expense tracking desktop application for Windows
Game Development
Create a 3D spinning cube with Unity
Machine Learning
Build a machine learning model to classify iris flowers
Internet of Things
Blink an LED light on your Raspberry Pi, or other single-board computer
.NET 101 video series
Getting started with .NET development? We have you covered with our .NET 101 video series. Explore videos on web, mobile, desktop, C#, machine learning, containers/docker, data access, and more.
Microsoft Learn
Discover your path to build apps with .NET on Microsoft Learn. Whether you’re just starting or an experienced professional, Microsoft Learn’s hands-on approach helps you arrive at your goals faster, with more confidence and at your own pace for free.
LinkedIn Learning
Get an introduction to the programming skills needed for a career as a .NET software developer. Experience .NET learning courses that provide a broad perspective on core technologies leveraging .NET.
Learning Materials
Got the basics and want to learn more? Dig into the developer documentation for the different .NET app types and programming languages.
Новые пути обучения Azure
Пути обучения помогут вам пройти обучение и подготовиться к карьере разработчика, администратора и архитектора решений, а также к сертификации Microsoft Azure.
Сертификация
Начните карьеру, заслужите признание и подтвердите свои навыки в работе с помощью признанных в отрасли сертификатов Microsoft.
Обучение под руководством инструктора
Уточните свои навыки в углубленном классе и обучении по запросу, предлагаемом обучающими партнерами, преподаваемым сертифицированными тренерами Microsoft.
сертификационный экзамен
Ознакомьтесь с имеющимися сертификационными экзаменами Microsoft, чтобы подтвердить свои навыки и продвинуться по карьерной лестнице.
Знакомство с Microsoft Learn
Новый способ изучения Azure и интеллектуальных бизнес-приложений. Овладейте навыками, которые вам нужны, разблокируйте достижения и продвиньтесь по своей карьерной лестнице.
Keeping pace with today’s technical skills with Microsoft Role-based Certification
Идите в ногу с современными техническими навыками благодаря ролевой сертификации от Microsoft
Что вы хотите изучать?
Найдите подходящие возможности для обучения и сертификации, которые будут способствовать вашему карьерному росту и успеху.
Раскройте свой профессиональный потенциал
Получите навыки работы с облаком, чтобы достичь успеха на всех уровнях
Получите навыки работы с Azure, чтобы раскрыть свой потенциал карьерного роста. Получите пользующиеся признанием в отрасли сертификации, пройдя комплексное обучение — от занятий на основе ролей до продвинутых курсовых работ.
Индивидуальная подготовка для Microsoft 365
Дайте вашей команде особые навыки, необходимые им для верного развертывания Microsoft 365 в первый раз. Благодаря онлайн-курсам и инструкторам, наши учебные возможности Microsoft 365 предназначены для адаптации к потребностям вашей организации.
Учитесь у экспертов
Независимо от ваших потребностей в обучении Microsoft 365, у нас есть решение для вас, созданное известными в отрасли экспертами Microsoft
Office 365
Узнайте, как Office 365 может помочь с обеспечением высокой безопасности, надежности и производительности пользователей, а также получите рекомендации по установке, администрированию и настройке.
Windows Server
Получите знания и навыки, необходимые для работы с сетями, приложениями и веб-службами нового поколения с поддержкой облачной оптимизации. Ознакомьтесь с настройками сети, хранением и виртуализацией.
C#/XAML
Научитесь у профессионалов программированию на C# и работе с XAML. C# является простым, но в то же время мощным языком программирования, позволяющим создавать приложения Windows и веб-службы, а XAML упрощает создание пользовательского интерфейса (UI).
Веб-разработка
Пройдите обучение по разработке веб-приложений у профессионалов, ознакомьтесь с HTML5, JavaScript, Node.js и React, а также Angular, Ember, MVC, C# и многим другим.
Windows
Узнайте, как Windows 10 помогает создать оптимальную среду для пользователей, в то же время обеспечивая контроль над безопасностью, управлением и настройками.
SQL Server
Выведите свои навыки работы с SQL Server на новый уровень, научившись внедрять и управлять решениями для баз данных, миграции на облако и работе с мощными функциями составления отчетов.
Анализ данных
Используйте SQL Server для более быстрого сбора данных. Кроме того, ознакомьтесь с Azure HDInsight, анализом данных и распространенными сценариями и технологиями обработки больших массивов данных.
How to Learn Programming?
Table of Contents
Introduction
Learning to code is a new skill that is popular these days. It is so much in demand that even high schools have added programming in their curriculum. Programming and coding are often used interchangeably but both are different and you can read about them here. With every chore being digitized & becoming smart and automotive with the AI technology, learning to code has become the need of an era.
Everything that you can possibly think of can be done using an app or a website from ordering a cab, or food or shopping online to watching movies or even taking a course & gaming skills. With applications being digitized the demand also increases for developers and programmers and hence learning a programming language would be beneficial. This article discusses how to learn the programming language of your choice and the correct way to begin your programming journey. So let us get started!
How to Learn to Code
Before we begin reading further let me remind you that you have chosen a path that demands patience and motivation to never give up in spite of the challenge on the way. Read through and follow the steps below to become a programmer.
Learn Programming Fundamentals
The first and foremost step is to choose the language to learn. It is recommended to start with Python as it is simple like English and so easy to learn you can check out some of the best Python tutorial and get started. But you may choose the language that interests you and also based on the project that you would like to develop in the future. So if you plan to develop a mobile app you may want to begin with Java or Kotlin for Android and Swift for iOS, and if you want to build a website Javascript is suggested, to begin with. For a profession in data science, AI & ML, Python & R are the languages to study.
You may want to learn the languages in one of the following two ways:
1. Through Interactive Websites
Websites like Codecademy and Freecodecamp are recommended for interactive coding sessions. These were built with the idea that many beginners are stuck at the beginning when they start to learn to code while setting up the development environment. These websites offer online text editors and compilers to begin coding instantly.
2. Through Video Tutorials
If you are a person who likes a detailed study with step by step guidance then we recommend you enroll into any online programming tutorial that teaches you from the beginning to install and download the required IDE to basic concepts of the language and it ends with a capstone project to test your coding skills. Some tutorials and courses also offer certifications that could help you later when you look for the job. We recommend Pluralsight and Lynda for searching the beginner tutorials for the preferred language. You may also want to check out some top-rated tutorials at Hackr.io.
Focus on Learning Programming Basics
It is always suggested to make your fundamentals strong so as to be a pro coder. Learn the basics thoroughly and try your hands on the code by making your own problems and solving them. Stress on the following topics to begin learning as they are common in almost all the languages.
- Data Types
- Variables
- Functions
- Array or Lists
- If statements
- Conditional loops
- Classes and objects
- Exception handling
- Trees, maps, and more.
Build your First Project
Building your personal project is the best way to analyze and learn what you have learned. Building a project of your choice would give you practical learning experience of the language in much detail as you would come across the implementation of the concepts that you have learned earlier and also learn how to deploy the project to be used by you and all others. Moreover, as you build your projects add it to your profile or your GitHub account, this would help you in the future when you look for a job in development.
The biggest question that arises at this stage is:
How Should I Choose a Project?
This is where most people get stuck at the deciding stage so what to build? The solution is simple. Let us see it below:
1. Choose What Interests You
Whether it comes to studying or coding you must do what interests you the most. You must enjoy the project area you choose so that you are passionate about it and it keeps you engage until built. If you choose something that is not of your interest you may end up giving up your project in the middle as you might eventually lack interest in it. So choose something that keeps you held upon itself like if like playing games then you might just want to develop a video game of your choice. Similarly, if you like photography you might want to build up your portfolio website showcasing your work or if you are someone who is interested in trading you might design an app or website to analyze your stock charts. Analyze and give it a thought that what you like before you begin to build.
2. Start With Something Simple
Being confident about your capabilities is good but being overconfident is not. So it is recommended that you begin with simple and easy projects to explore the language more before you dive into building complex projects.
For example, if you choose to build a video game do not straightaway begin with the complex video game League of Legends instead begin within something like tic-tac-toe or if you want to build a website do not start with building something like Amazon or Facebook instead go for something easier like a to-do list.
3. Build Something Useful for Yourself and the Community
Be innovative and build something that is useful for you as well as that interests the community. Building something of community’s interest would give an opportunity to have several downloads or viewers to your project and this way you would have something to showcase your and also have an edge over other candidates while looking for a job.
Few Ideas to Get Started
If you are puzzled about where, to begin with, we have got you few ideas to start with your project building. You could begin with a simple website like making a to-do list or if you want to make a game app then games like Tetris, sudoku, and the flappy bird are good to start with learning programming.
If you want something challenging you might want to consider building a website similar to Twitter but with not as many features as Twitter offers but with some basic functionality like to tweet and follow. Hackr gives you many project ideas for several languages ranging from the beginner level to the advanced level. Check out the projects of different languages here:
Feeling Stuck?
There would come a time while you develop the projects that you would feel stuck it could anything from getting errors, your program crashing without any message or even your coding executing fine but not generating the output you desired you might get so restless even sometimes that you might want to give up. What do you do in such scenarios? Don’t give up! Stay motivated, and to help consider below the points to continue working on your project.
1. Learn to Google the Error Correctly
This is a crucial step that you must master. Searching and surfing the error of your code would help you correct your code within few minutes but on the other hand, if are not sound at this skill it would be like diving into a whirlpool of code without a map. A tip that I would like to share here is put the error generated by your compiler in double-quotes (“ ”) before searching on Google. This way Google would specifically target the error as the same sentence and that would give a much accurate filtered result.
2. Popular Websites to Guide You
Websites like Stack-Overflow and Reddit top the charts here to guide developers around the world with their code. It is a full-fledged community of developers from all fortes that come up to help each other in their projects. Posting your doubts here could even take 2-3 weeks to get a response but it is worthy, although you might already end up finding the solution to your error as many people might have come across the same error before. It is also suggested that you answer some of the questions that you can to help others and so this way you would also learn.
3. Events and Meetups
This step might be difficult to start with as it requires you to leave your comfort zone but trust me once you start doing it you would enjoy it. So, start by looking for people who have similar interests as yours and get to know or maybe work with them. You could try searching for some “coding events” at your Facebook’s event page or visiting the meetup site and connect with people to learn more.
Get a Job or an Internship
Finally, many learn programming languages to end up in a development job. So when you are confident enough or believe that you know some basic programming you may want to step in the development industry by starting with an internship. Start working as a paid or an unpaid intern in a project that is of your interest or you may even assist or work with some experienced developer to learn. Working as an intern gives you an opportunity to learn and enhance your skills and sometimes even get paid. Even if you are not getting pain you get an opportunity to make your network in the industry for future references and placements.
You may want to begin your internship search in the following ways:
- LinkedIn: It is the most trusted source that reaches a wide audience and can help you find a variety of internships of your interest.
- Career Fairs: These are pretty helpful as you get an opportunity to meet the recruiters in person and hence can discuss your interests and analyze if the project interests you too.
- Networking: This is the most recommended way of getting an internship as you get into a job through someone’s reference you are certain to get an edge over other candidates as they tend to trust you easily if someone from there firm refers you. You can build up your network by going to events and meetups as guided above.
Computer Science Degrees or Bootcamps: Which is beneficial to learn to program?
Whether to study by enrolling in a degree program or into a Bootcamp? Is a common question that comes for those you begin to learn to code. There not a certain answer to this question as it entirely depends upon person to person and also their learning capability. To further guide you, if you are a high school student who is yet to enrol in graduate school and programming is the career then you must go to for a degree in computer science but if computer science and coding is something that interested you later in your career then you might want to go for a Bootcamp in a programming language of your choice. However, it is also recommended that you begin with an online course either paid or free to get a flavour of coding first before spending on the Bootcamp as they are expensive.
Conclusion
That brings us to the end of the guide to learn to program. I hope after reading this article you are urged to learn to program and start coding your first project. We at Hackr.io have shortlisted the best courses for almost all the programming languages that you might want to check out. So gear up and begin your journey of becoming a developer. Do you have other tips that you would like to share with others in the programming community? Let us know. Happy Coding!
People are also reading:
Simran Kaur Arora
Simran works at Hackr as a technical writer. The graduate in MS Computer Science from the well known CS hub, aka Silicon Valley, is also an editor of the website. She enjoys writing about any tech topic, including programming, algorithms, cloud, data science, and AI. Traveling, sketching, and gardening are the hobbies that interest her. View all posts by the Author