
Photo by Philip Rasch
Navigating through the Paris Metros offers convenience, yet it can become challenging during peak hours due to crowded conditions and limited seating availability. Thanks to advanced predictive tools, commuters can now strategize their trips more efficiently, sidestepping the hassles of packed trains.
In this piece, we delve into crafting a prototype for forecasting crowd levels in Paris Métros using Azure, Microsoft’s cloud solution. Detailed guidance and coding illustrations in C# and Terraform will be presented to initiate your journey.
Connect and Create resources in Azure
The provided code demonstrates the authentication process with Azure through the AuthenticationContext class within the Microsoft.IdentityModel.Clients.ActiveDirectory namespace. Subsequently, it initializes a DataFactoryManagementClient instance from the Microsoft.Azure.Management.DataFactory namespace to engage with the Azure Data Factory.
Furthermore, the code illustrates the creation of a data factory and the establishment of input and output datasets utilizing the AzureBlobDataset class. It also outlines the formulation of a pipeline incorporating a copy operation from the input dataset to the designated output dataset.
This code can serve as a foundational blueprint for designing your personalized data workflows within Azure Data Factory. Ensure adaptation to your distinct requirements by substituting variables like tenantId, clientId, clientSecret, subscriptionId, factoryName, resourceGroup, and storageConnectionString.
using Microsoft.Azure.Management.DataFactory;
using Microsoft.Azure.Management.DataFactory.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
namespace DataFactoryExample
{
class Program
{
static void Main()
{
// Authenticate and create a DataFactoryManagementClient
var client = AuthenticateDataFactoryClient("tenantId", "clientId", "clientSecret", "subscriptionId");
// Define resource group and factory name
var resourceGroup = "dev-rgp";
var factoryName = "dev-adf";
// Create Data Factory and datasets
CreateDataFactory(client, resourceGroup, factoryName);
CreateDatasets(client, resourceGroup, factoryName);
// Create pipeline
CreatePipeline(client, resourceGroup, factoryName);
// Create a pipeline run
CreatePipelineRun(client, resourceGroup, factoryName);
}
// Authenticate and create DataFactoryManagementClient
static DataFactoryManagementClient AuthenticateDataFactoryClient(string tenantId, string clientId, string clientSecret, string subscriptionId)
{
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;
ServiceClientCredentials cred = new TokenCredentials(authenticationResult.AccessToken);
var client = new DataFactoryManagementClient(cred) { SubscriptionId = subscriptionId };
return client;
}
// Create Data Factory
static void CreateDataFactory(DataFactoryManagementClient client, string resourceGroup, string factoryName)
{
var dataFactory = new Factory { Location = "francecentral" };
client.Factories.CreateOrUpdate(resourceGroup, factoryName, dataFactory);
Console.WriteLine("Data Factory created successfully.");
}
// Create Input and Output datasets
static void CreateDatasets(DataFactoryManagementClient client, string resourceGroup, string factoryName)
{
CreateDataset(client, resourceGroup, factoryName, "input", "input.txt", "InputDataset");
CreateDataset(client, resourceGroup, factoryName, "output", "output.txt", "OutputDataset");
Console.WriteLine("Datasets created successfully.");
}
// Helper method to create dataset
static void CreateDataset(DataFactoryManagementClient client, string resourceGroup, string factoryName, string blobPath, string blobFilename, string datasetName)
{
var dataset = new DatasetResource(
new AzureBlobDataset
{
LinkedServiceName = new LinkedServiceReference { ReferenceName = "AzureBlobStorageLinkedService" },
FolderPath = blobPath,
FileName = blobFilename,
Format = new TextFormat()
}
);
client.Datasets.CreateOrUpdate(resourceGroup, factoryName, datasetName, dataset);
}
// Create pipeline with a copy activity
static void CreatePipeline(DataFactoryManagementClient client, string resourceGroup, string factoryName)
{
var pipelineName = "Prediction_Pipeline";
var pipeline = new PipelineResource
{
Activities = new List<Activity>
{
new CopyActivity
{
Name = "CopyFromBlobToBlob",
Inputs = new List<DatasetReference> { new DatasetReference() { ReferenceName = "InputDataset" } },
Outputs = new List<DatasetReference> { new DatasetReference() { ReferenceName = "OutputDataset" } },
Source = new BlobSource(),
Sink = new BlobSink()
}
}
};
client.Pipelines.CreateOrUpdate(resourceGroup, factoryName, pipelineName, pipeline);
Console.WriteLine("Pipeline created successfully.");
}
// Create pipeline run
static void CreatePipelineRun(DataFactoryManagementClient client, string resourceGroup, string factoryName)
{
CreateRunResponse runResponse = client.Pipelines.CreateRunWithHttpMessagesAsync(resourceGroup, factoryName, "Prediction_Pipeline").Result.Body;
Console.WriteLine("Pipeline run created successfully.");
}
}
}
Train a Machine Learning Algorithm
Subsequently, it’s essential to train a machine learning algorithm using the accumulated data for predictive purposes. Employ Azure Machine Learning, a cloud-centric platform dedicated to constructing, refining, and deploying machine learning models, for this task.
Below is an illustration demonstrating the training of a machine learning algorithm utilizing C# in conjunction with the Azure Machine Learning.
using Microsoft.ML;
using Microsoft.ML.Data;
public class MetroTravelData
{
[LoadColumn(0)]
public float NumberOfPassengers;
[LoadColumn(1)]
public float TimeOfDay;
[LoadColumn(2)]
public float DayOfWeek;
[LoadColumn(3)]
public bool IsHoliday;
[LoadColumn(4)]
public string LevelOfCrowdedness;
}
// Define the input for model prediction
public class MetroTravelInput
{
public float NumberOfPassengers;
public float TimeOfDay;
public float DayOfWeek;
public bool IsHoliday;
}
// Define the output after model prediction
public class MetroTravelOutput
{
[ColumnName("PredictedLabel")]
public string PredictedCrowdednessLevel;
}
class Program
{
static void Main()
{
// Create MLContext
var mlContext = new MLContext();
// Load the dataset
var dataset = mlContext.Data.LoadFromTextFile<MetroTravelData>("data.csv", separatorChar: ',');
// Split the dataset into training and testing sets
var trainTestSplit = mlContext.Data.TrainTestSplit(dataset);
var trainingData = trainTestSplit.TrainSet;
var testingData = trainTestSplit.TestSet;
// Define the data processing pipeline
var dataProcessingPipeline = mlContext.Transforms.Conversion.MapValueToKey("LevelOfCrowdedness")
.Append(mlContext.Transforms.Concatenate("Features", new[] { "NumberOfPassengers", "TimeOfDay", "DayOfWeek", "IsHoliday" }))
.Append(mlContext.Transforms.NormalizeMinMax("Features"));
// Define the training algorithm
var classificationTrainer = mlContext.MulticlassClassification.Trainers.SdcaNonCalibrated();
var trainingPipeline = dataProcessingPipeline
.Append(classificationTrainer)
.Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
// Train the model
ITransformer trainedModel = trainingPipeline.Fit(trainingData);
// Evaluate the model
var modelPredictions = trainedModel.Transform(testingData);
var modelMetrics = mlContext.MulticlassClassification.Evaluate(modelPredictions);
}
}
This script demonstrates the utilization of the MLContext class within the Microsoft.ML namespace to establish a machine learning environment. It employs the LoadFromTextFile function to ingest data from a CSV file into an IDataView structure.
Subsequently, the code illustrates the division of the dataset into training and validation subsets via the TrainTestSplit function. Furthermore, it constructs a data transformation pipeline utilizing various transformations available in the Microsoft.ML.Transforms namespace.

Join the conversation! Your thoughts help the community grow.