
print("hello python")
from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential
# Initialize MLClient using your local workspace config
ml_client = MLClient.from_config(credential=DefaultAzureCredential())
# Get the registered data asset metadata
data_asset = ml_client.data.get(name="iris", version="1")
# Extract the cloud or local path string
data_path = data_asset.path
data_path
import pandas as pd
# Load directly using the file path URI
df = pd.read_csv(data_path)
df
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score
# --- 1. Prepare data ---
# (Assuming 'df' contains your loaded Azure data asset dataframe)
# Split features (X) and target label (y)
X = df[['sepal.length', 'sepal.width', 'petal.length', 'petal.width']]
y = df['variety']
# Convert text labels ('Setosa', etc.) into numbers (0, 1, 2)
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
# --- 2. Train-Test Split ---
# Split data: 80% for training, 20% for testing
X_train, X_test, y_train, y_test = train_test_split(
X, y_encoded, test_size=0.2, random_state=42, stratify=y_encoded
)
# --- 3. Model Training ---
# Initialize and train the Random Forest model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# --- 4. Evaluation ---
# Predict on the test set
y_pred = model.predict(X_test)
# Print accuracy and performance breakdown
print(f"Accuracy: {accuracy_score(y_test, y_pred) * 100:.2f}%\n")
print("Classification Report:")
print(classification_report(y_test, y_pred, target_names=label_encoder.classes_))
%pip install seaborn
import matplotlib.pyplot as plt
import seaborn as sns
# Set style for cleaner graphs
sns.set_theme(style="ticks")
# Plot all features colored by the 'variety' column
pair_plot = sns.pairplot(df, hue="variety", palette="Set2", diag_kind="kde")
pair_plot.fig.suptitle("Iris Dataset Feature Relationships", y=1.02)
plt.show()
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
# Create a figure with two subplots side-by-side
fig, ax = plt.subplots(1, 2, figsize=(14, 5))
# --- Plot 1: Confusion Matrix ---
cm = confusion_matrix(y_test, y_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=label_encoder.classes_)
disp.plot(cmap="Blues", ax=ax[0], values_format='d')
ax[0].set_title("Confusion Matrix")
ax[0].grid(False) # Turn off grid lines for clean visual
# --- Plot 2: Feature Importance ---
# Get feature scores from your trained random forest model
importances = model.feature_importances_
feature_names = X.columns
# Sort features by importance
feat_importances = pd.Series(importances, index=feature_names).sort_values(ascending=True)
# Plot horizontal bar chart
feat_importances.plot(kind='barh', color='skyblue', ax=ax[1])
ax[1].set_title("Feature Importance (Random Forest)")
ax[1].set_xlabel("Relative Importance Score")
plt.tight_layout()
plt.show()
import joblib
# Save the trained Random Forest model
joblib.dump(model, 'iris_random_forest_model.pkl')
# Save the label encoder (crucial for decoding predictions later)
joblib.dump(label_encoder, 'iris_label_encoder.pkl')
print("Model and Label Encoder saved locally successfully!")
import joblib
import pandas as pd
# Load kembali model dan encoder dari direktori Anda
loaded_model = joblib.load('iris_random_forest_model.pkl')
loaded_encoder = joblib.load('iris_label_encoder.pkl')
print("Model dan Label Encoder berhasil dimuat!")
data_baru = pd.DataFrame([[5.1, 3.5, 1.4, 0.2]],
columns=['sepal.length', 'sepal.width', 'petal.length', 'petal.width'])
prediksi_angka = loaded_model.predict(data_baru)
prediksi_nama = loaded_encoder.inverse_transform(prediksi_angka)
print(f"Hasil prediksi untuk data baru: {prediksi_nama[0]}")
Download notebook here
Practical Machine Learning Course using Azure ML
Want to learn Machine Learning without getting overwhelmed by programming and complex mathematics? Practical Machine Learning Course using Azure ML is designed specifically for learners who want to understand and apply Machine Learning using Microsoft Azure, including students with little or absolutely no coding experience.
This course takes a practical, beginner-friendly approach to Machine Learning. You will learn how to build and work with Machine Learning solutions using Azure Machine Learning, with a strong focus on Azure's low-code and no-code capabilities.
The main focus of the course is Azure Automated ML (Automated Machine Learning) and Azure Designer, where you can create Machine Learning models and workflows with minimal or no programming. You will learn how to prepare data, configure Machine Learning experiments, train models, evaluate results, and understand how Azure helps automate many of the traditionally complex Machine Learning tasks.
The course is also designed for students who may want to go beyond the no-code approach. As an additional skillset, the course introduces Azure Machine Learning Notebooks, giving you an opportunity to learn how Machine Learning can be implemented using Python and code within the Azure environment.
You do not need to be a programmer to start this course. The no-code/low-code sections are designed to help you understand the practical Machine Learning process first. If you already know coding—or decide that you want to learn coding later—the notebook section provides a pathway toward a more hands-on, code-based approach.
In this course, you will explore:
Machine Learning fundamentals and practical concepts
Azure Machine Learning
Azure Automated ML
Building Machine Learning models with minimal/no coding
Azure Machine Learning Designer
Data preparation and model training
Model evaluation and comparison
Understanding Machine Learning workflows
Azure Machine Learning Notebooks as an additional coding skillset
Introduction to implementing Machine Learning using Python in Azure
By the end of the course, you will have a practical understanding of how Azure ML can simplify the Machine Learning development process, whether you prefer a no-code approach or want to take the next step toward coding.
This course is ideal for beginners, business professionals, students, aspiring data scientists, analysts, and anyone interested in learning practical Machine Learning using Microsoft Azure without requiring extensive programming experience.