Quantcast
Channel: MSDN Blogs
Viewing all 5308 articles
Browse latest View live

Avoid email notifications from Office Groups when adding people to groups when embedding Power BI into SharePoint pages

$
0
0

I am sitting in the Seattle SharePoint Saturday and one of the attendee’s asked how to suppress the welcome message sent from adding people to the Office 365 group.

When you embed a Power BI report into a SharePoint page only the members of the Office Group will be able to see the report….even if the page is published.

Those uses will see the Power BI error: 

“This content isn’t available”


image

Getting around this is very easy…Add the user to the Office Group hosting the Power BI Report (note this user will need to have a Power BI Pro license or this report will need to be a Premium Capacity)


image

After being added this user now has access to the page AND the Power BI


image


Unfortunately those users will also receive a Welcome email like the following

image

To disable this you will need to run the following PowerShell command

Set-UnifiedGroup -Identity "Name of your group" -UnifiedGroupWelcomeMessageEnabled:$false


How to build a user interactive bot with Microsoft Bot Framework

$
0
0

Guest blog by Shu Ishida Microsoft Student Partner at Oxford University

image

About me

My name is Shu Ishida, and I am a third year engineering student at the University of Oxford. I am into web development and design, and my ambition is to help break down educational, cultural and social barriers by technological innovation. My current interest is in applications of Artificial Intelligence to e-Learning. I also have passion towards outreach and teaching, and have mentoring experiences in summer schools as an Oxford engineering student ambassador.

LinkedIn: https://www.linkedin.com/in/shu-ishida

Introduction

I would like to give an overview on how to build a user interactive bot with Microsoft Bot Framework. For those of you who are not familiar with bots, bots are applications that can assist your daily needs like a virtual robot. They can perform semi-automated tasks, such as setting an alarm, searching online, making an order, and posting on social media. The beauty of modern bots is that it can understand and operate on instructions that are given through text and voice dialog.

Today we are going to make a bot that is both usable and user friendly. We’ll use Microsoft Bot Framework – a comprehensive framework that can be used by anyone from beginners to developers. We’ll first discuss how to build a bot, and later on, talk more about why user experience is important and how we can design conversation flow.

Registering to Microsoft Azure

To get started, let’s create an Azure account – registration and trial is free.

https://azure.microsoft.com/

If you are new to Azure, Azure is a comprehensive set of cloud services to build, deploy and manage applications. Today we are going to focus on Bot Service, but there are other fantastic features such as Azure Machine Learning where you can train your online machine learning model which require minimal amount of programming.

Creating your first bot

Once you are registered, go to your dashboard at https://portal.azure.com/ and click ‘New’ with the green plus icon. From the options, select ‘Data + Analytics’ > ‘Bot Service’.

clip_image002

Alternatively, you can go to https://dev.botframework.com/ and click ‘Create a bot’ button on the ‘My bots’ page. This site also has useful documentation for Bot Framework.

Fill in the app name and the location, and press ‘Create’. Here I named my bot ‘superbott’.

clip_image004

There are five templates available to get your development going. You can choose your template according to what sort of bot you are going to make. For now, let’s try building a bot which can understand dialogs using the Cognitive Services LUIS (Language Understanding Intelligent Service) API. [Read Documentation]

A screen appears, prompting you to get an App ID and password. After pressing ‘Create Bot’, a window will open to ask you to connect Azure Bot Service to LUIS:

clip_image006

How to use LUIS

A LUIS app takes a user utterance and extracts intents and entities that correspond to activities in the client application’s logic. In a nutshell, this means that LUIS can identify the type of action that the user is requesting, such as flight booking, reminder, food order, etc. together with the information of quantity, specific location or name of the item of interest. LUIS gives a response in JSON format, denoting the confidence in its recognition. We can pass this response to the bot which can then take appropriate action based on the user intentions. [Read Documentation]

Let me explain more about the three concepts – utterance, intents and entitles. Utterance is the user’s input, usually by text or voice. Intents are actions that the bot is requested to take (the intention of the user), usually corresponding to the verb within the uttered sentence. Entitles are information associated to the action, such as location, date and noun in the utterance (name of an app, item, etc.). The task of LUIS is to identify the intents and entitles within an utterance. Intent options are defined by the developer (you), so in order to get the bot working, we have to first decide on what kind of tasks we are expecting our bot to do.

Here are some good tutorials on how to use LUIS to create a bot.

https://channel9.msdn.com/Blogs/MVP-Azure/build-a-chatbot-with-azure-bot-service

http://www.codeshare.co.uk/blog/how-to-create-a-hangman-chat-bot-game-in-nodejs-using-microsoft-bot-framework/

Make the bot respond to you

Let’s start by creating a very simple bot. The default page should look like this. You can either edit the code on an online editor, or download the code and work from a local IDE / editor. The ‘Channels’ tab shows you apps that you can connect with. From ‘Settings’ you can change your bot icon. By clicking the blue ‘Test’ button, a bot emulator appears.

clip_image008

At the moment the bot is being highly unsociable. That is because we haven’t programmed anything yet so the bot doesn’t know what to do. We can manually programme the bot so that it can recognise utterances starting with ‘hey’ as an intent. You can make the bot respond with “Hello. How can I help you?” or maybe you can be more creative…

clip_image011

Ooops, we’ve made the bot angry! In this example, I’ve just added this extra line of code so that it can detect ‘hey’ at the start of the utterance.

image

^ denotes the start of a sentence, and ‘i' indicates that the search should be case-insensitive. These are called regular expressions, often used in text search and text replacement. The bot replies to you using session.message.text which contains your utterance.

We can continue manually coding conditions for the bot, but that makes the code convoluted. This is where LUIS becomes useful. Go to https://www.luis.ai/applications and click on the app connected to your bot. You should be able to ‘Create an intent’. Let’s call it ‘Greeting’.

clip_image013

We can add many examples of utterances to train the bot. Once you have finished training the bot, go to ‘Publish App’ at the bottom left navigation. Going back to the code, replace /^hey/i with ‘Greeting’ as shown below. Now your bot should be able to pick up different greetings.

image

Making your first Twitter bot

Now your bot will start responding to various user inputs. However, it is not exactly useful yet. To make it do something useful, let’s change it into a twitter bot. I am going to walk you through how to set it up, but if you need further details, here is a good article on how to set up your twitter and connect it to your bot.

https://medium.freecodecamp.org/how-to-build-and-deploy-a-multifunctional-twitter-bot-49e941bb3092

Alternatively, this is a good YouTube tutorial that walks you through how to create a twitter bot.

First, we want to register our bot to our twitter account so that the bot can have access using the access token and key. I strongly recommend you get a new Twitter account for development, so that if anything goes wrong, you won’t lose your Twitter account or your followers. Once you’ve logged into your new account, go to https://apps.twitter.com/app/new and fill in the details of your bot. A website URL is not essential for this.

clip_image015

Once you register your application, you can get details for the Consumer Key (API Key), Consumer Secret (API Secret), Access Token and Access Token Secret. Now we will return to the code on Azure and create an .env file with these details as shown below.

clip_image017

Separating out your API key information from the main code and storing it in .env is good practice. Otherwise, your account will be at risk if you are working on a collaborative project or sharing your code on GitHub. NEVER share your key online, even in a tutorial video or screenshot. There are crawler bots out there that tries to steal your account / API keys and if you are unlucky you can be charged for incredibly expensive bills. In case you want to upload your code to GitHub in the future, add .env to .gitignore file so that it wouldn’t be uploaded.

We have two more steps – first to read in the key information from .env into Node.js, and then connect to twitter using that account information. We can do these by installing node modules called dotenv and twit. Open the console and type

image

clip_image019

Now that we have dotenv, we can import the key information from .env to config.js.

image

clip_image021

Finally, in the app.js file, set up twitbot (a Twit object that carries out the tweeting operations) configuring with the key information. Make sure you don’t call this just ‘bot’ – it will overlap with the ‘bot’ variable defined already.

image

Below is the part where twitbot posts a tweet. We can determine the content in ‘status’, which I set to ‘hello world!’.

image

Let’s append this to the response to ‘Greeting’ for the time being as shown below.

clip_image023

Now everything is set up. Go to your online bot emulator and type in some greeting. After the bot responds, check your twitter account and, lo and behold! You have your first tweet!

clip_image025

Making the bot tweet what you want

Cool stuff! So now we can add some flexibility to the bot and make it tweet whatever we want. To get started, let’s add another intent ‘Tweet’ to LUIS so that it can distinguish between greetings and tweet tasks. Create an intent and add utterances. Remember to re-publish your changes once you’ve finished.

clip_image027

Now you can go ahead and handle the case where the intent matches ‘Tweet’.

image

The major changes I have made in the code is this bit where I have added a dialog that is called by beginDialog(‘/tweet’). This sort of dialog structure is called waterfalls implementation [Read Documentation]. In the dialog, the bot asks what the user wants to tweet and directly goes ahead posting it. This looks straight forward, but might raise an issue if we want to quit midway - we should handle this case in the next section.

imageimage

Finally our bot is up and running, and can change what it tweets according to the user’s order. Notice that the initial conversation starter has been altered to indicate what the bot is about.

clip_image030

Go on to your twitter account and make sure it’s working! If you are having problems with your tweet, maybe it is because you are posting the same sentence over and over again. Twitter doesn’t seem to allow multiple identical tweets.

clip_image032

The problem with quitting

So far so good. But what if we change our mind half-way through the action? Consider this situation below:

clip_image034

In this case we want the bot to be clever enough to detect that the user has changed their mind and wants to quit. Although we can try creating an additional intent for cancellation, there is a straightforward way of handling user action, and moreover, call out a predefined function to cancel an action. Here we are going to use cancelAction, but other actions such as triggerAction and reload Action could be also handy. [Read Documentation]

image

clip_image037

As it could be seen, this interface provides the opportunity for users to quit, and moreover, cancel the quit operation and go back to where the bot was interrupted. Determining every possible flow of conversation that can occur, and handling cases that doesn’t follow the designed conversation pattern is crucial in bot building, since it doesn’t have a navigation system of back and forward unlike web browsers. This documentation can give you further insight into this topic.

Tweet from Facebook

Finally, let’s learn about how to use channels. By going to the ‘Channels’ tab, you can see many options where you can use your bot. Slack is quite a common place to use bots, but today let’s have our bot working on Facebook messenger. To get started with, click the Facebook messenger icon. The documentation walks you through step by step. [Read Documentation]

clip_image039

Since the bot is associated to a Facebook page rather than a user account and is intended to be used as an autoreply bot for an organisation, we’ll first have to create a new Facebook page and connect the bot to it.

1. Create a new Facebook page from https://www.facebook.com/bookmarks/pages.

2. Create a new Facebook App from https://developers.facebook.com/quickstarts.

3. Select Messenger as your product and generate a Page Access Token.

4. Copy and paste your credentials from all the above into the Bot Framework Portal.

5. Click ‘Set up Webhooks’ on the Messenger setup page.

6. Copy and paste the webhook callback URL and verify token from the portal into the webhook form.

7. Save details.

clip_image041

Now let’s go back to the Facebook page we have created and send a message, and lo and behold! The Facebook page gives automated replies!

clip_image043

For obvious reasons, you don’t want all the Facebook users in the world to be able to tweet on your Twitter account, so make sure you delete the newly created Facebook App once you’re done with it. Although a Twitter bot was probably not the best example of bots that can be embedded on Facebook messenger, it demonstrates how bots can be implemented and be useful when you are dealing with a ton of customers. Now, you can start to visualise these bots actually interacting with humans, and more importantly, perceived as human operators across the screen. Therefore it is highly important that the bots can provide essential services with a well-designed communication flow and without the intervention of humans.

Build your own bot with Microsoft Bot Framework

Now is time for you to create your own bot. If you are not making it public, it could be a personal planner and secretary. If you are developing for your enterprise or an online service, it could be easily made into a receptionist, companion, gaming opponent, media source, image processing service or more. Interface matters because it is automated, but once you get over that barrier, there are many opportunities out there since it could be built in to commonly used services such as Facebook messenger and Skype, so that it would be easy to subscribe.

And with that, we have come to the end of this article. Thank you very much for reading through all the way.

Resources and further information

Microsoft Bot Framework Documentation https://docs.microsoft.com/en-us/bot-framework/

Video tutorial of building a LUIS chat bot

Example of playing hangman on a Microsoft Bot http://www.codeshare.co.uk/blog/how-to-create-a-hangman-chat-bot-game-in-nodejs-using-microsoft-bot-framework/

Example of building a Twitter bot https://medium.freecodecamp.org/how-to-build-and-deploy-a-multifunctional-twitter-bot-49e941bb3092

YouTube tutorial on how to create a Twitter bot https://www.youtube.com/watch?v=GQC2lJIAyzM&list=PLRqwX-V7Uu6atTSxoRiVnSuOn6JHnq2yV&index=3

Introduction to Microsoft Intelligent Edge

$
0
0

Guest post by Ivaxi Miteshkumar Sheth Microsoft Student Partner at Imperial College

image

About me

I am Ivaxi Miteshkumar Sheth. I am a year 2 student at Imperial College London pursuing Electrical & Electronic Engineering. Since childhood, I have been interested in Mathematics and Technology. With my degree, I am looking forward to building various projects that can help the society. I am interested in hardware designing. Currently I am a Committee Member of Department Women’s Society that aims to provide support and increase the gender ratio of women in the Department. I am also working as an Electrical Engineer for Imperial Green Racing. Apart from tech, I am very passionate about dancing.

Linkedin Profile https://www.linkedin.com/in/ivaxi-miteshkumar-sheth-269454135/

The agenda of this blog is to introduce you all to a relatively new technology by Microsoft called Microsoft Intelligent Edge.

What Is Windows Azure?

Windows azure is Microsoft cloud computing platform that to run a application and scale. It takes a application centric view of cloud computing that manages entire life cycle of the application. From development to testing to deployment with a touch of a button to motoring and scaling the application and running on internet that helps to understand the application and analyses it so that we can build and better version and deploy on cloud without incurring any downtime.

What is IOT?

IOT stands for Internet of Things. By 2020 there will be 50 billion objects connected to the internet with a total population of about juts 7.6 billion. Which means there will be 6.6 objects per head connected to the internet. Devices are given an opportunity to sense, control and communicate with other devices that enables an efficient working of a module. IOT is becoming increasing popular with as it can make humans life easier with almost no effort. Makes lifes easier than a Robot maybe?

What is Microsoft Intelligent Edge?

Microsoft Intelligent Edge takes information from cloud and runs on IOT devices. It harnesses signal from real world or real time from iot device and puts more intelligence. It is cross platform supported by Windows and Linux. It enables development and testing of edge workloads in the cloud with later deployment the edge as part as a continuous integration and deployment.

Edge runtime gives services for the rest of the infrastructure on the box. Each edge run time itself would be trusted, meaning that with each boot time and even whenever anything happens in memory, edge run time would continue. Isolation of devices- Downstream can be managed from edge run time and this is gives flexibility of run time as well as for scale. Modules are managed by edge runtime. One can add capabilities to runtime like machine learning function and analytics, cognitive services. These are packaged in a container which has certain properties. Performs an action based on certain input and output. Any kind of routing is possible. Any number of modules can communicate with each other or not set as per user.

It has seamless deployment of advanced capabilities such as multiplexing to any 3rd party available in 36 centers across the globe. Getting insights and actions are externally possible too, but cloud helps to scale the information and share it across the globe and provides intelligence.

image

Microsoft Intelligent Edge uses connection from azure iot hub which is secure to establish a communication. Detect that the network is disappeared and start storing and network comes back and start forwarding it to cloud. Edge will be managed from cloud, so when the device is online, it is accessed through the cloud. Edge will give instructions and the instruction will tell edge to load from the cloud and run locally.

One of the biggest concern of firms is security. A secure connection from device to iot edge is established, updates and controls the telemetry and monitor security of the device. Privacy of data and protection. With iot hub you get security and device management, one can bring down insights, alerts and other operations happening to the cloud, in the cloud down to device. While sharing the information across the globe, the developer can share only some data while keeping the rest to cloud.

How does IOT helps while working on projects?

As engineering students, we continuously work on interesting projects. Often it happens that we are unable to log every change that we have made to the hardware or the code, IOT edge comes very handy. All you would have to do is get Azure IOT Hub and download Edge on the single board computers like Raspberry Pi or Arduino. After appropriate coding, one can easily reflect through the changes.

A typical student’s life with IOT Edge.

image

How can this lead to a prospective career?

There are two main parts of Edge role. One is Development that is the back end and Operation of the Edge will be the front End. One can get involved in the following manner:

· Cloud development

· Coding platform eg: Visual Studio

· Develop and Test

· Deployment and scaling

· Managing large workplaces

· Feedback and Alert System

Resources

Azure IOT Edge, Make hybrid cloud and edge Internet of Things (IoT) solutions a reality with Azure IoT Edge, a service that delivers cloud capabilities to the edge. IoT Edge provides easy orchestration between code and services, so they flow securely between cloud and edge to distribute intelligence across IoT devices. Easily integrate Microsoft Azure and third-party services, or augment existing services to create a custom IoT application with your own business logic. You get the best of both worlds with devices that can act locally based on the data they generate, while also taking advantage of the cloud to configure, deploy, and manage them securely and at scale.

Try out Azure IOT Edge Preview for Microsoft Azure https://azure.microsoft.com/en-us/campaigns/iot-edge/

Microsoft Docs on Azure IOT Edge https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-iot-edge-overview

Azure IOT Edge Extending Intelligence https://blogs.microsoft.com/iot/2017/05/10/microsoft-azure-iot-edge-extending-cloud-intelligence-to-edge-devices/

You can get IOT Edge on GitHub here https://github.com/azure/iot-edge

You can get started with Microsoft Azure here https://portal.azure.com/

Draw a Picture of Halloween with Small Basic

$
0
0

Let's draw a picture of Halloween with Small Basic.  Happy Halloween!

Screen shot of a program Halloween 2017

This program ID is TGR736.

It has never been easier… (NAV on Docker #2)

$
0
0

As of this morning, all shipped cumulative updates (+ all localizations) of Microsoft Dynamics NAV 2016 and 2017 are available as Docker images in the Docker Hub, ready for execution on a Windows system with Docker installed.

How do I use them?

This means, that if you have a computer running Windows 10 Professional edition or Windows Server 2016, you can install Docker (follow this blog post until the Set up an ASP.NET... section or for Windows Server 2016, you can install the EE version by following this blog post) and run:

C:>docker run -e accept_eula=Y -m 4G microsoft/dynamics-nav

in a Command Prompt running as Administrator and get the W1 country version of the latest cumulative update of the latest version of NAV running on your computer within a few minutes (the first time will take more time for downloading base components)

Or you can run any other cumulative update (of 2016 or 2017), just by specifying the version, the CU and the country version you want as a tag:

C:>docker run -e accept_eula=Y -m 4G microsoft/dynamics-nav:2016-cu5-dk

Note: One of my next posts will be a troubleshooting blog post - what can you do if things doesn't work.

Where is my NAV!

When you execute the docker run command, Docker will start downloading the image if it doesn't already exist. After downloading the image from the docker hub, you should be seeing something like this:

and if you open up your internet browser and type in the Web Client URL, you should be prompted with a login dialog, where you can login with the NAV Admin Username/Password displayed:

So you are clearly running NAV somewhere but if you investigate your system, you won't find this version of NAV installed. You also might not be running IIS or SQL Server, so how in earth can NAV run on my box with database, Web Client and all?

If you investigate your Hyper-V Manager you also won't see any Virtual Machines, so...

Is it magic?

When every other attempt to explain something fails, it must be magic, right?

Well fortunately, there are good explanations to what you are seeing. You are running NAV in a Container (aka NAV on Docker). It is kind of a Virtual Machine, but then again it isn't. For now, the only thing you really need to know is, that what's inside the container is isolated from the host, meaning that you can run any number of containers (resources allowing) side by side without any conflicts.

Yes, that also means that you can run different versions, different cumulative updates and different localization's of NAV very efficiently side by side.

OK, I get it!, but is this it?

Now you might be thinking: So, I can run the NAV Web Client towards the NAV Demo Database - big deal - but I need much more than that, can I ...???

And you certainly can get much more than that.

In fact, you can:

  • use your own database in the Container
  • connect to your own SQL Server
  • integrate NAV with your AD (and use Windows Authentication)
  • avoid the SSL warning when running locally
  • use the Classic Development Environment and customize NAV
  • use the Windows Client
  • split Web Client and Service Tier
  • and a lot lot more

You can really configure the service tier inside the container the way you want. Some things can be done just by specifying a parameter, some things might require PowerShell code.

The idea is that I will write up a series of blog posts on how to achieve a number of these things.

 

Enjoy

Freddy Kristiansen
Technical Evangelist

JavaScript Unit Test Intergration in VSTS Build Pipeline

$
0
0

VSTS supports any kinds of JavaScript test runner as long as it can be invoked via command line, we can either use Chutzpah with PhantomJS or karma with most popular browsers in its build pipeline. This article will demonstrate how to integrate karma unit test into VSTS and notice that any other test runner just can follow similar patterns to accomplish the integration.

Configure Unit Test

Execute the following commands to initialize the karma test environment:

npm init
npm install karma --save-dev
npm install jasmine-core --save-dev
npm install karma-junit-reporte --save-dev
npm install gulp --save-dev
karma init

The following is the generated karma.conf.js with a little bit code modification:

module.exports = function(config) {
 config.set({

  // base path that will be used to resolve all patterns (eg. files, exclude)
  basePath: '',

  // frameworks to use
  // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
  frameworks: ['jasmine'],

  // list of files / patterns to load in the browser
  files: [
    'specs/*.js'
  ],

  // list of files to exclude
    exclude: [
  ],

  // preprocess matching files before serving them to the browser
  // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
  preprocessors: {
  },

  // test results reporter to use
  // possible values: 'dots', 'progress'
  // available reporters: https://npmjs.org/browse/keyword/karma-reporter
  reporters: ['progress', 'junit'],

  // web server port
  port: 9876,

  // enable / disable colors in the output (reporters and logs)
  colors: true,

  // level of logging
  // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
  logLevel: config.LOG_INFO,

  // enable / disable watching file and executing tests whenever any file changes
  autoWatch: false,

  // start these browsers
  // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
  browsers: ['Chrome'],

  // Continuous Integration mode
  // if true, Karma captures browsers, runs the tests and exits
  singleRun: false,

  // Concurrency level
  // how many browser should be started simultaneous
  concurrency: Infinity
 })
}

Add test case to the spec folder and run "node .node_moduleskarmabinkarma start" should see the test cases can be executed as expected by Chrome.

Integrate with Task Runner gulp

VSTS supports node command task while we can use gulp to drive the test task even easier in a more complex scenario. We can add gulpfile.js shown below to enable this functionality. Then, we should be able to run the test case by invoke command "gulp unittest".

var gulp = require('gulp');
var Server = require('karma').Server;
gulp.task('unittest', function(done){
    new Server({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done).start();
});

Support Headless Testing

Before adding the build pipeline to VSTS, we need think about what build agent we will use to run the test case on. Apparently, the most convenient ways is to use hosted agents which are maintained by VSTS as we don't need to take care of the restart, patch anymore. While, the hosted agents don't have Chrome installed and the above test will always fail because of that. Alternatively, we can use private agent which are maintained by ourselves and can install any required software as we want, we just follow https://docs.microsoft.com/en-us/vsts/build-release/concepts/agents/agents to configure a private host and to VSTS. In this example, I will use a hosted VS2017 agent to make it. In order to run karma on a hosted agent without Chrome installed, we need support headless testing:

  • Run "npm install puppeteer --save-dev"
  • Add "process.env.CHROME_BIN = require('puppeteer').executablePath()" to the beginning of karma.conf.js
  • Change browsers setting from Chrome to ChromeHeadless

Setup Continuous Integration

In VSTS Build & Release tab, add a new build definition. Then add a "npm install" task shown below. WebApp/JSUnitTest is the working folder that contains the project.json.

Add a gulp task shown below, make sure the gulp task name matches the task name defined in the gulpfile.js.

In Triggers tab, enable trigger shown below. Then the CI build process will automatically run the test cases every time a team member commits changes to version control.

Add JUnit Test Report

 

Now any code change to the repository will trigger a new build process, you might want to check the test result instead of a rough test succeed or fail result. Currently, the karma.conf.js has been able to generate junit result by reporters setting. We just need to  enable JUnit Test Results  in gulp task shown below to let VSTS understand where to grab the test result.

Once a build completes, select the build number and we can see the test result in summary.

Hilscher NetPi: Raspberry Pi 3 for industrial automation (Part 1)

$
0
0

Hi!

Over the last weeks, I've been working with a nice little device that is very useful for prototyping professional IoT.

One of the challenges in this area is talking to field bus systems. There are many field busses out there and all of them have their individual reason of existence, either coming from a specific group of hardware vendors (e.g. Profibus and Profinet coming from the Siemens PLC ecosystem) or being adopted in specific application domains (CAN in vehicles). But luckily, there are companies that have implemented hardware and software to talk to many of these busses and Hilscher  is one of those partners. They have implemented their own silicon in form of their NetX chip which is able to speak many of these protocols.

Now enter the NetPI. Hilscher has built an industrial gateway hardware that combines the standard Raspberry Pi 3 Broadcom SOC with a NetX chip. In addition, they took some ideas from the RPi 3 compute module and added an eMMC to replace the ever-failing SD-cards and added a standard 24V industrial grade power supply circuit.

On the software side, the NetPI runs a hardened Linux, Docker and a web-based UI. Via this UI, one can run Docker containers. See here for a list of images provided by Hilscher.

Getting the device up and running is rather straightforward:

Attach Ethernet and 24V (my device is drawing 150 mA, so about 3.6W). The NetPI will do dhcp on its Ethernet port and acquire an IP address. It will also register a hostname which is simply "NT" plus its Ethernet address, that's all printed on its side. Now you can access your device via http://NTxxxxxxxxxxxx or via its IP address http://x.x.x.x that you can find in your router. It will redirect you to https:// and then you will see a certificate warning. Ignore the warning and connect anyway. (In Edge on Windows 10, you need to click on "Details", then "go on to the website". You can upload a certificate to the device, then this error goes away.) Then you will see this:

Here, you can configure the device via the "control panel" or manage Docker. The initial login information is printed on the side as well. (No big secret here: username "admin", password "admin", the device will force you to change the password immediately.) To make things work, you should first check if the clock is set right in the control panel, otherwise you will get a number of strange errors, but their root cause is that the NetPI does not accept any TLS certificates because it thinks they are outside their validity period. So click on control panel, (accept the certificate warnings again) then log in and head to system/time. Now add an NTP server of your preference (I'm using ptbtime1.ptb.de which is the official master clock in Germany) and press "save changes".  Now the clock should update and under "status", the display should read "Synchronized to time server ..." If you don't do this step, there is a high chance that you won't be able to run any Docker images since the TLS-based download of the images will fail!

Now click on the Services/Service List in the menu, then select Docker. Start Docker and set the Docker service to autostart, then click "Apply".

Now head back to the main portal and this time, click on Docker. The quickest way I found is simply to edit the URL and remove anything behind the host name. If you have successfully started Docker, then you will get to the Docker management interface when clicking on the item. If not, then head back to the Service menu and check if Docker is running (the icon next to Docker should be green.) Now you should see the portainer.io Docker management portal. To check if the internet connection is working, go to the "image" section and enter "hilschernetpi/netpi-raspbian:latest" in the Name field under "Pull Image" and click "Pull". Now the image should show up in the image list below. Other useful images to pull are "hilschernetpi/netpi-nodered-fieldbus:latest" and "hilschernetpi/netpi-netx-programming-examples:latest".

To get started, run the Node-RED fieldbus container on your device. The instructions are here. If you want to write code that interacts with the fieldbus directly, look here. This environment can also be used to run the Azure IoT SDK on the NetPi. I will write up more instructions on this in my next post.

Hope this helps,
H.

 

 

 

 

 

 

 

 

 

SQL Server on Linux on Docker quick and easy

$
0
0

Often in conversations with healthcare customers the topic of architecture evolutions or roadmaps come up and in every conversation, is mention of a hybrid strategy – one where use of both on premise and cloud technologies need to be factored into the solution (sometimes both near-term & long-term solutions). In addition to those situations sometimes you just want to quickly stand up SQL Server (for use with a demo of Azure ML Workbench (preview), this happened to me recently). Below is the script I use to get SQL Server up and running quickly using Docker. I usually use a combination of vscode, PowerShell & the appropriate extensions (PowerShell Extension & mssql) to make this easy.

Prerequisites:

  1. Docker for Windows (this should work the same on Linux as well with some slight modifications of source paths & maybe syntax)

Optional:

  1. Visual Studio Code
  2. SQL Server Management Studio (may not be needed if you use mssql extension for vscode).

Install

  1. Install Docker for Windows. This is a simple wizard install. Make sure you have enough memory to run SQL Server in Docker – see this: https://docs.microsoft.com/en-us/sql/linux/quickstart-install-connect-docker

Optionally install the other software. Technically you could run the TSQL code from sqlcmd inside the Docker container but in my setup, I don't usually do that because I want to externalize any data & code from the running container that way I can easily upgrade to new releases of SQL Server as they come and do things like check in my code to a code repository. The rest of the steps can be done when you want to run an instance and serve data but making sure Docker is setup and operational is a good thing to have ready to go.

Start Docker and Run the container

I usually keep Docker turned off and start it up when I need to run a container.

  1. Launch Docker and wait about 30 seconds for it to start up.
  2. Launch vscode and open the PowerShell script with my saved commands.
  3. Run the commands per the script (except the last one). Note that the first time you do the pull it may take a minute or two to download the container image. When you run this the second time docker will check to see if you have the proper image or if a new one needs to be downloaded, if not then docker will save you time and not download the image again.

    # Confirm that Docker is running
    docker ps

    # Start container

    docker pull microsoft/mssql-server-linux:2017-GA

    docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=***************" -p 1433:1433 --name sql1 -d microsoft/mssql-server-linux:2017-GA

     

    # Confirm that the container is running. SQL Server should be up and running now and ready to host data

    docker ps

     

    # Copy sample DB MDF file into container, make sure you change the attach database files to location:

    docker cp C:UsersusernameSampleDataAdventureWorksAdventureWorksLT2012_Data.mdf sql1:/var/opt/mssql/data/AdventureWorksLT2012_Data.mdf

 

  1. Open the .sql file containing the code needed to attach the database and run the command:

    -- Attach the MDF file copied into the container

    USE [master]

    GO

    CREATE
    DATABASE [AdventureWorksLT2012] ON

    (FILENAME
    =
    N'/var/opt/mssql/data/AdventureWorksLT2012_Data.mdf')

    FOR
    ATTACH;

    GO

     

  2. Open console in vscode by pressing Ctrl + Shift + P
  3. Type "connect" and you should see the option MS SQL: Connect, select it and press Enter.
    1. Follow steps to create a connection profile for this locally running SQL Server, once saved you'll just select the profile
  4. Select the code in the script and execute it by pressing Ctrl + Shift + E
  5. You might see response saying that the database has been upgraded in version (I'm seeing upgrade from version 864 to 863 for my MDF file) but as long as the MDF file is in working order the attach should work as planned.
  6. To confirm the attach run SELECT
    name, database_id, create_date FROM
    sys.databases;
    and you should see your database listed there. From that point you can
    run USE command and query as needed.
  7. When finished close all client connections to the server and then go back to cleanup your docker container by running the last line in the script:

    # When finished with SQL Server, use this to stop the container

    docker stop sql1

 

So, there you have it, SQL Server on Linux on Docker on Windows in 10 easy steps. These very simple scripts are saved in this GitHub repo but it's probably easier to just copy and paste or memorize.

 


Education in Australia: transforming for the 2020 economy

$
0
0

Digital transformation is revolutionising Australian education. With students’ learning journeys top of mind, progressive educators and institutions are exploring new ways to prepare today’s students for the challenges of tomorrow.

Together with Harvard Business Review Analytic Services (HBR-AS), we set out to explore how Australian schools and higher education institutions are approaching digital transformation. Our report Education in Australia: transforming for the 2020 economy sheds light on the drivers of change in our education sector and how institutions are embracing digital solutions to improve outcomes.

Driving change

There are three key drivers of change in the Australian education sector. These include the need to:

  1. Remain competitive in a global marketplace
  2. Address national and international skills inequalities
  3. Prepare students to prosper in an uncertain future.

International assessments show Australian school students are falling behind their peers in other countries in literacy, numeracy and science rankings. While this is a threat to our international competitiveness, we’re seeing similar disparities on home soil between geographical areas and groups of varying socio-economic status. Deteriorating skills and unequal skill distribution are serious concerns if we expect Australian children to be able to collaborate with each other and compete in a global employment market.

Our higher education sector is also being pushed to change. Universities and vocational education providers face growing pressure to unbundle their programs and offer more virtual learning opportunities for students who are starting to find existing education routes rigid and impractical.

Uncertainty is another major driver of transformation. To thrive in ambiguous and volatile environments, students need new, unconventional teaching materials and methods that give them practical knowledge and skills they can apply outside an education setting.

Improving outcomes

Our report shows forward-thinking institutions in Australia are already reimagining operations inside and outside the classroom. They are using digital technologies to deliver more engaging and meaningful instruction when, where and how students require it.

One such school system is Catholic Education Western Australia (CEWA), a Catholic education system with nearly 78,000 students and 15,000 staff members across the state. CEWA’s LEADing Lights platform deploys a broad array of cloud-based technologies to empower teachers, provide more equitable access to best-practice learning, and transform student outcomes. CEWA is also developing solutions to help students who live remotely, or who have special needs, to access the richest education programs and experiences. You can learn more about CEWA’s digital platform here.

Looking to the future

New education models push us to re-imagine what we teach and how we learn. By strengthening teachers’ abilities and empowering students to take charge of their own learning experiences, digital transformation can open up a world of opportunity for the Australian education sector.

Microsoft is partnering with schools and tertiary institutions to achieve this transformation. We are helping develop digital solutions that engage students, empower teachers, optimise institutions and transform learning. On top of this, we are championing initiatives to improve the nation’s proficiency in science, technology, engineering and maths (STEM) subjects and helping deploy solutions for stronger and more equitable learning outcomes.

As the Australian education sector continues to embrace change, our schools and universities will improve their international ranking, boost enrolments and retention, and open up employment opportunities. Most importantly, a transformed Australian education sector will be best placed to prepare students to thrive in an unknown future.

You can learn more about how our education sector is transforming in our report Education in Australia: transforming for the 2020 economy.

Finally, I encourage you to join us at Microsoft Summit, 14 November in Sydney. We have a dedicated Education track including; If robots are going to destroy jobs, are they going to destroy education too?, Empowering citizens through digital transformation & Diversity and inclusion – empowering people to achieve more. Register here for your free ticket.

Load Azure Storage Data into Cloudera HDFS

$
0
0

How do I get data from an Azure Storage account into an Azure-deployed Cloudera cluster running HDFS?  This question seems to be coming up with quite a bit of frequency lately, so that I thought I might answer it with a post.

Paige Liu has done an excellent job documenting how to configure Cloudera to read from an Azure Storage account.  You can read her step-by-step instructions here.

So assuming you’ve already moved data into your Azure Storage account using either the Azure Storage Explorer, CLI, PowerShell, AZCopy, the Import/Export Service, or some other data transfer mechanism, once you’ve completed the configuration changes Paige details, you are ready to transfer data using a command like one of the following:

hadoop fs -cp wasbs://mydata@brysmi.blob.core.windows.net/myfiles/ /myhdfsfiles/

hadoop distcp wasbs://mydata@brysmi.blob.core.windows.net/myfiles/ /myhdfsfiles/

In these two examples, brysmi is the name of my Azure Storage account, mydata is the name of the container in that Storage account which holds my files, and myfiles is the folder path under that container where the files (blobs) have been landed.  (The second path, i.e. /myhdfsfiles/, represents the path in HDFS where I want to files copied to.)

Finally, its important to note that distcp works much faster when you have numerous files with a large total storage volume as it copies files in parallel.

Mise en place d’un environnement Azure Machine Learning

$
0
0

Pour utiliser les nouveaux services d'Azure Machine Learning (Azure ML), il convient au préalable créer un compte et les ressources associées sur Azure. Après avoir abordé les évolutions d'Azure ML dans un précédent billet, ce billet vise à vous présenter une vue d'ensemble de la mise en place d'un environnement de travail complet Azure ML en intégrant bien sûr l'installation de l' « établi » Azure ML Workbench et l'outillage en mode ligne de commandes. De plus, dans ce contexte, ce billet est l'occasion de s'intéresser votre environnement de développement intégré (IDE) pour Azure ML Workbench avec Visual Studio Code, la mise en œuvre de la technologie de Docker, etc. pour la science des données.

J'en profite pour remercier Paul Jenny actuellement en stage de fin d'étude au sein de Microsoft France pour cette contribution.

Les prérequis pour Azure ML Workbench

L'application Azure ML Workbench peut être installée sur les plateformes suivantes pour le moment :

  • Windows 10,
  • Windows Server 2016,
  • MacOS Sierra (MacOS High Sierra n'est pas encore supporté).

Qui dit services managés dans Azure, dit abonnement Azure. Si vous n'avez encore de compte Azure, vous pouvez créer un compte gratuit ici.

Nous supposons que vous disposez à ce stade d'un tel compte.

La création d'un compte Azure ML et des services associés

Via le portail Azure

Vous devez au préalable vous connecter au portail Azure avec vos identifiants de compte Azure :

  1. Cliquez sur le bouton Nouveau situé dans le panneau à gauche de votre écran
  2. Recherchez Machine Learning Experimentation.

  1. Sélectionnez Machine Learning Experimentation (preview).
  2. Cliquer ensuite sur Créer.

  3. Un panneau (blade en anglais) ML – Expérimentation s'ouvre. Remplissez le formulaire correspondant en s'aidant des indications ci-dessous :
    1. Nom du compte d'expérimentation : spécifie le nom unique qui identifie votre compte d'expérimentation. Vous pouvez utiliser votre nom, le nom de votre projet ou de votre entité ou département pour identifier au mieux vos expérimentations qui seront effectuées sous ce compte. Le nom doit être entre 2 et 32 caractères (caractères alphanumériques et tiret autorisés).
    2. Abonnement : précise votre abonnement Azure sur lequel sera facturée l'utilisation des services Azure ML.
    3. Groupe de ressources : indique le groupe de ressources à utiliser. Vous pouvez utiliser un groupe existant ou en créer un nouveau selon vos besoins dans votre projet.
    4. Emplacement : spécifie l'emplacement où déployer votre instance. Actuellement, en version préliminaire publique, seules 3 régions sont disponibles : Est des Etats-Unis 2, Est de l'Australie, et Ouest-Centre des Etats-Unis. Choisissez la région la plus proche de vos utilisateurs et de vos données.
    5. Nombre de sièges : indique le nombre d'utilisateurs qui utiliseront ce compte d'expérimentation. Actuellement, les 2 premiers sont gratuits.
    6. Compte de stockage : indique le compte de stockage Azure à utiliser. Vous pouvez utiliser un compte de stockage existant ou créer un nouveau. Ce compte est nécessaire pour stocker l'historique de vos exécutions et les artefacts de vos projets (graphiques, dépendances, etc.)
    7. Espace de travail pour le compte d'expérimentation : spécifie le nom de l'espace de travail. Ce nom apparaîtra dans Azure ML Workbench pour regrouper vos projets de ce compte. Le nom doit être unique et doit faire entre 2 et 32 caractères (caractères alphanumériques et tiret autorisés)
    8. Affecter un propriétaire pour l'espace de travail : spécifie le propriétaire de cet espace. Choisissez une personne qui sera responsable des tâches d'administration de cet espace de travail
    9. Créer un compte Gestion des modèles : Si vous ne souhaitez pas utiliser le service Gestion des modèles d'Azure ML, vous pouvez décocher cette case. Néanmoins, celui-ci vient en complément du service d'expérimentation pour faciliter le déploiement de vos modèles dans le cloud Azure, en bordure ou en local.
    10. Nom du compte : précise le nom unique qui identifie votre compte de Gestion des modèles. Vous pouvez utiliser votre nom, le nom de votre projet ou de votre département pour identifier au mieux vos expérimentations qui seront effectuées sous ce compte. Le nom doit être entre 2 et 32 caractères (caractères alphanumériques et tiret autorisés)
    11. Niveau tarifaire de la Gestion des modèles : spécifie le niveau tarifaire. Choisissez le niveau tarifaire au nombre de modèles vous allez déployer et le nombre de cœurs alloués à ce déploiement. Le niveau « DEVTEST » est gratuit mais néanmoins limité en nombre. De préférence, pour les besoins de ce billet et des suivants sur le même sujet, vous pouvez choisir celui-ci.
  4. Cliquez enfin sur Créer pour créer votre compte d'expérimentation (et le compte Gestion des modèles si vous avez coché la case – ce que nous suggérons ici -)
  5. Attendez le déploiement effectif des services qui sera indiqué par une notification :

L'installation d'Azure ML Workbench en environnements Windows

Comme indiqué en début de ce billet, Azure ML Workbench est disponible pour Windows 10 et Windows Server 2016.

Pour procéder à l'installation de l' « établi » en environnements Windows, téléchargez et exécutez le programme d'installation d'Azure ML Workbench via l'explorateur de fichiers. L'installation inclut les dépendances nécessaires comme Python, Miniconda, Azure CLI (avec Azure ML CLI). Elle peut prendre une trentaine de minutes pour se terminer.

L' « établi » Azure ML Workbench est installé dans le répertoire suivant :

C:Users<user>AppDataLocalAmlWorkbench

L'installation d'AML Workbench sur MacOS

Azure ML Workbench est actuellement disponible pour MacOS Sierra uniquement. Vous devez au préalable installer la dernière version d'OpenSSL en utilisant Homebrew. Vous pouvez vous référer aux prérequis de .NET Core pour MacOS pour plus d'informations.

# install Homebrew first if you don't have it already

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

 

# install latest openssl needed for .NET Core 1.x

brew update

brew install openssl

mkdir -p /usr/local/lib

ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/

ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/

Pour procéder à l'installation de l' « établi » sur MacOS Sierra, téléchargez la dernière version d'Azure ML Workbench puis installer en utilisant Finder (l'installation depuis le navigateur peut poser des problèmes). L'installation inclut les dépendances nécessaires comme Python, Miniconda, Azure CLI (avec Azure ML CLI). Elle peut prendre une trentaine de minutes pour se terminer.

L' « établi » Azure ML Workbench est installé dans le répertoire suivant :

/Applications/AmlWorkbench.app

L'installation de Docker

Pour pouvoir utiliser le nouveau service d'expérimentation d'Azure ML dans un contexte local (c.à.d. pouvoir entraîner un modèle dans un conteneur Docker local), vous devez, au préalable, installer la technologie Docker.

Actuellement, Docker n'est supporté que sur les versions 64 bits de Windows 10 Pro, Entreprise et Education à jour et MacOs El Capitan (ou plus récent).

  • Pour télécharger Docker pour les environnements Windows, vous pouvez retrouver le programme d'installation ici.
  • Pour télécharger Docker sur MacOS, vous pouvez retrouver le programme d'installation ici.

Remarque : Le service Docker a besoin d'une quantité importante de mémoire vive (RAM) pour pouvoir fonctionner. Si la mémoire est insuffisante, vous serez amené(e) à désactiver ou éteindre des applications au préalable.

L'installation de Visual Studio Code

Un environnement de développement intégré (IDE) est nécessaire pour pouvoir développer vos projets. Parmi les environnements pris en charge par l' « établi », nous vous conseillons l'utilisation de Visual Studio Code, un éditeur multi-plateformes développé par Microsoft sous licence Open Source MIT. Celui-ci, au-delà de ses caractéristiques intrinsèques, s'accompagne d'un écosystème important d'extensions pour étendre la liste s'il en était besoin des fonctionnalités proposées.

Vous pouvez récupérer la dernière pour MacOS et Windows ici. Une fois le logiciel installé, il faut installer les différentes extensions utiles pour la science des données disponibles depuis la place de marché (Marketplace) des extensions, et en particulier :

  • Visual Studio Code Tools for AI : cette extension a été annoncée en même temps que les nouveaux services d'Azure ML. Cette dernière apporte le support des technologies d'apprentissage automatique (Machine Learning) et d'apprentissage profond (Deep Learning). Vous pourrez notamment profiter des services d'Azure ML (service d'expérimentation et service de gestion des modèles), l'auto-complétion d'IntelliSense et des suggestions avec les derniers Frameworks de Data Science (Cognitive Toolkit de Microsoft, Tensorflow de Google, etc.) ainsi que parcourir la liste des exemples d'Azure ML depuis l'éditeur intégré !
  • Docker (optionnel) : cette extension ajoute le support de la technologie Docker dans l'éditeur. Vous pourrez alors générer des Dockerfile (fichiers pour construire une image Docker), profiter de l'auto-complétion d'IntelliSense dans le contexte d'un fichier de Docker ou encore effectuer des actions (build, save image, etc.) depuis la palette de commandes de Visual Studio Code.
  • Python : cette extension ajoute le support du langage Python depuis l'éditeur. Vous pourrez ainsi profiter d'IntelliSense pour Python (auto-complétion, suggestions, etc.), exécuter des scripts Python depuis l'éditeur via le lancement d'une invite de commandes, mettre en forme du code, etc.
  • Jupyter (optionnel) : cette extension ajoute le support des bloc-notes Jupyter depuis l'éditeur. Vous pourrez écrire puis exécuter vos blocs-notes depuis Visual Studio Code. Néanmoins, nous considérons celle-ci comme optionnelle car Azure ML Workbench apporte le support des blocs-notes directement depuis son interface.
  • : cette extension ajoute le support de l'autre langage principal de la science des données, à savoir R. Vous pourrez profiter ainsi de la coloration syntaxique, exécuter des scripts R depuis l'éditeur dans l'invite de commandes intégrée ou encore bénéficier de lintr (outil d'analyse de code pour corriger la mise en forme, etc.).

Remarque : L'ensemble de ces extensions peuvent être installées directement depuis Visual Studio Code. Pour cela, appuyez sur CTRL + Shift + X pour afficher la fenêtre des extensions. Vous pourrez ensuite rechercher les différentes extensions ci-dessus.

La palette des commandes de Visual Studio Code est affichable en appuyant sur CTLR + Shift + P ou en allant dans Afficher / Palette de commandes…. Par exemple, pour accéder aux commandes pour l'IA, vous pouvez taper « AI » :

En sélectionnant AI : List Jobs, vous pourrez par exemple accéder à toutes les différentes expérimentations de votre projet directement depuis Visual Studio Code :

Le premier lancement d'AML Workbench

Si vous n'avez pas cliqué sur le bouton Launch Workbench à la fin du programme d'installation d'Azure ML Workbench ou si vous avez fermé l'application, vous pouvez double-cliquer sur l'icône sur votre bureau pour pouvoir la lancer :

  1. Dans la fenêtre de connexion, connectez-vous avec vos identifiants de votre abonnement Azure que vous avez utilisé précédemment
  2. Une fois que la connexion est réussie, Azure ML Workbench recherche tous les comptes d'expérimentation associées à vos abonnements Azure. Il utilise par défaut le premier compte d'expérimentation qu'il trouve et affiche les projets et espaces de travail associés. Si vous avez accès à plusieurs comptes d'expérimentation, vous pouvez changer le compte courant en cliquant sur l'icône avec votre avatar située en bas à gauche d'Azure ML Workbench.
  3. Vous pouvez maintenant parcourir les exemples proposés en créant un nouveau projet via le bouton + situé à droite de vos espaces de travail.

La configuration de Visual Studio Code avec Azure ML Workbench

Azure ML Workbench n'est pas un éditeur de texte. Il est déconseillé d'éditer directement des fichiers depuis le logiciel malgré la présence de fonctionnalités basiques pour l'édition. Visual Studio Code vient donc en complément des nouveaux services pour fournir un environnement de développement de solutions de science des données complet.

Depuis Azure ML Workbench, accédez au menu File puis Configure Project IDE. Un menu s'ouvre sur la droite de l'application.

  • Dans Name, vous pouvez indiquer le nom que vous voudrez. Celui s'affichera dans le menu File une fois ce paramétrage terminé.
  • Dans Executable Path, vous devez parcourir votre ordinateur pour rechercher l'exécutable de votre éditeur (Code.exe pour Visual Studio Code). Par défaut, il est situé dans le répertoire C:Program FilesMicrosoft VS CodeCode.exe.

Une fois paramétré, lorsque vous aurez sélectionné au préalable un projet dans Azure ML Workbench, dans le menu File, vous aurez Open Project (VOTRE EDI) :

En cliquant sur Open Project, Visual Studio Code s'ouvre dans le répertoire de votre projet Azure ML Workbench. Vous pourrez ainsi éditer les fichiers depuis l'éditeur de Visual Studio.

Votre environnement Azure ML est à ce stade installé et configurer sur votre machine. Vous pouvez maintenant utiliser Azure ML Workbench ou les outils en ligne de commande pour interagir avec les nouveaux services. Abordons la partie « Docker ».

La configuration de Docker avec Azure ML

Afin d'accélérer la remontée des informations de votre exécution par télémétrie, il est conseillé d'activer le partage de votre disque local. De plus, ce paramétrage est nécessaire si vous souhaitez utiliser le répertoire partagé entre votre hôte et votre conteneur (Cf. La Gestion des fichiers dans votre projet Azure ML ci-dessous).

Pour modifier le paramètre, une fois Docker lancé, vous pouvez atteindre le panneau de configuration de Docker en effectuant un clic-droit sur l'icône Docker située dans votre zone de notifications pour Windows puis Settings :

Une fois la fenêtre, vous devez aller dans Shared Drives puis cocher la case située à gauche de votre lecteur (sur lequel est situé Azure ML Workbench dans un contexte local de préférence) puis Apply :

La gestion des fichiers dans votre projet Azure ML

Grâce aux nouveaux services d'Azure ML, vous pouvez aisément exécuter vos scripts d'un projet dans différents contextes, qu'ils soient distants (Docker, HDInsight, etc.) ou locaux (Docker, Python ou R). Néanmoins, cette facilité d'opérationnalisation des projets apporte certaines subtilités quant à la gestion des fichiers (lecture, écriture). En effet, pour respecter les principes de reproductibilité et portabilité (quel que soit le contexte de calcul de l'exécution précédente, si vous exécutez le même script deux fois, vous obtiendrez le même résultat), certaines contraintes ont été ajoutées, étant donné qu'à chaque expérimentation, l'ensemble de votre projet est copié dans le contexte d'exécution.

Ainsi, stocker des fichiers lourds dans votre projet est fortement déconseillé. Une limite est actuellement mise à 25 Mo pour forcer l'utilisation d'alternatives. Il existe actuellement 3 solutions (cumulables) :

  1. Utiliser le répertoire de sortie outputs du projet.
  2. Utiliser le répertoire partagé.
  3. Utiliser un espace de stockage externe.

Voyons ce qu'il en est.

Utiliser le répertoire de sortie outputs du projet

La première option consiste à utiliser un répertoire prévu dans le fonctionnement des services d'Azure ML. Les fichiers situés dans ce répertoire sont versionnés et peuvent être récupérés ultérieurement (grâce au service d'expérimentation). Par exemple, on pourrait imaginer stocker un modèle entrainé qui a été produit par le script ou encore un graphique (une matrice de confusion, etc.)

Attention : En versionnant des fichiers, vous utilisez du stockage dans Azure. Cela peut entraîner un (très léger) surcoût.

En bref, cette option s'avère préférable pour les conditions suivantes :

  • Vous produisez des fichiers (un modèle, des jeux de données, etc.)
  • Ces fichiers sont susceptibles d'être différents entre deux expérimentations
  • Vous souhaitez conserver un historique de ces fichiers

Pour recourir à cette option, vous devez écrire les fichiers que vous désirez garder dans un répertoire nommé outputs situé à la racine de votre projet. Le service d'expérimentation détectera automatiquement les fichiers et effectuera le traitement nécessaire pour les versionner. Les fichiers pourront ensuite être téléchargés depuis l'interface d'Azure ML Workbench ou via la ligne de commande Azure CLI suivante :

az ml asset download

Utiliser le répertoire partagé

La seconde option conste à utiliser le répertoire partagé entre les expérimentations d'Azure ML. A la différence du répertoire précédent, les fichiers dans ce répertoire ne sont pas versionnés et ne peuvent être téléchargés. Par conséquent, les fichiers situés dans ce répertoire ne peuvent être utilisés que par les scripts s'exécutant dans un même contexte.

En conséquence, il est préférable d'utiliser cette solution dans les cas suivants :

  • Votre script génère des fichiers intermédiaires utilisés ultérieurement par un autre script (par exemple, un script de scoring a besoin d'un modèle entrainé précédemment par un script d'apprentissage ; un jeu de données qui aura été modifié par un script auparavant)
  • Votre script a besoin de données situées dans le même contexte (fichiers CSV, images, etc.)

Pour recourir à cette option, vous devez utiliser la variable d'environnement AZUREML_NATIVE_SHARED_DIRECTORY dans votre script et configurer l'emplacement du répertoire dans le fichier de configuration .compute de votre contexte d'exécution avec le paramètre nativeSharedDirectory. Par défaut, il est fixé à :

  • ~/.azureml/share/ pour les environnements sous Linux.
  • C:users<username>.azuremlshare<exp_acct_name><workspace_name><proj_name> pour les environnements Windows.
  • /Users/<username>/.azureml/share/<exp_acct_name>/<workspace_name>/<proj_name>/ sous MacOS.

Il existe un cas particulier où vous devez paramétrer une variable supplémentaire. En effet, lorsque vous procédez à une exécution dans un contexte Docker qu'il soit local ou distant, vous devez ajouter la variable sharedVolumes à true :

  • sharedVolumes: true
  • nativeSharedDirectory: ~/.azureml/share

Depuis Docker, ce répertoire partagé entre l'hôte et le conteneur est toujours défini comme étant /azureml-share/. Néanmoins, pour des soucis de compatibilité future, il est conseillé d'utiliser la variable d'environnement AZUREML_NATIVE_SHARED_DIRECTORY au lieu du chemin absolu vers ce répertoire.

Remarque : Pour utiliser ce paramètre sous Docker, vous devez activer le partage du disque local avec vos conteneurs dans Docker. Cf. section « La configuration de Docker avec AzureML ».

Utiliser un espace de stockage externe

La dernière option consiste à utiliser un espace de stockage externe pour persister des données à travers vos différentes expérimentations (support externe physique comme une clé USB accessible par le contexte de calcul, espace de stockage en ligne, etc.). Il est préférable d'utiliser cette alternative dans les cas suivants :

  • Vous n'avez pas besoin de versionner ces fichiers ;
  • Ces fichiers sont utilisés dans des contextes de calcul différents (par exemple, sur une machine distante) ;
  • Vos données sont déjà stockées dans un espace de stockage externe.

Une des solutions est d'utiliser un stockage Blob dans Azure. Vous devez, au préalable, avoir créé pour cela un compte de stockage Azure dans votre abonnement Azure. Pour cela, vous devez naviguer vers le portail Azure puis aller dans Comptes de stockage et Ajouter :

Les fichiers contenus dans le stockage Blob sont situés dans des conteneurs. Ci-dessous, vous pourrez trouver un exemple pour créer et téléverser des fichiers en Python ici (d'autres langages sont disponibles dans la documentation).

En guise de conclusion

Votre environnement Azure ML est à ce stade installé et configuré. Vous possédez une large palette d'outils pour développer des solutions de Machine Learning et de Deep Learning.

Dans le prochain billet, vous apprendrez à utiliser les services avec un cas d'exemple de bout-en bout : la maintenance prédictive.

En attendant, vous pouvez parcourir la documentation officielle ici 😉

Premiers pas avec les nouveaux services d’Azure Machine Learning – 1ère partie

$
0
0

Pour faire suite à notre première introduction sur les évolutions d'Azure Machine Learning (Azure ML) et sur la configuration de l' « établi » et des services associés, nous souhaitons vous donner à présent au travers de ce billet (en deux parties) un premier aperçu des capacités du nouvel environnement Azure ML, c.à.d. le service d'expérimentation, le service de gestion des modèles et bien sûr l' « établi » (Azure ML Workbench), sur un jeu de données en rapport avec la maintenance prédictive.

Après une rapide présentation des objectifs et des prérequis, cette première partie aborde le jeu de données que nous nous proposons d'utiliser pour la circonstance et l'étape clé de préparation de celui-ci. Une seconde partie couvrira sur cette base l'apprentissage de nos modèles à proprement parler.

J'en profite pour remercier Paul Jenny actuellement en stage de fin d'étude au sein de Microsoft France pour cette contribution.

Nos objectifs pour ce billet

Comme souligné ci-avant, ce billet vise à proposer une illustration de bout en bout du nouvel environnement Azure ML. Pour ce faire, cette illustration simple utilise un algorithme d'apprentissage profond (Deep Learning) avec comme objectif de pouvoir prédire si un équipement va tomber en panne prochainement pour optimiser la maintenance de celui-ci. Le modèle obtenu pourra être déployé directement sur/à proximité de l'équipement au sein de son informatique embarquée par exemple : un cas d'usage typique des scenarii de l'Internet de vos objets (IoT).

Cette illustration utilise pour cela un jeu de données provenant de capteurs d'un moteur d'un moteur d'avion. (Une étude réalisée à partir de ce jeu de données sur la modélisation de la propagation des dommages est disponible ici sur la forge GitHub.)

L'algorithme utilisé pour la classification binaire est ici un réseau de neurones récurrents de type LSTM (Long-Short Term Memory), qui s'avère particulièrement efficace lorsqu'il s'agit d'étudier des « tendances » dans des données périodiques. En effet, les données sont remontées régulièrement par les capteurs et nécessitent donc d'être analysées par « cycle » pour obtenir une tendance générale (notamment à cause du bruit induit par le capteur).

En résumé, les objectifs pour ce billet sont :

  • L'utilisation de l' « établi » Azure ML Workbench,
  • L'utilisation d'un bloc-notes Jupyter,
  • La création d'un algorithme de classification binaire pour prédire si le moteur va se dégrader, dans une fenêtre de temps donnée (ici un cycle moteur),
  • L'utilisation du service d'expérimentation d'Azure ML,
  • L'utilisation du service de gestion de modèles pour un déploiement futur sur un équipement. (IoT, etc.).

Avertissement : ce tutoriel n'a pas pour but de générer le modèle le plus « précis ». De nombreuses pistes d'amélioration sont exposées à la fin de ce billet pour les lectrices et lecteurs de ce blog souhaitant aller plus en profondeur. Il s'agit ici de couvrir une première utilisation de bout ne bout du nouvel environnement Azure ML.

Quelques prérequis

Pour les besoins de l'exercice, ce tutoriel suppose les prérequis suivants :

  • Disposer de bases en Machine Learning (et notamment les réseaux de neurones),
  • Bénéficier d'un compte Azure actif (Cf. billet précédent),
  • Avoir installé les nouveaux services d'Azure (voir le billet précédent ici),
  • Avoir créé un compte de stockage Azure pour le stockage des jeux de données via un blob,
  • Avoir téléchargé le jeu de données utilisé ici issu de la NASA,
  • Disposer des bases en Python,
  • Avoir téléchargé les scripts Python et les fichiers de configuration du projet en pièce jointe de ce billet.

Le jeu de données

La première étape d'un scénario d'analyse de données consiste à explorer le jeu de données à la recherche de tendances, d'incohérences, de valeurs manquantes, etc.

Les fichiers texte sont des jeux de données séparées par un espace. Chaque ligne représente une capture des différentes données provenant des capteurs des moteurs sur un cycle donné.

Les colonnes représentent :

  • Le n° du moteur
  • Le moment auquel la capture a été faite, en cycles,
  • Le paramètre n°1 du moteur,
  • Le paramètre n°2 du moteur,
  • Le paramètre n°3 du moteur,
  • La mesure du capteur n°1,
  • La mesure du capteur n°2,
  • ...
  • La mesure du capteur n°26.

Quatre scénarios (FD001, FD002, FD003, FD004) ont été simulés pour tester le moteur sous différentes conditions (altitude de l'avion et dégradation du moteur).

Les données ont déjà été séparées en données d'entraînement (train_FDXXX.txt)
et données de test (test_FDXXX.txt) :

  • Dans les données d'entraînement, les observations sont récoltées à chaque cycle jusqu'à la panne du moteur. La dernière ligne pour chaque moteur représente ainsi son dernier cycle avant ladite panne moteur.
  • Dans les données de test, la dernière observation ne représente pas le dernier cycle avant panne moteur.

Afin de valider nos modèles, le temps restant réel pour les données de test a été ajouté dans des fichiers distincts (RUL_FDXXX.txt).

Pour les besoins de notre illustration, nous allons nous consacrer uniquement sur un seul scénario : FD001. Dans les jeux de données, nous avons ainsi :

  • Train_FD001.txt : ~20 000 lignes et 100 moteurs,
  • Test_FD001.txt : ~13 000 lignes et 100 moteurs,
  • RUL_FD001.txt : 100 lignes (une pour chaque moteur).

Nous voulons répondre à la question suivante dans le cas de la classification binaire :

Est-ce que le moteur va tomber en panne dans les X prochains jours ? (X est un paramètre choisi par le client).

La préparation du jeu de données

Nous allons commencer par créer notre projet sur l' « établi » Azure ML Workbench. Pour cela, lancez l'application Azure ML Workbench et cliquer sur le + situé sur la droite de votre espace de travail puis sur New Project :

Nous vous laissons le soin de donner un nom à ce projet et choisissez pour cela Blank Project. Copiez ensuite dans le dossier du projet les fichiers fournis en pièce jointe de ce billet. Ceux-ci sont les scripts Python pour l'apprentissage et la configuration du projet.

Nous allons ensuite importer nos différents fichiers dans le projet :

  • Cliquez sur l'icône Data
    puis sur le + et Add Data Source.
  • Choisissez ensuite File(s) / Directory puis Local et recherchez votre fichier train_FD001.txt.

  • Dans la fenêtre suivante, dans la liste déroulante de Promote Headers Mode, sélectionnez No headers. Cela a pour effet d'indiquer à AML Workbench de ne pas sélectionner la première ligne du fichier en tant que libellés de colonnes.
  • Ensuite, vous pouvez sélectionner le type (Numeric, String, Date, Boolean) de vos colonnes. Azure ML Workbench a essayé de déterminer pour vous le type.

     

  • Enfin, dans la fenêtre Sampling, vous pouvez séparer vos données pour ne pas charger l'ensemble du jeu ce qui pourrait amener à une consommation excessive de mémoire vive. Néanmoins, comme le jeu de données est ici relativement léger, nous pouvons considérer de charger l'ensemble du jeu en mémoire. En conséquence, cliquez sur Edit puis dans Sample Strategy la méthode Full File.

  • Dans la dernière fenêtre Path column handling, sélectionnez Do Not Include Path Column. Le chemin du fichier peut être utile pour pouvoir extraire des informations qui ne sont pas présents autrement dans le jeu de données. (Par exemple, nous pourrions ici filtrer par scénario moteur si l'on mélangeait tous les jeux de données disponible dans le dossier de la NASA).

  • Cliquez enfin sur Finish.

Vous pouvez vous déplacer dans ce tableau sans éditer les données ou les colonnes. Cette étape permet d'explorer un jeu de données, de gérer les valeurs manquantes, etc.

La barre verte située sous le nom des colonnes représente la proportion de valeurs présentes (vert), valeurs manquantes (gris) et erreurs (rouge). On peut donc ainsi facilement déduire que notre jeu de données d'entraînement ne comprend aucune valeur manquante. Ensuite, on remarque deux colonnes vides situées à la fin sont présentes. Il convient donc de (penser à) les supprimer. Cela est vraisemblablement dû à une erreur de formatage du fichier source.

Nous pouvons enfin aussi regarder des métriques (distribution, fréquence, moyenne) sur nos colonnes en cliquant sur la commande Metrics juste au-dessus du tableau.

Vous pouvez à présent effectuer les mêmes opérations pour le jeu de données de test (test_FD001.txt) et le fichier de vérité (RUL_FD001.txt).

Vous devez vous retrouver ainsi avec 3 sources de données :

Deux choix s'offrent à vous ensuite pour préparer le jeu de données :

  • Vous pouvez utiliser un code en Python dans un bloc-notes Jupyter (1_dataprep.ipynb) ;

-ou-

  • Vous pouvez passer l'excellent outil de préparation des données d'Azure ML Workbench.

Quelle que soit l'approche, deux fichiers CSV (train.csv et test.csv) sont créés pour l'apprentissage de nos modèles dans le dossier de votre projet et/ou dans un stockage Blob dans votre compte de stockage Azure.

Voyons ce qu'il en est.

Avec un bloc-notes Jupyter

Pour accéder au bloc-notes Jupyter associé, vous pouvez cliquer sur l'icône sur la gauche d'Azure ML puis sur le bloc-notes 1_dataprep. Vous devez ensuite lancer le serveur Jupyter en cliquant sur Start Notebook Server.

Vous connaissez ensuite les opérations pour pouvoir exécuter les différentes cellules.

Avec Azure ML Workbench

Pour préparer vos jeux de données, sélectionnez tout d'abord la source de données. Commençons par la source « train_FD001 ». Cliquez sur le bouton Prepare situé au-dessus du tableau.

Nommez le fichier de préparation de données « train ». Vous retrouvez ici exactement la même interface que précédemment. Cependant, vous pouvez dorénavant supprimer des colonnes, exécuter des codes Python, etc.

Commençons par exemple par supprimer les deux dernières colonnes vides. Sélectionnez les deux colonnes par l'appui de la touche CTRL puis cliques-droit sur Remove Column. Une nouvelle étape est ajoutée sur la droite de l' « établi ». Vous pouvez ainsi aisément revenir en arrière, visualiser les différentes étapes qui vont ont permis de préparer votre jeu de données.

L'outil supporte également l'ajout de transformation en Python. Par exemple, vous pouvez renommer les colonnes. Pour cela, allez dans la barre de tâches / Transforms / Transform Dataflow (Script). Une fenêtre vide s'affiche avec les instructions pour écrire vos transformations en Python. Renommez les colonnes avec le code ci-dessous :

capteurs = ["c{0}".format(i) for i in range(1,22)]

params = ["param{0}".format(i) for i in range(1, 4)]

columns = ["id","cycle"] + params + capteurs

df.columns = columns

Cliquez sur OK. Après quelques secondes, vous pouvez apercevoir que vos colonnes ont changé de nom et une nouvelle étape a été ajoutée à votre préparation de données.

Nous allons ensuite effectuer une seconde transformation pour pouvoir récupérer le RUL (pour rappel, Remaining Use of Life) pour chaque cycle d'un moteur.

df['cycle_max'] = df.groupby(['id'])['cycle'].transform(max)

df["RUL"] = df["cycle_max"] - df["cycle"]

del df["cycle_max"]

Pour gérer notre cas de classification binaire, il est nécessaire qu'on le puisse générer le libellé associé à la classe. (Pour rappel, nous souhaitons savoir si un moteur va tomber en panne dans X jours).

Nous allons ainsi utiliser une autre transformation d'Azure ML Workbench, à savoir Add Column (Script) :

  • New Column Name : spécifie le nom de la colonne créée (ici, broken_30_cycles)
  • Insert this New Column After : indique à quelle position cette colonne doit-elle être ajoutée ?
  • New Column Code : précise le code pour générer la colonne

    1 if row.RUL < 30 else 0

  • Code Block Type : indique comment votre code doit être interprété ? (Expression ou module Python)

Nous avons choisi ici un nombre de jours défini à 30 avant la panne. Grâce à l'utilitaire, vous pouvez facilement éditer cette valeur via cette étape ultérieurement sans parcourir tout votre code. Cliquez sur OK.

Notre jeu de données d'entraînement est maintenant prêt. Nous allons à présent l'exporter vers un format plus simple à manipuler aisément, un fichier CSV. Pour cela, retournez dans le menu Transforms puis sélectionnez Write to CSV.

Vous pouvez aussi exporter vers un fichier Parquet pour l'écosystème Apache Hadoop dans le cas de fichiers lourds. Exportez ce fichier :

  • Dans le dossier de votre projet avec le nom « train.csv » si vous souhaitez effectuer l'entraînement en local ;

-ou-

  • Sur un stockage Blob dans (un compte de stockage) Azure si vous souhaitez effectuer l'entraînement du modèle sur une cible distante.

Remarque : Vous pouvez exporter les données vers différentes cibles. Ainsi, vous pouvez créer une étape pour l'exportation vers un dossier local et une autre étape pour l'exportation vers stockage Blob dans (un compte de stockage) Azure.

Nous pouvons à présent passer à la préparation des données de test. Retournez pour cela sur la source de données test_FD001 puis cliquez sur Prepare. Choisissez bien l'option + New Data Preparation Package afin de créer un nouveau fichier de préparation de données.

Nous allons effectuer une opération identique à la précédente pour supprimer les colonnes et renommer les colonnes restantes (Cf. ci-dessus pour le code asscoié).

Un aspect intéressant de l'outil de préparation est de pouvoir fusionner plusieurs sources de données dans un seule et même fichier de préparation de données. Cliquez sur la source de données RUL_FD001 puis sur Prepare. Cette fois-ci, choisissez le dprep (Data Preparation Package) test (celui que vous venez de créer). Vous avez ainsi dans votre dprep deux flux de données, test_FD001 et RUL_FD001. Nous allons ajouter dans RUL_FD001 l'index de nos différents moteurs (qui correspond au numéro de la ligne). Pour cela, ajouter une transformation Transform Dataflow (Script) :

df.insert(loc = 0, column="moteur",value= df.index + 1)

Cliquez sur OK.

On va ensuite renommer la colonne Line par RUL_restants. Vous pouvez double-cliquer sur le nom de la colonne ou effectuer un clic-droit puis Rename Column pour effectuer cette action.

Une fois ceci effectué, passons à la fusion de nos deux flux de données : notre fichier de vérité et notre fichier de test. Pour cela, effectuez une nouvelle transformation Join. Choisissez pour Left le flux test_FD001 et pour Right le flux RUL_FD001 puis cliquez sur Next.

Azure ML Workbench va tenter de déterminer les colonnes sur lesquelles les jointures devront être effectuées. Néanmoins, ici, cela ne fonctionne pas… Choisissez pour lui en cliquant sur la colonne id de test_FD001 et sur la colonne moteur de RUL_FD001 puis cliquez sur Next.

Azure ML Workbench affiche alors un aperçu de la jointure avec les lignes qui correspondent ainsi que les lignes qui n'ont pas trouvé de correspondance pour chacun des deux flux de données. Vous pouvez choisir le type de jointure que vous souhaitez utiliser (LEFT, RIGHT, INNER, OUTER) en cochant les cases associées à droite. Ici, nous n'allons conserver que les lignes qui ont une correspondance.

Un nouveau flux de données est créé avec votre jointure. Nous allons à présent pouvoir effectuer les mêmes opérations que sur le jeu de données d'entraînement. Effectuez la transformation Transform Dataflow (Script) pour pouvoir générer le nombre de jours restants avant que le moteur ne tombe en panne :

df['cycle_max'] = df.groupby(['id'])['cycle'].transform(max)

df["RUL"] = df["cycle_max"] - df["cycle"]

del df["cycle_max"]

del df["moteur"]

del df["RUL_restants"]

Puis ajoutez la colonne pour avoir le libellé nécessaire à la classification binaire avec la transformation Add Column :

  • New Column Name : spécifie le nom de la colonne à créer (ici, broken_50_cycles)

    Insert this New Column After : inique à quelle position cette colonne doit être ajoutée ?

  • New Column Code : précise le code pour générer la colonne :

    1 if row.RUL < 50 else 0

  • Code Block Type : indique comment votre code doit être interprété ? (Expression ou module Python)

Pour valider que le choix de 50 cycles est approprié par rapport à notre jeu de données, vous pouvez regarder le nombre de 1 et 0 dans cette colonne. Pour cela, effectuez un clic-droit sur l'en-tête la colonne broken_50_cycles puis cliquez sur Value Counts :

Notre jeu de test est maintenant prêt, nous allons pouvoir l'exporter en fichier .CSV ou Parquet par la transformation Write to CSV ou Write to Parquet.

Exportez dans le dossier du projet sous le nom « test.csv » si vous souhaitez effectuer l'entraînement du modèle en local ou sur un stockage Blob dans Azure si vous souhaitez effectuer l'entraînement du modèle sur une cible distante.

L'étape de préparation du jeu de données est maintenant terminée.

Avertissement : L'ensemble des opérations précédentes pouvaient être effectuées via le bloc-notes Jupyter 1_dataprep.ipynb. L'objectif était ici de démontrer avec Azure ML Workbench les facilités données d'explorer un jeu de données, de traiter les erreurs éventuelles, de formater les données dans un format utilisable pour la suite.

Nous allons donc pouvoir passer à l'apprentissage de nos modèles ! Ce sera l'objet de la seconde partie de ce billet. Stay tuned!

Microsoft’s software for quantum computing, Liqui|>

$
0
0

Guest post by Vani Asawa Microsoft Student Partner at Oxford University

 image

About me

Hi! I am Vani Asawa, a second year student at the University of Oxford studying Mathematics. Originally from India. I have always been very passionate about science and technology and knew from a very young age that I would be working in those areas. I am particularly interested in understanding the applications of Machine Learning and Big Data. At Oxford, I am involved with the Artificial Intelligence Society as the Social Media Director, working to make my peers realise the potential of Artificial Intelligence and organising events with speakers working in this field. 

Introduction

Alan Turing invented the programmable computer in 1936 to show that certain mathematical problems could not be solved computationally. He believed that a computer, armed with the necessary resources, is capable of realizing any reasonable algorithm.

Since then, the computer industry has not only managed to build programmable computing machines, but also managed to double their capabilities every few months. However, despite these advances in computer technology, modern computers are still unable to make significant dents in hard problems. Problems that require exponential resources remain as intractable today as they were in 1936.

Enter Quantum Computing

With its ability to harness quantum-mechanical phenomenon such as superposition and entangling, quantum computing uses the power of atoms to perform memory and processing tasks. In just hours or days, a quantum computer can solve complex problems that would otherwise take years for a traditional computer to solve. This will have massive implications for research in energy, medicine, artificial intelligence, environmental systems, smart materials, investments, logistics and supply chains, and more.

Through this blog, you will not only be able to find out more about the power of quantum computing and its impact on our future economy, but also be able to start building quantum applications using Microsoft’s software for quantum computing, Liqui|>!

Let’s get started!

What is Quantum Computing?

clip_image002

“Quantum Computing” is the use of quantum mechanical systems with the full use of their quantum mechanical properties to do computations.

What does this mean?

Think of a modern, or classical computer. Classical computers store information in bits. Equivalent to an atom, a bit is the smallest unit of information storage. Each bit can take the value of 1 or 0. These 1s and 0s act as on/off switches that ultimately drive computer operations.

Quantum computers, on the other hand, are based on qubits, which operate according to two key principles of quantum physics: superposition and entanglement.

- By the principles of superposition, each qubit can represent both a 1 and a 0 at the same time.

- As a result of entanglement, the state of a qubit, or the property of a qubit being 1 or 0, can depend on the state of another qubit being 1 or 0.

Using these two principles, qubits can act as more sophisticated switches, enabling quantum computers to function in ways that allow them to solve difficult problems that are intractable using today’s computers.

Pictorially, a qubit can be thought of as follows:

clip_image004

Whereas a classical bit can only be in two states - in this case, the two poles of the sphere |0> and |1>, a qubit can be any complex vector form the centre of the sphere pointing to a spot on the unit sphere.

Thus, unlike classical bits, qubits arise in the way that they can simultaneously exist as both 0 and 1, with the probability for each state given by a numerical coefficient. Describing a two- qubit quantum computer thus requires four coefficients. Generalising for an n-qubit quantum system, we observe that n qubits demand 2n numbers, which rapidly becomes a sizable set for larger values of n. For example, if n equals 100, about 1030 numbers are required to describe all the probabilities for all the possible states of the quantum machine—a number that exceeds the capacity of the largest conventional computer. Thus, a quantum computer could naturally perform myriad operations simultaneously, or in parallel, using only a single processing unit.

Now that we have understood the ideology behind quantum computing, let’s take a look at what is LIQ|⟩ and some key terminologies before we get started on coding quantum application!

LIQ|⟩

LIQ|⟩, or “Language-Integrated Quantum Operations”, is a software for developing quantum applications. Currently being developed by the Quantum Architectures and Computation Group (QuArC) at Microsoft Research, LIQ|⟩ includes a programming language, optimization and scheduling algorithms, and quantum simulators to aid in the development and understanding of quantum protocols, quantum algorithms, quantum error correction, and quantum devices.

Currently, there are three classes of simulators built into the system representing different levels of abstraction:

1. Physical Modeling: One of the slowest simulators by nature, the physical modelling simulator attempts to model some of the actual physics in a quantum system.

2. Universal Modeling: This simulator is highly optimized for performing multiple calculations simultaneously, and is highly efficient in memory usage. However, its main limitation is the number of qubits (~30) that can be entangled at one time.

3. Stabilizer Modeling: This simulator has the virtue of allowing large circuits on tens of thousands of qubits, but has limitations on the types of operations.

These Simulations can be accomplished in the following ways:

  1. Test Mode: Functions that are built into the software can be called from the command line prompt and run.
  2. Script Mode: The system can be run directly from an F# text file. There is no separate language compilation required, and the entire simulation can be available from this mode.
  3. Function Mode : This mode involves a compilation environment and the use of a .Net language, typically F#. The user is free to build their own application using the APIs available in the F# environment.
  4. Circuit Mode : Function mode can be compiled into a circuit data structure, which can be manipulated by the user in several ways, such as running through built-in optimizers, having quantum error correction added, and exporting for use in other environments.

Some other key terminologies that will be useful to know before we learn how to code quantum applications are:

  1. Ket refers to the complete state of the system, and is of the length 2n where n is the number of qubits in the state.
  2. Gate refers to a matrix that is used to represent an operation, such as measurement and reanimation, that can be applied to a set of qubits.
  3. Finally, Circuits are used to represent a list of operations on gates. They can provide pre-processing of quantum algorithms for various reasons, such as performing multiple operations (or parallelizing) , substitution (some gates will not be available in target physical systems), and optimization.

Why LIQ|?

LIQUi| allows the simulation of Hamiltonians, quantum circuits, quantum stabilizer circuits, and quantum noise models, and supports Client, Service, and Cloud operation. It allows the user to express circuits in a high-level functional language like F#, and supports the extraction of circuit data structures that can be passed to other components for circuit optimization, quantum error correction or gate replacement.

As a user, you can use LIQUi| to define quantum circuits, render them into a variety of graphical formats, and execute them using an appropriate simulator. Some of the specific algorithms you can simulate with LIQUi| are:

● Simple quantum teleportation

● Shor’s factoring algorithm

● Quantum chemistry: computing the ground state energy of a molecule

● Quantum error correction

Getting Started

Depending on your platform of choice, following are the steps for installing LIQUi|:


WINDOWS

  1. Install Visual Studio: Download the official MSI Installer. This will install the tools and put them on your PATH. Make sure you select F# as one of the languages to install.

03/01/2016 10:14 AM <DIR> .

03/01/2016 10:14 AM <DIR> ..

03/01/2016 10:14 AM 10,086 AzureGuide.md

03/01/2016 10:14 AM <DIR> bin

03/01/2016 10:14 AM <DIR> docs

03/01/2016 10:14 AM 17,292 GettingStarted.md

03/01/2016 10:14 AM <DIR> img

03/01/2016 10:14 AM 6,118 LICENSE.md

03/01/2016 10:14 AM <DIR> linux

03/01/2016 10:14 AM 32,708 LiquidTikZ.tex

03/01/2016 10:14 AM 5,441 README.md

03/01/2016 10:14 AM <DIR> Samples

03/01/2016 10:14 AM <DIR> source

03/01/2016 10:14 AM <DIR> UserCode

5 File(s) 71,645 bytes

    1. Install LIQUi|: Download the zip file from GitHub. Extract the contents into C:. This will create C:Liquid-master - rename the directory to C:Liquid.
    2. Run the App: Go into the C:Liquidbin directory, run the app and accept the license!

0:0000.0/===================================================================================================

0:0000.0/= The Language-Integrated Quantum Operations (LIQUi|>) Simulator =

0:0000.0/= is made available under license by Microsoft Corporation =

0:0000.0/= License terms may be viewed at https://github.com/msr-quarc/Liquid/blob/master/LICENSE.md =

0:0000.0/= Please type Y, followed by return, to indicate your acceptance of these terms =

0:0000.0/===================================================================================================

Y


UBUNTU (14.04)

  1. Install Mono and F# - Make sure you remove any previous installations of the two to avoid incompatibilities!

$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF

$ echo "deb http://download.mono-project.com/repo/debian wheezy main" |

sudo tee /etc/apt/sources.list.d/mono-xamarin.list

$ sudo apt-get update

$ sudo apt-get install mono-complete fsharp

    1. Install LIQUi|: Download the zip file from GitHub. Extract the contents into your home directory. This will create ~/Liquid-master - copy to the final destination

$ cd ~/Liquid-Master

$ sudo mkdir /Liquid

$ sudo chown $USER /Liquid

$ cp * /Liquid --recursive

    1. Run the app: Go into the /Liquid/linux directory, run the app and accept the license.

0:0000.0/===================================================================================================

0:0000.0/= The Language-Integrated Quantum Operations (LIQUi|>) Simulator =

0:0000.0/= is made available under license by Microsoft Corporation =

0:0000.0/= License terms may be viewed at https://github.com/msr-quarc/Liquid/blob/master/LICENSE.md =

0:0000.0/= Please type Y, followed by return, to indicate your acceptance of these terms =

0:0000.0/===================================================================================================

Y


OSX (10.11)

  1. Install Mono and F#: http://www.mono-project.com/download/
  2. Install LIQ⏐〉
    1. Download the zip file from GitHub.
    2. From your Downloads, open the folder Liquid-master.
    3. Select and Copy all the files..
    4. Type Shift-Command-G and then a slash (/) to go to the root.
    5. Type Shift-Command-N to create a new folder, and create the Liquid folder.
    6. Double click on the Liquid folder paste the contents of the downloaded Liquid-master tree into Liquid.
  3. Run the app: Go into the /Liquid/linux directory, run the app and accept the license

Vani:~ vaniasawa$ cd /Liquid/linux

Vani:linux vaniasawa$ mono Liquid.exe

0:0000.0/===================================================================================================

0:0000.0/= The Language-Integrated Quantum Operations (LIQUi|>) Simulator =

0:0000.0/= is made available under license by Microsoft Corporation =

0:0000.0/= License terms may be viewed at https://github.com/msr-quarc/Liquid/blob/master/LICENSE.md =

0:0000.0/= Please type Y, followed by return, to indicate your acceptance of these terms =

0:0000.0/===================================================================================================

Y

0:0000.5/===================================================================================================

0:0000.5/= Thank you for accepting the license terms =

0:0000.0/===================================================================================================

Y

Example of a Quantum Application - Spin Glass Simulation

Spin Glass - An Introduction

The study of spin glasses was inspired by the known physics of structural glasses (like window glass). Typical solid phases have crystalline ground states, where the atoms are arranged in a simple periodic arrangement, but window glass has amorphous arrangements of atoms. Now, to form glass, you need to quench the molten glass, so that it cools very rapidly and does not have time to "find" its crystalline ground state. Once it is at room temperature, it is so cold that the probability of the atoms in the glass finding their crystalline ground state, which is suppressed by a factor of e−ϵ/T for some energy barrier ϵ, is negligibly small.

Now, just as the atoms in the glass are trapped in local minima of the energy, but globally the glass is not in its ground state, physicists noted that the same thing could happen in simple models of magnetism. Suppose that you have a magnet whose Hamiltonian energy is given by

H=∑ij Jij si sj

where si ∈ {+1,−1}, and the couplings Jij between various spins look random: sometimes positive, and sometimes negative. In general, this system will be frustrated: some of the bonds will have "unfavorable" energies: e.g., a positive Jij with si=sj. However, there certainly exists a ground state for the magnet and it is quite likely that some bonds will be frustrated, but the idea is that the existence of frustration typically leads to a very large number of local minima in the energy H, just as there are many local minima in a window glass.

So how do we define what a spin glass is? A heuristic physicist's definition of a spin glass is as follows:

A spin glass should have two properties:

1) An exponential number of locally stable equilibria, which do not have to be Hamiltonian

2) If you give the system reasonable dynamical rules, there are dynamics on all time scales. The simple way to see that this will happen is to recognize that the local minima in your system consist of clusters of spins of very large size, which all have to simultaneously flip, to get from one ground state to another. This cluster can be taken to be connected without loss of generality. Dynamics on all time scales then, heuristically, maps to the presence of clusters of all sizes. This leads to aging, where the system takes a very long time to relax to its ground state. In many models, aging breaks ergodicity -- the system will never explore the full phase space, but is trapped in some very small pocket of it.

Spin Glass Simulation

The Spin class in LIQ⏐〉 is used to define Spin-Glass problems to the system. The Hamiltonian being simulated is:

=Γ(t)∑i Δii+Λ(t)( ∑ihii+∑ i<j ij ii )

We are starting in a ground state that we know in the direction (Γ = 1, Λ = 0 ) and ending in a target state in the direction (when Γ = 0, Λ = 1) which we’d like to discover. This is referred to as an adiabatic evolution since it is expected that if we move slowly enough (changing Γ, Λ) we can stay in the ground state of the entire system and smoothly move to the solution. The changing of strength over time is called the annealing schedule and typically looks like this:

clip_image006

There are two main ways to instantiate the class. The first is the “bottom level” version that lets you specify everything:

type Spin(
spinTerms : SpinTerm list,
numSpins : int,
runMode : RunMode)

The constructor arguments are:

1. spinTerms which are a list of elements that contain:

a. schedule:0 based index of an annealing schedule that will be used

b. op: Operation(Gate) to apply

c. ampl: Amplitude(strength) of this term

2. numSpins: How many spins are there(qubits)

3. runMode:Trotterization to use:

a. Trotter1: First order Trotter term

b. Trotter1x: Split the transvers (X) field terms to the start and end of the Circuit

c. Trotter2: Second order Trotterization

The second form of the constructor takes care of many of the details for you:

type Spin(
hs : Dictionary<int,float>,
Js : Dictionary<int*int,float>)

The constructor arguments are:

● hs – Create a dictionary for each Qubits that you want to provide a strength to in the range (typically) of -1.0 to +1.0. These are the ZR terms.

● Js – Coupling strength between two Qubits. This is a dictionary of Qubit Id pairs and strength. Only Ids where the first is less than the second is searched for (i<j) and typical values are -1.0 which is ferromagnetic coupling and +1.0 which is antiferromagnetic coupling (0.0 = no coupling). These are the ZZR terms.

Note that there’s no XR term, since it’s implied automatically and is on annealing schedule 0. The ZR and ZZR are terms on automatically placed on schedule 1.

Two built-in static members are available to aid in setting up spin-glass systems. Let’s go through the example provided in the samples directory (Ferro.fsx) which simulates a ferromagnetic chain. The file shows both static members, but take a look at the simpler one here:

let tests = 50 // Tests to run
let qCnt = 12 // Qubit count
let h0 = 1.0 // h0: Left most qubit Z strength
let hn = -1.0 // hn: Right most qubit z strength
let coupling= 1.0 // 1=ferro -1=anti-ferro 0=none
let sched = [(100,0.0,1.0)] // Annealing schedule
let runonce = true // Runonce: Virtual measurements

let decohere= [] // No decoherence model

Spin.Ferro(tests,qCnt,h0,hn,coupling,sched,runonce,decohere)

The arguments are:

  1. tests: How many instances to run.
  2. qCnt: Total number of qubits to use as spin terms
  3. h0: Strength of the h term on Qubit 0. +1 = Force spin up
  4. hn: Strength of the h term on the last Qubit. -1 = Force spin down
  5. coupling:Strengthofthebetweenqubitterms(buildaferromagneticchain by specifying +1.0)
  6. sched: At time 0, schedule 0 is always 1.0 (the term) and all the other schedules are at 0.0 . For this reason, we only need to specify the ending point for the schedules. Here we’ve specified a final time of 100 where the term (schedule 0) becomes 0.0 and the terms (schedule 1) become 1.0.
  7. runonce: This is a simulation optimization that lets us run a test once and then look directly into the state vector (since we’re a simulator) and obtain all the probabilities instead of running 100s or 1000s of times and measuring to get the same result (which we’d have to actually do on a quantum computer).
  8. decohere: This is an advanced option that allows dechoherence models to be plugged in. For this test, we’re using perfect qubits.

What we’ve done is created a twisted chain (one end up; one end down) so when we simulate, we get both details for 1 run and a histogram across all runs:

0:0000.0/ 1%: ............ [<H>=-6.000 Stdev 0.000] [S_mid=0.000]

0:0000.0/ 10%: -..........+ [<H>=-5.525 Stdev 0.043] [S_mid=0.009]

0:0000.0/ 18%: 0..........1 [<H>=-5.242 Stdev 0.049] [S_mid=0.036]

0:0000.0/ 20%: 0-........+1 [<H>=-5.197 Stdev 0.049] [S_mid=0.048]

0:0000.0/ 25%: 0--......++1 [<H>=-5.142 Stdev 0.058] [S_mid=0.095]

0:0000.0/ 26%: 00-......+11 [<H>=-5.142 Stdev 0.061] [S_mid=0.108]

0:0000.0/ 28%: 00--....++11 [<H>=-5.154 Stdev 0.065] [S_mid=0.139]

0:0000.0/ 30%: 000-....+111 [<H>=-5.185 Stdev 0.069] [S_mid=0.180]

0:0000.0/ 32%: 000--..++111 [<H>=-5.234 Stdev 0.070] [S_mid=0.228]

0:0000.0/ 34%: 0000-..+1111 [<H>=-5.303 Stdev 0.067] [S_mid=0.267]

0:0000.0/ 81%: 00000..11111 [<H>=-9.031 Stdev 0.060] [S_mid=0.631]

0:0000.1/!Histogram:

0:0000.1/!Ferro 6.0% 000000000001 (E=-11.0000) [ones= 1]

0:0000.1/!Ferro 10.0% 000000000011 (E=-11.0000) [ones= 2]

0:0000.1/!Ferro 8.0% 000000000111 (E=-11.0000) [ones= 3]

0:0000.1/!Ferro 12.0% 000000001111 (E=-11.0000) [ones= 4]

0:0000.1/!Ferro 4.0% 000000011111 (E=-11.0000) [ones= 5]

0:0000.1/!Ferro 12.0% 000000111111 (E=-11.0000) [ones= 6]

0:0000.1/!Ferro 30.0% 000001111111 (E=-11.0000) [ones= 7]

0:0000.1/!Ferro 6.0% 000011111111 (E=-11.0000) [ones= 8]

0:0000.1/!Ferro 2.0% 000111111111 (E=-11.0000) [ones= 9]

0:0000.1/!Ferro 10.0% 001111111111 (E=-11.0000) [ones=10]

The detailed output shows the probability of each qubit between 0 and 1 (- = tending to 0, +=tending to 1 and .= no tendency). The histogram shows each case seen, what percentage of the runs fell into that category and the final energy (showing we reached the ground state). The test also generated two diagrams. The first was Ferro.htm which shows all the pieces (as well as the fact that we used RunMode Trotter1X visible from the fact that the RpX gates are both at the beginning and end of the Circuit):

clip_image008

The second diagram shows the Circuit that was actually run after “Gate Growing” was performed:

clip_image010

 

Here you can see that we only had to do 5 matrix multiplies to perform the entire circuit (major speed-up). One of the reasons not to grow even further is that the circuit changes at every time step (due to the annealing schedule), so spending time optimizing beyond a certain point simply doesn’t pay.

The Spin.Test(...) static routine allows arbitrary connections (not just chains) and much finer control (including Trotter number).

Conclusion

clip_image012

Today, quantum computing is somewhere between the arrival of FORTRAN and Engelbart’s “Mother of all Demos.” Highly trained specialists are able to translate real world problems into language a quantum computer can understand, but for most people the technology is out of reach. That will change in the years to come.

It might not be that we have quantum computers in all our homes, but we will likely be able to access them in the cloud and they will help us solve problems that seem impossible today. According to D-Wave’s Jeremy Hilton,“the quantum computing revolution may be even more profound than the digital computing revolution a half century ago and it will happen much faster.”

Excited? Want to find out more about Quantum Applications?

Take a look at the following links and go explore the world of quantum applications and LIQ⏐〉!

https://www.microsoft.com/en-us/quantum/default.aspx

http://www.research.ibm.com/ibm-q/learn/what-is-quantum-computing/

https://www.microsoft.com/en-us/research/project/language-integrated-quantum-operations-liqui/

http://cdn.nanalyze.com/uploads/2017/04/Dilbert-Quatum-Computing.gif

https://www.ibm.com/developerworks/library/l-quant/index.html

https://www.quora.com/What-is-a-spin-glass-and-how-did-the-study-of-spin-glasses-get-started

https://www.forbes.com/sites/gregsatell/2016/10/02/heres-how-quantum-computing-will-change-the-world/#30d053c0ad6d

Premiers pas avec les nouveaux services d’Azure Machine Learning – 2nde partie

$
0
0

Nous souhaitons vous donner au travers de ce billet un premier aperçu des capacités du nouvel environnement Azure ML, càd le service d'expérimentation, le service de gestion des modèles et bien sûr l' « établi » (Azure ML Workbench), sur un jeu de données en rapport avec la maintenance prédictive.

Pour cela, ce billet vise à proposer une illustration de bout en bout du nouvel environnement Azure ML. L'illustration simple sur laquelle nous nous appuyons utilise un algorithme d'apprentissage profond (Deep Learning) avec, comme objectif, de pouvoir prédire si un équipement va tomber en panne prochainement pour optimiser la maintenance de celui-ci.

Avec la première partie, l'étape de préparation du jeu de données est maintenant terminée. Nous allons donc pouvoir passer à l'apprentissage de nos modèles avec cette seconde partie !

J'en profite pour remercier à nouveau Paul Jenny actuellement en stage de fin d'étude au sein de Microsoft France pour cette contribution.

L'apprentissage du modèle de classification

Le fichier pour l'apprentissage du modèle appelé train.py est fourni en pièce jointe de ce billet. Le but ici n'est pas d'expliquer précisément chaque ligne mais de vous montrer les possibilités pour entraîner un modèle dans différents contextes.

En local

Vous pouvez lancer l'entraînement du modèle dans un contexte local. Vous devrez avoir au préalable préparer votre environnement Conda avec les dépendances nécessaires. Cette opération n'est à effectuer qu'une seule fois et uniquement pour un contexte local. Pour cela, allez dans la barre de tâches d'Azure Machine Learning Workbench puis cliquez sur File > Open Command Prompt.

Voici les différentes dépendances à installer au préalable :

pip install keras sklearn matplotlib h5py https://cntk.ai/PythonWheel/CPU-Only/cntk-2.2-cp35-cp35m-linux_x86_64.whl

Remarque : Nous avons choisi ici d'utiliser la version CPU de CNTK comme l'ordinateur utilisé ne disposait pas de GPU. Néanmoins, si vous avez un ou plusieurs GPUs, vous pouvez télécharger la version adéquate. Cf. le tutoriel d'installation de CNTK avec la version 3.5 de Python sur docs.microsoft.com.

Une fois l'installation des dépendances effectuées, nous allons pouvoir lancer l'apprentissage du modèle.

Pour cela, allez dans le navigateur de fichiers d'Azure ML Workbench puis sélectionnez train.py puis, dans la barre située au-dessus de l'éditeur de texte, choisissez la cible local puis cliquez sur Run :

Un nouveau travail s'affiche sur la barre à droite indiquant l'avancement de l'exécution et la console associée.

Remarque : Vous pouvez ajouter des arguments à l'exécution. Par exemple, ici, vous pouvez configurer la taille des batchs pour l'apprentissage du réseau de neurones en entrant un nombre dans la case Arguments.

Une fois le calcul effectué, le script génère une matrice de confusion et un fichier model_XX.h5. Ce fichier correspond à l'exportation du modèle que vous venez d'entraîner (avec les poids associés et les différents paramètres). Il peut être déployé et chargé via la méthode load() de la bibliothèque Keras. La matrice générée est appelée cm.png.

Remarque : Cette opération aurait pu être effectuée via la ligne de commandes. En effet, en ouvrant une invite de commandes dans Azure ML Workbench (File -> Open Command Prompt), avec la commande suivante :

az ml experiment submit -c local .train.py

Sur un docker en local

Grâce au nouveau service de gestion des modèles, vous pouvez lancer vos calculs dans un conteneur Docker automatiquement crée pour l'occasion.

Dans le dossier aml_config, vous avez des fichiers docker .XX . Ceux-ci sont relatifs à l'exécution d'expérimentation dans l'environnement docker. La différence par rapport aux fichiers local.XX est que vous spécifiez que votre contexte d'exécution est un localdocker.

De plus, par rapport à un contexte local, vous n'avez pas à vous soucier de la préparation de votre environnement et de vos dépendances. Celles-ci sont automatiquement récupérées depuis les fichiers conda_dependencies.yml pour les dépendances liées à Python avec Conda et spark_dependencies.yml pour celles liées à Spark.

Lancez maintenant l'apprentissage en allant dans le navigateur de fichiers puis en choisissant docker au lieu de local :

Un nouveau travail s'affiche sur la barre de droite en indiquant que votre cible d'exécution est dorénavant docker.

Remarque : Vous pouvez ajouter des arguments à l'exécution. Par exemple, ici, vous pouvez configurer la taille des batchs pour l'apprentissage du réseau de neurones en entrant un nombre dans la case Arguments.

Une fois le calcul effectué, le script crée un fichier model_XX.h5 et une matrice de confusion sous forme d'image. Néanmoins, vous ne pouvez pas naviguer dans un docker. Azure ML vous permet de récupérer les objets générés par votre script via l'utilisation d'un dossier approprié : outputs (Cf. billet précédent concernant la gestion des fichiers d'un projet par Azure ML). Pour cela, naviguez dans l'historique des exécutions dans Azure ML Workbench. Vous pouvez retrouver différentes statistiques de vos exécutions (générés par Azure ML mais aussi personnalisées) ainsi que les fichiers associés :

Remarque : Cette opération aurait pu être effectuée via la ligne de commandes. En effet, en ouvrant un terminal de commandes dans Azure ML Workbench (File -> Open Command Prompt), avec la commande suivante, vous soumettez une nouvelle expérimentation dans le contexte docker :

az ml experiment submit -c docker .train.py

Sur un docker distant

Vous pouvez aussi exécuter votre apprentissage sur tout environnement supportant Docker. Par exemple, nous avons choisi d'effectuer notre calcul sur les toutes nouvelles machines virtuelles dédiées à la science des données d'Azure, à savoir les Data Science Virtual Machines (DSVM). Celles-ci sont puissantes et prêtes à l'utilisation pour la science des données. Vous pouvez bien évidemment utiliser tout autre environnement qui supporte Docker (IoT, etc.).

Pour créer un nouvel environnement d'exécution pour notre projet, depuis Azure ML Workbench, nous avons ouvert une invite de commande (File -> Open Command Prompt) puis tapé avec la commande suivante :

az ml computetarget attach --name remotevm --address <IP address> --username <username> --password <password> --type remotedocker

Remarque : L'authentification via une clé n'est actuellement pas supportée. Vous devez utiliser la combinaison utilisateur / mot de passe uniquement.

Remarque : L'adresse IP peut être un nom de domaine accessible publiquement (FQDN). Il est, en général, intéressant d'attribuer à une VM dans Azure un FQDN car l'adresse IP de celle-ci peut être différente entre deux redémarrages.

Ce script permet de générer la paire de fichiers de configuration nécessaires pour un environnement remotevm.compute et remotevm.runconfig. Il faut ensuite préparer l'environnement distant avec l'installation des dépendances, etc. Pour cela, encore dans l'invite de commandes, utilisez la commande suivante :

az ml experiment prepare -c remotevm

Le service d'Azure ML va télécharger, installer et créer l'image Docker associé à votre projet sur votre cible d'exécution distante. Cette opération n'est à effectuer que la première fois que vous utilisez un environnement ou suite à une modification dans les dépendances du projet (dans conda_dependencies.yml ou spark_dependencies.yml).

Remarque : Vous pouvez forcer Azure ML à toujours préparer l'environnement même s'il a déjà été utilisé auparavant. Pour cela, il faut affecter la valeur true à PrepareEnvironment » dans le fichier remotevm.runconfig. Néanmoins, cela rallonge la durée d'exécution lorsque vous effectuez plusieurs expérimentations sur une même configuration…

Une fois l'environnement préparé, il ne reste plus qu'à soumettre l'expérimentation dans ce contexte d'exécution. Pour cela, retournez dans le navigateur de fichiers d'Azure ML Workbench puis choisissez remotevm dans la liste des cibles de calcul et enfin cliquez sur Run :

Un nouveau travail s'affiche sur la barre de droite en indiquant la progression de votre exécution.

Une fois le calcul effectué, le script crée un fichier model_XX.h5 et une matrice de confusion sous forme d'image. Néanmoins, vous ne pouvez pas naviguer dans un docker. Azure ML vous permet de récupérer les objets générés par votre script via l'utilisation d'un dossier approprié : outputs (Cf. billet précédent concernant la gestion des fichiers d'un projet par Azure ML).

Pour cela, comme précédemment, naviguez dans l'historique des exécutions dans Azure ML Workbench. Vous pouvez retrouver différentes statistiques de vos exécutions (générés par Azure ML mais aussi personnalisées) ainsi que les fichiers associés :

Remarque : Cette opération aurait pu être effectuée via la ligne de commandes. En effet, en ouvrant une invite de commandes dans Azure ML Workbench (File -> Open Command Prompt), avec la commande suivante :

az ml experiment submit -c remotevm .train.py

Le déploiement du modèle

Notre modèle est maintenant entraîné et prêt à être utilisé sur tout environnement supportant la bibliothèque Keras.

La récupération du modèle

Grâce à l'historique des exécutions lancées, depuis Azure ML Workbench, vous pouvez récupérer le « meilleur » modèle d'une exécution pour une utilisation ultérieure.

Pour cela, allez dans la section Historique d'Azure ML Workbench puis choisissez une des exécutions qui vous semblent pertinentes en termes de métriques puis dans Outputs, cochez la case de model_200.h5 pour pouvoir le télécharger :

Une fois ce modèle récupéré, vous pouvez le charger dans un script Python avec Keras avec la commande suivante :

from keras.models import load_model

model = load_model('model_200.h5')

Vous pouvez ensuite utiliser vos méthodes habituelles pour travailler avec celui-ci, prédire de nouvelles classes, etc… Un bloc-notes Jupyter a été créé « 2_loadingmodel.ipynb » pour fournir un exemple d'utilisation ou vous pouvez regarder la documentation officielle de Keras.

En guise de conclusion

Ceci conclut cette seconde partie. Ainsi, par ce billet, nous espérons que vous avez pu découvrir un peu plus les possibilités offertes par les nouveaux services d'Azure ML avec notamment Azure ML Workbench (« l'établi »), le service d'expérimentation et le service de gestion des modèles.

Si vous avez suivi l'ensemble des étapes illustrées, vous avez normalement dû réussir à préparer un jeu de données cohérent avec votre utilisation, à l'exporter vers différentes sources (en local et sur un stockage Blob dans un compte de stockage Azure), à réaliser l'entraînement d'un réseau de neurones artificiels de type LSTM, à accéder à l'historique des exécutions pour choisir le modèle « pertinent » et enfin à récupérer ce modèle pour une utilisation ultérieure.

Il ne reste plus qu'à vous lancer avec vos propres jeux de données pour réaliser les expériences !

 

Issues with Hosted Build and Load Test in South Central US region – 10/30 – Mitigating

$
0
0

Update: Monday, October 30th 2017 18:01 UTC

Impact to users of Hosted Build has been mitigated after additional capacity has been provisioned. Users should not notice any more delays on their build requests.

Users of Load test are still impacted. A mitigation is in progress, but it will take some more time to take effect.

  • Work Around: Until this incident is mitigated, we recommend Load Test users to choose a location other than 'South Central US' when triggering a load run. See 'Run and Analyze your load test' section in this document for instructions on how to choose a location.
  • Next Update: Before Monday, October 30th 2017 21:15 UTC

Sincerely,
Sri Harsha


Update: Monday, October 30th 2017 16:52 UTC

Investigation has pointed that the users of VSTS Hosted Build and Cloud Load Test are impacted by the current incident. We are closely working with our partners in Azure to mitigate the underlying platform issues which limiting our ability to provision additional VMs to handle the user load.

  • Next Update: Before Monday, October 30th 2017 18:00 UTC

Sincerely,
Sri Harsha


Initial Update: Monday, October 30th 2017 16:07 UTC

A potentially customer impacting alert is being investigated. Triage is in progress and we will provide an update with more information.

  • Initial Investigation indicates that some users in South Central may see long-waiting requests for Hosted Builds
  • Next Update: Before Monday, October 30th 2017 17:07 UTC

Sincerely,
Dexter


Resize Azure VMs in bulk

$
0
0

If you need to do a bulk update of VM sizes from one type to another to take advantage of new technology being released, this script should help you out.

This script will work for Resource Manager VMs, and NOT Classic VMs.
It targets VMs that are deallocated only.

I've preloaded the SizeMapping table with the mapping to move from Dv2 Promo and Av1 sizes to their equivilent Dv3, Ev3 & Av2 sizes.
You can change this as to your requirements, just set the Old and New elements for each record.
Make sure only select ONE subscription from the Select Grid.

$AvailSubscriptions = Get-AzureRmSubscription

$ErrorActionPreference = "Stop"
$SelectedSubscription = $AvailSubscriptions | select Name, Id | Out-GridView -Title "Select ONE (only) Subscription" -PassThru

$SubscriptionGUID = $SelectedSubscription.Id

Select-AzureRmSubscription -Subscription $SubscriptionGUID

$SizeMapping = @()
$SizeMapping += @{Old='Standard_A1';New='Standard_A1_v2'}
$SizeMapping += @{Old='Standard_A2';New='Standard_A2_v2'}
$SizeMapping += @{Old='Standard_A3';New='Standard_A4_v2'}
$SizeMapping += @{Old='Standard_A4';New='Standard_A8_v2'}
$SizeMapping += @{Old='Standard_A5';New='Standard_A2m_v2'}
$SizeMapping += @{Old='Standard_A6';New='Standard_A4m_v2'}
$SizeMapping += @{Old='Standard_A7';New='Standard_A8m_v2'}
$SizeMapping += @{Old='Standard_D2_v2_Promo';New='Standard_D2_v3'}
$SizeMapping += @{Old='Standard_D3_v2_Promo';New='Standard_D4_v3'}
$SizeMapping += @{Old='Standard_D4_v2_Promo';New='Standard_D8_v3'}
$SizeMapping += @{Old='Standard_D5_v2_Promo';New='Standard_D16_v3'}
$SizeMapping += @{Old='Standard_D11_v2_Promo';New='Standard_E2_v3'}
$SizeMapping += @{Old='Standard_D12_v2_Promo';New='Standard_E4_v3'}
$SizeMapping += @{Old='Standard_D13_v2_Promo';New='Standard_E8_v3'}
$SizeMapping += @{Old='Standard_D14_v2_Promo';New='Standard_E16_v3'}
$SizeMapping += @{Old='Standard_DS2_v2_Promo';New='Standard_D2s_v3'}
$SizeMapping += @{Old='Standard_DS3_v2_Promo';New='Standard_D4s_v3'}
$SizeMapping += @{Old='Standard_DS4_v2_Promo';New='Standard_D8s_v3'}
$SizeMapping += @{Old='Standard_DS5_v2_Promo';New='Standard_D16s_v3'}
$SizeMapping += @{Old='Standard_DS11_v2_Promo';New='Standard_E2s_v3'}
$SizeMapping += @{Old='Standard_DS12_v2_Promo';New='Standard_E4s_v3'}
$SizeMapping += @{Old='Standard_DS13_v2_Promo';New='Standard_E8s_v3'}
$SizeMapping += @{Old='Standard_DS14_v2_Promo';New='Standard_E16s_v3'}

$VMs = Get-AzureRmVM
foreach ($VM in $VMs) {
    $Status = Get-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Status
    if ($Status.Statuses[1].DisplayStatus -eq "VM deallocated" -and $VM.HardwareProfile.VmSize -in $SizeMapping.Old) {
        $NewSize = $SizeMapping.New[$SizeMapping.Old.IndexOf($VM.HardwareProfile.VmSize)]
        $VM.HardwareProfile.VmSize = $NewSize
        Update-AzureRmVM -VM $VM -ResourceGroupName $VM.ResourceGroupName
    }
}

Azure Serverless ワークショップ Deep Dive : モジュール 1 – 2

$
0
0

ハロウィーン楽しんでますか?

今回は Serverless Conf 開催記念ということで、GitHub 上にある Azure Serverless ワークショップの Deep Dive をやります。各モジュール事に、まずワークショップをやってからこちらをご覧ください。

GitHub: Azure Serverless Workshop 日本語版

ワークショップの概要

このワークショップはボットをフロントエンドに使い、バックエンドに各種 Azure Serverless テクノロジーを使っています。各モジュールごとにボットが強化されていく様は、なかなか面白いです。ユーザーがボットにタスク(コマンド)を送ると、ボットが必要なことを聞いてくるので、すべて返信すると結果が返される仕組みです。

前提条件

Windows でも Mac でも動作するように作られています。必要なものはワークショップの手順にあるのでそちらを参照。このブログでは、Windows ベースでの検証をします。

モジュール 1

ワークショップの紹介と事前準備だけのため、Deep Dive 不要。Visual Studio 2017 など各種ツールは最新にすることを推奨します。

モジュール 2

モジュール 2 では Azure ファンクションの作成が学べます。

Azure Functions Core Tools (@core)

Azure Function Core Tools は .NET Core で動作する Azure Function を作成したり実行できるツールです。実はこのツールバージョン 2 であり、Windows 環境用にバージョン 1 もあります。挙動が違いますがコマンドが同じため間違えると面倒です。必ず以下コマンドでモジュールをインストールしてください。

npm install -g azure-functions-core-tools@core 

以下、簡単な見分け方です。

- func new とした時の言語選択 : 今日時点でバージョン 2 は選択肢が C# と JavaScript のみだが、バージョン 1 は豊富。
- application.json と local.settings.json : バージョン 1 は構成ファイルとして application.json を作成するが、バージョン 2 は local.settings.json

ここさえ間違えなければほぼ大丈夫です。

デバッグ方法

ワークショップでは紹介していないものとして、VSCode でのデバッグがあります。

1. 以下のコマンドで Azure ファンクションを起動。

func host start --debug vscode

2. VSCode を起動して、デバッグメニューを開く。Attach to Azure Functions があるので、そのまま F5 押下。

image

3. ブレークポイントを張って、Postman 等でアクセス。ブレークポイントにヒットするか確認。

C# での Azure ファンクション

ワークショップの最後に C# もやってみてくださいとあるので、Visual Studio 2017 と C# で同じ Azure ファンクションを作成します。

1. 新しいプロジェクトより、”Azure Funcitons" を選択。名前を任意で作成。ここでは ”MyFunctions” にして作成。

image

2. プロジェクト右クリック | 追加 | 新しい項目 より、”Azure 関数” を “LanceFetcher.cs” として追加。

3. Azure ファンクションは様々な方法で呼び出しが可能。ここでは Http trigger を選択。また権限はだれでも実行できるように Anonymous を選択。

image

3. 作成されたテンプレートにはサンプルコードがあるため、内容を確認。やり方が分かった所で以下のコードに差し替え。

using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Net.Http.Formatting;
using Newtonsoft.Json.Linq;

namespace MyFunctions
{
    public static class LanceFetcher
    {
        [FunctionName("LanceFetcher")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            dynamic data = await req.Content.ReadAsAsync<object>();

            // Body を確認。
            if (data != null)
            {
                const string long_lance = @"
         TTT
       TTTTTTTTT
    TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
       TTTTTTTTT
         TTT";

                const string short_lance = @"
       TTT
    TTTTTTTTTTTT
       TTT";
               
                var material = data?.lance_material == "wood" ? "w" : "m";
                var lance = data?.lance_length == "short" ? short_lance.Replace("T", material) : long_lance.Replace("T", material);
                JObject resData = new JObject();
                resData["message"] = $"Here's your lance! {lance}";
                return req.CreateResponse(HttpStatusCode.OK, resData, JsonMediaTypeFormatter.DefaultMediaType);
            }
            else
            {
                return req.CreateResponse(HttpStatusCode.BadRequest, "I couldn't figure out how to do that...");
            }
        }
    }
}

4. F5 を押下してデバッグ。起動するとコンソールで以下の表示。Azure 関数が起動した URI を確認。

image

5. Postman で POST を実行。結果を確認。

image

6. デバッグはいつも通りなので割愛。

まとめ

今回はモジュール 2 までの内容を深堀してみました。次回はモジュール 3 の紹介と Deep Dive を紹介します。

中村 憲一郎

Azure Serverless ワークショップ Deep Dive : モジュール 3

$
0
0

前回に続いて、今回はモジュール 3 の Deep Dive です。

GitHub: https://github.com/Azure-Samples/azure-serverless-workshop-team-assistant/tree/lang/jp/3-squirebot

概要

このモジュールではボットの本体を作ります。既存の GitHub 上のソリューションを使うため手順は簡単ですが、ここではコードを見ていきます。このソリューションにはボットの他に、タスク (コマンド) を登録するための Web アプリが含まれます。

プログラムの取得と実行

1. コマンドプロンプトより任意のディレクトで以下のコマンド実行。

git clone https://github.com/christopheranderson/squirebot

image_thumb[16]

2. まずボット側から。squirebotsrctask-functions に移動して code . コマンドで Visual Studio Code を起動。

image_thumb[18]

3. 次に package.json を確認。依存関係がすべて記述。Visual Studio Code の統合ターミナルより npm i を実行して依存関係をインストール。node_modules フォルダが作成されモジュールがコピーされる。

image_thumb[20]

4. 続いてコンソールより npm start を実行。4 つのファンクションが起動。フォルダ構成を確認し、function.json を含むフォルダがファンクション名となっていることを確認。

image_thumb[22]

image_thumb[24]

5. 既にモジュール 2 で出てきてた lanceFetcher から確認。function.json を開く。認証レベル、トリガーのタイプ、変数名等を含み、実際のスクリプトが index.js であることが scriptfile に記載あり。

image_thumb[26]

6. index.js も確認。module.exports で HttpRequest が来た際の処理だけ記述。C# と少しパターンが異なるため確認。Hello ファンクションも同様。Azure ファンクションは起動したまま次のステップへ。

7. 次に Web アプリ。新しいコマンドプロンプトで squirebotsrcwebapp に移動して code . コマンドで Visual Studio Code を起動。

8. ターミナルより npm i を実行しパッケージの復元。

9. npm start で開始したら、URL を確認して、ブラウザでアクセス。画面が出たら正常。

image_thumb[85]

image_thumb[87]

bot ファンクション

bot ファンクションは Azure ファンクションとしての要素と BotFramework としての要素があります。

Azure ファンクション: botindex.js

まず Azure ファンクションの実装を確認していきます。

1. module.exports で HttpRequest が来た際に要求を受ける処理を公開。LancerFetcher と異なり、listen(req, response(context)); の一行だけで実質内部関数を呼んでいるだけ。

image_thumb[28]

2. listen は const として定義されており、connector.listen が相当。

image_thumb[30]

3. connector は一番上に const として定義されており、../lib/bot を読み込んで、公開されている connector にアクセスしている。

image_thumb[38]

4. response 関数は listen の引数として渡している。この方法で既定の挙動を上書きできるが、ここではログを追加している程度であるためあまり気にしなくて良い。

Bot Framework モジュール libbot

次に Bot Framework のモジュールが格納されている libbot ディレクトリの中身を確認してきます。

1. ボットの本体は botindex.js にある。また dialogs フォルダには 2 つのダイアログが存在。server.js は bot 単体で起動する際に利用する restfy を含んでいる、しかし今回は Azure ファンクションの一部として稼働し、ボット単体でホストしないため利用しない。

image_thumb[32]

2. bot 直下の index.js の実装を確認。冒頭から botbuilder の読み込みと、各ダイアログを取得、および connector と bot の作成。その後ダイアログのセットアップを行う。ここまではテンプレ通り。Bot Framework に触るのが初めての場合、こちらの記事の手順を一度やることを推奨。

image_thumb[34]

3. 一番下にある module.exports で connector を公開。これが Azure ファンクションの bot 関数から呼ばれているものの実体。

image_thumb[36]

Bot Framework ダイアログ

Bot Framework は 1 問 1 答の簡単なボットだけではなく、会話形式をサポートしており、その機能をダイアログと呼びます。詳細はこちら。このソリューションでは 2 つのダイアログがありますが、dialogsindex.js をメインに使い、handleParameters.js は子ダイアログとして実行されます。

1. メインのダイアログとなる dialogsindex.js を確認。冒頭でモジュールの読み込み。4 行目、5 行目ではタスク (コマンド) の一覧の読み込みや変更などを、ローカルのメモリから読み込むか、リモートのデータベースに対して行うかを、環境変数から取得。設定は local.settings.json にある。ワークショップの最後で CosmosDB を設定するが、その場合 UseInMemoryStore が false になる。7 行目ではタスクサービスをローカルから読み込むか、リモート Web API から実行するかを指定。その場合、合わせて TASKAPIHOST 名も正しく設定。

image_thumb[51]

2. Bot Framework のダイアログは、上から順番に処理されるウォーターフォール形式。まず一番初めの会話は挨拶確認。hello か squire を送られてきた場合は挨拶を返し、それ以外の場合は次の会話へユーザーからの入力を引数に遷移。

image_thumb[43]

3. 次の会話では、ユーザーから送られてきたメッセージ (コマンド) を検索。コマンドがあった場合、タスク (コマンド) に必要なパラメーターをユーザーに聞くために、handleParameters ダイアログを子ダイアログとして開始。タスク見つからない場合はエラーを返信。

image_thumb[45]

4. 最後の会話でマンドと、ユーザーから集めたパラメーターの値で、実際の処理を実行。

5. handleParameters.js を開くと、基本的には index.js と同じだが、必要なモジュールは botbuilder のみ。はじめの会話で index.js から受け取ったパラメーターの一覧を session オブジェクトに代入。確認するパラメーターがない場合は、そのまま endDialog を実行して index ダイアログに結果を返す。

image_thumb[47]

6. 次の会話で自分を再起呼び出し。全てのパラメーターがなくなるまで繰り返し。

image_thumb[49]

ボットの部分は以上で終わりです。ダイアログに慣れないと記述が複雑に見えますが、順番に見ると分かりやすいです。

タスクサービス

タスクサービス libtasks.js に実装があるタスク (コマンド) を扱うサービスで、タスクの CRUD (Create/Read/Update/Delete) を行う taskService と、タスクを実行する taskRunnerService があります

1. libtasks.js を確認。一番下で 2 つのサービスを公開。

image_thumb[53]

2. 15 行目から 56 行目で既定のタスクを定義。UseInMemoryStore が true の場合に初期のタスクとして利用されるため、はじめから ”Fetch me my lance” コマンド等が利用可能。コマンド実行 URL と必要なパラメーターが定義されている。Web アプリ起動時に 2 つタスクが出てきたのもこのため。

image_thumb[57]

3. その下で Action、Parameter、Task など各種モデルの定義。

image_thumb[61]

4. そこからタスクサービスの実装とモデルの定義。内容はタスクの CRUD。

5. さらにその下にタスクランナーサービスの実装とモデルの定義。基本的にはタスクにある URL やパラメーターを元に HTTP リクエストを送信、結果のハンドルを行う。

データベースサービス

タスクを格納する先を、メモリではなく MongoDB にするヘルパーが lib/mongohelper.js に実装されています。これはあくまでヘルパーなのでここでの解説はしません。

task-api ファンクション

Azure ファンクションとして公開されるサービスの 1 つで、タスクサービスをリモートサービスとして使う場合に利用されます。

1. task-apiindex.js を確認。冒頭で ../lib/tasks を読み込んでいるので実体はタスクサービスを利用。

image_thumb[63]

2. ファンクションとしては 99 行目で run メソッドをだけを公開。run メソッドでは HTTP Verb 毎にタスクサービスの関数を呼び出す。

image_thumb[65]

ローカルのクラスを Web API として公開する参考としてとても勉強になります。

デバッグ

最後に Visual Studio Code でのデバッグ方法です。前回とほぼ同じです。

1. 今回の Azure ファンクションは npm start で起動しているが、start が実際に実行するコマンドは package.json に格納。ファイルを開き、scripts の start の引数をデバッグ用のものに変更。

func host start --debug vscode

image_thumb[79]

2. ターミナルより npm start で実行。変更した引数がついていることを確認。

image_thumb[83]

3. もしスクリプトを変更したくない場合は、npm start にダブルハイフンを付けると、それ以降を引数とできるため、同様の効果。

npm start -- --debug vscode

4. VSCode のデバッグメニューより F5 押下、または実行ボタンをクリック。ステータスバーがオレンジに変わればアタッチ完了。

image_thumb[67]

5. 必要な場所にブレークポイントを置いて実行。

ボットのデバッグ

折角なのでボットの部分をデバッグしてみましょう。

1. botindex.js 40 行目にブレークポイントを設定。

image_thumb[69]

2. libbotdialogsindex.js の 13 行目にもブレークポイントを設定。

image_thumb[71]

3. func host start で Azure ファンクションを開始。全てのファンクションが実行され、デバッガーが 5858 で待っていることを確認。

image_thumb[73]

4. Visual Studio Code でデバッグ開始。

5. BotFramework Emulator を開始し、http://localhost:7071/api/bot に接続。ID やパスワードは不要。

image_thumb[75]

6. Connect した瞬間にブレークポイントにヒットするので、F5 で継続。

7. hello と送信。再度ブレークポイントにヒット。F5 で継続。

image_thumb[77]

8. 続いてダイアログのブレークポイントにヒット。ここからは F11 等で好きにデバッグ。

Web アプリ

Angular 2 ベースの Web アプリです。このアプリを説明しだすと Angular 2 の世界にどっぷりですが、重要な点はワークショップでも触れている通り、タスクサービスのページと関連設定のみです。

Azure への展開

ワークショップでは開発したものを全て Azure に展開していますが、ここでも特に Deep Dive は必要なさそうなので割愛します。

まとめ

このモジュールでは Azure ファンクション、Bot Framework、CosmosDB、Angular と関連技術が山盛りのため、興味があれば勉強する材料には困りません。Serverless 観点からは Azure ファンクションだけ確認してください。次回はモジュール 4 を見ていきます。

中村 憲一郎

Azure Serverless ワークショップ Deep Dive : モジュール 4

$
0
0

前回に続いて、今回はモジュール 4  の Deep Dive です。

GitHub: https://github.com/Azure-Samples/azure-serverless-workshop-team-assistant/tree/lang/jp/4-github-bot

概要

このモジュールでは Logic Apps を使ったボット機能の拡張をしています。全て GUI のため迷うところは少ないですが、面白い点はボットの登録先は Azure ファンクションである必要がなく、REST ベースで呼べるものであれば良い点です。

Logic App 作成時のトラブルシューティング

作成時点でうまくいかない場合は、以下の方法でトラブルシューティングできます。

ログの確認

1. アクティビティログを選択。

image

2. フィルター条件を指定して、適用。

image

GUI でうまく操作できない

ごく稀に、GUI でうまく入力できないなどの問題が出ます。その場合は以下の方法でトラブルシュートできます。

- 最新のブラウザまたは異なるブラウザで試してみる
- ズーム比率を変えて試してみる
- 余計なブレードを閉じて領域を確保する

それでもうまくいかない場合、Code View を使って直接編集することも可能です。慣れないうちは難しい感じがしますが、JSON 形式で定義されているだけですので、順番に見ると分かるはずです。

1. Logic App のメニューから Code View を開きます。

image

2. 必要な個所を編集して保存します。

Logic App 実行時のトラブルシューティング

構成は簡単なものの、うまく動作しない場合のトラブルシューティングは知っておいて損はないでしょう。

実行ログ

1. Azure ポータルより作成した Logic App を選択。Overview に Runs history と Trigger History がある。

image

2. Run history は実行履歴。Failed になっているものを開くと以下のように失敗した詳細が確認可能。この場合、”Create an issue” ステップで失敗。

image

3. 失敗したステップをクリックして展開。入出力の詳細が確認可能。この場合、"Issues are disabled for this repo" とあるため、Issue を登録できないレポジトリに登録しようとして失敗したと分かる。

image

image

4. ”Show raw inputs/outputs” リンクをクリックすると、raw データが確認可能。

5. 問題が修正できる場合は、修正後 ”Resubmit” ボタンをクリックすると同じ条件で再実行可能。

6. 一方 Trigger History は Logic App がトリガーされた履歴。そもそもトリガー出来ているかを確認するのに有用。

API 接続

Logic Apps を使うメリットは、各種サービスに対する接続とアクションが GUI で簡単に定義できることです。接続は API 接続として作成されますが、これを知っていると切り分けが容易になります。認証がうまくいっていない場合は、API 接続を確認してください。

1. メニューより API Connections を選択。

image

2. このモジュールでは GitHub に対する操作を追加したため、github 接続が作成されている。

image

3. 選択すると詳細が表示される。

image

4. ”API 接続の編集” をクリックすると、接続の詳細が確認可能。接続の種類によっては明示的な ”承認” が必要な場合もあり。その場合は ”承認する” ボタンをクリック。

image

尚、API 接続はリソースグループレベルで作成されるため、リソースグループの画面でも出てきます。

IP アドレス

Log Apps が外部のサービスにアクセスする場合、そちらのサービスで IP アドレス制限をかけているかもしれません。以下の方法で IP を確認します。

1. Properties を選択。

image

2. 各種設定の確認。OUTGOING アドレスは Logic Apps が外部サービスに接続する際に利用するアドレスで、ACCESS ENDPOINT は Logic Apps にアクセスする際に使う IP アドレス。

image

まとめ

Serverless テクノロジーの課題として、うまくいかない場合のトラブルシューティングがあります。Logic App も最近ではローカルで開発、テストをしてから公開することが出来るようになっていますので、是非そちらも検討してください。

参考: Visual Studio で Azure Logic Apps を作成してデプロイする

中村 憲一郎

Azure Serverless ワークショップ Deep Dive : モジュール 5

$
0
0

前回に続いて、今回はモジュール 5  の Deep Dive です。

GitHub: https://github.com/Azure-Samples/azure-serverless-workshop-team-assistant/tree/lang/jp/5-voting-service

モジュール 5 は v1 が付きと無しがありますが、v1 は Windows 環境のみでサポートされる Azure ファンクション v1 の CLI 対応です。ここではマルチプラットフォームである v2 を対象にします。

概要

このモジュールでは投票を行える機能を実装します。以下の絵にあるように、合計 5 つ投票系のファンクションを作成し、Squire ボットに連携する仕組みです。

アーキテクチャ

注意点

今日の時点で確認した限り、CosmosDB の拡張モジュール導入に日本語 UI 環境では失敗します。こちらのモジュールは英語 UI に切り替えて試してください。

プログラムの解析

基本的にはコマンドを実行して、コードをコピーしていけば動作しますが、いくつかポイントを見ていきます。

バインディング

あまり触れてきませんでしたが、Azure ファンクションの特徴の 1 つにバインディングがあります。バインディングは外部サービスなどの連携に利用される技術で、 function.json ファイルで定義され、index.json などメインのコードから利用できます。

1. CreateVotingNode の function.json を開き、内容を確認。はじめのバインディングは、方向が in で名前が req と指定されており、タイプが httpTrigger となっている。これはファンクションが Http リクエストでトリガーされることを示しており、req をコードから利用可能。

image

2. index.js を開き、req の使われ方を確認。HttpRequest オブジェクトのため、body を含んでおり、req.body でデータにアクセス可能。

image

3. 次のバインディングは方向が out で名前が res。

image

4. コード内では結果を返す際に利用。req は関数の引数で渡ってきていたため直接アクセスしているが、res は context に含まれる形。

image

5. 3 つ目は CosmosDB に対する出力用のバインディング。CosmosDB 関連の設定を含み、名前が outputDocument。接続文字列は votingbot_DOCUMENTDB となっており、local.settings.json から値を取得できる仕組み。

image

6. バインディングの仕組みがあるため、CosmosDB に対するデータの書き込みは 1 行。非常にシンプルに記述が可能。

image

7. バインディングは入力または出力には利用が容易だが、このサンプルでは削除処理はメインのコード内で処理している。DeleteVotingNode の index.json を開いて冒頭のモジュール読みこみを確認。接続文字列は共通のため、設定ファイルより読みこまれる process.env から取得。

image

8. 作成した client オブジェクトを使って削除処理を実行。

image

CosmosDB での確認

Azure ポータルから CosmosDB の中身も確認できます。レコード作成のトラブルシューティングにも使えるのでポータルからも操作を確認してください。

まとめ

バインディングを理解できると Azure ファンクションを使いこなすことが出来ます。非常に多くのバインディングをサポートしていますので色々試してください。

中村 憲一郎

Viewing all 5308 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>