Your content here
Artemis Setup Raspberry : Panduan setup environtment buat ngerjain tesis di raspi.
Artemis Setup Ubuntu : Panduan setup environtment buat ngerjain tesis di ubuntu (native).
Model : yolov8n_best.pt
Program optimasi : file instant_exporter.py, disebut instant karena ini pake banduan library ultralytics.
import os
import time
import pandas as pd
import numpy as np
import threading
import subprocess
import re
from ultralytics import YOLO
# =====================================================
# CONFIGURATION
# =====================================================
MODEL_DIR = "../model/experimental_variants_instant"
DATASET_ROOT = "../../01_raw_dataset"
DATA_YAML = "pi5_test.yaml"
OUTPUT_CSV = "../output/pi5_experimental_results.csv"
FOCUS_MODELS = ['float32.tflite', 'float16.tflite', 'full_integer_quant.tflite']
# =====================================================
# DATASET YAML (WAJIB train + val)
# =====================================================
abs_root = os.path.abspath(DATASET_ROOT)
with open(DATA_YAML, "w") as f:
f.write(f"""
path: {abs_root}
train: train/images
val: valid/images
test: test/images
names:
0: fire
""")
# =====================================================
# TEMPERATURE
# =====================================================
def get_cpu_temp():
try:
with open("/sys/class/thermal/thermal_zone0/temp") as f:
return float(f.read()) / 1000.0
except:
return 0.0
# =====================================================
# PMIC POWER (Raspberry Pi 5)
# =====================================================
def read_pmic():
try:
return subprocess.check_output(
["vcgencmd", "pmic_read_adc"],
text=True
)
except:
return ""
def extract_value(label, text):
m = re.search(rf"{label}.*?=([0-9.]+)", text)
return float(m.group(1)) if m else 0.0
def get_core_power():
data = read_pmic()
v = extract_value("VDD_CORE_V", data)
c = extract_value("VDD_CORE_A", data)
return v * c
class PowerMonitorPi5:
def __init__(self):
self.keep_running = False
self.samples = []
def start(self):
self.keep_running = True
self.samples = []
self.thread = threading.Thread(target=self._run)
self.thread.start()
def _run(self):
while self.keep_running:
p = get_core_power()
if p > 0:
self.samples.append(p)
time.sleep(0.1)
def stop(self):
self.keep_running = False
self.thread.join()
return np.mean(self.samples) if self.samples else 0.0
# =====================================================
# MAIN BENCHMARK
# =====================================================
monitor = PowerMonitorPi5()
results = []
print("\n--- Memulai Benchmark Final Raspberry Pi 5 ---")
for m_file in sorted(os.listdir(MODEL_DIR)):
if not any(x in m_file for x in FOCUS_MODELS):
continue
model_path = os.path.join(MODEL_DIR, m_file)
print(f"\nMenguji: {m_file}")
model = YOLO(model_path, task='detect')
monitor.start()
val_res = model.val(
data=DATA_YAML,
split='test',
imgsz=640,
batch=1,
verbose=False
)
avg_power = monitor.stop()
curr_temp = get_cpu_temp()
latency = val_res.speed['inference']
precision = val_res.results_dict["metrics/precision(B)"]
recall = val_res.results_dict["metrics/recall(B)"]
f1 = (2 * precision * recall) / (precision + recall) if (precision + recall) > 0 else 0.0
results.append({
"Model": m_file,
"Precision": round(precision, 4),
"Recall": round(recall, 4),
"F1": round(f1, 4),
"mAP50": round(val_res.results_dict["metrics/mAP50(B)"], 4),
"mAP50-95": round(val_res.results_dict["metrics/mAP50-95(B)"], 4),
"Latency(ms)": round(latency, 2),
"FPS": round(1000 / latency, 2),
"Power_CPU_Core(W)": round(avg_power, 3),
"Energy_per_inference(J)": round(avg_power * (latency / 1000), 4),
"Temp(C)": round(curr_temp, 2)
})
# =====================================================
# SAVE RESULTS
# =====================================================
df = pd.DataFrame(results)
print("\n" + "=" * 120)
print(df.to_string(index=False))
print("=" * 120)
df.to_csv(OUTPUT_CSV, index=False)
print(f"\nHasil disimpan ke: {OUTPUT_CSV}")
import os
import time
import board
import busio
import threading
import numpy as np
import pandas as pd
from adafruit_ina219 import INA219
from ultralytics import YOLO
# =====================================================
# 1. KONFIGURASI PATH & DATASET
# =====================================================
MODEL_DIR = "../model/experimental_variants" # Folder berisi .tflite
TEST_DIR = "../dataset/test" # Berisi /images dan /labels
OUTPUT_CSV = "../output/pi4_experimental_results.csv"
# Buat file YAML dataset otomatis
DATA_YAML = f"""
path: {os.path.abspath(TEST_DIR)}
test: images
names:
0: fire
"""
with open("pi_test.yaml", "w") as f:
f.write(DATA_YAML)
# =====================================================
# 2. MONITORING DAYA (INA219 - RPi 4)
# =====================================================
class PowerMonitorPi4:
def __init__(self):
i2c = busio.I2C(board.SCL, board.SDA)
self.ina = INA219(i2c)
self.koreksi = 1.28
self.keep_running = False
self.power_samples = []
def start(self):
self.keep_running = True
self.power_samples = []
self.thread = threading.Thread(target=self._monitor)
self.thread.start()
def _monitor(self):
while self.keep_running:
v = self.ina.bus_voltage
c = self.ina.current / 1000.0 # mA -> A
p = (v * c) * self.koreksi
self.power_samples.append(p)
time.sleep(0.5) # sampling 500 ms
def stop(self):
self.keep_running = False
self.thread.join()
return np.mean(self.power_samples) if self.power_samples else 0.0
# =====================================================
# 3. CPU TEMPERATURE
# =====================================================
def get_cpu_temp():
try:
with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
return float(f.read()) / 1000.0
except:
return 0.0
# =====================================================
# 4. LOOP EVALUASI EKSPERIMEN
# =====================================================
def main():
if not os.path.exists(MODEL_DIR):
print(f"Error: Folder {MODEL_DIR} tidak ditemukan!")
return
model_files = [f for f in os.listdir(MODEL_DIR) if f.endswith(".tflite")]
if not model_files:
print("Error: Tidak ada file .tflite di folder model!")
return
monitor = PowerMonitorPi4()
final_data = []
print("\n--- Memulai Evaluasi Komprehensif Raspberry Pi 4 ---")
print(f"Dataset: {TEST_DIR} | Iterasi: Full Test Set")
for m_file in sorted(model_files):
m_path = os.path.join(MODEL_DIR, m_file)
print(f"\n Memproses Varian: {m_file}")
model = YOLO(m_path, task="detect")
size_mb = os.path.getsize(m_path) / (1024 * 1024)
start_temp = get_cpu_temp()
monitor.start()
val_results = model.val(
data="pi_test.yaml",
split="test",
imgsz=640,
batch=1,
verbose=False
)
avg_power = monitor.stop()
end_temp = get_cpu_temp()
map50 = val_results.results_dict["metrics/mAP50(B)"]
latency = val_results.speed["inference"]
fps = 1000 / latency
energy_per_inf = avg_power * (latency / 1000.0)
res = {
"Method": m_file.replace(".tflite", ""),
"Size (MB)": round(size_mb, 2),
"mAP50": round(map50, 4),
"Latency (ms)": round(latency, 2),
"FPS": round(fps, 2),
"Avg Power (W)": round(avg_power, 3),
"Energy/Inf (J)": round(energy_per_inf, 4),
"CPU Temp (C)": round(end_temp, 2)
}
final_data.append(res)
print(f" > Hasil: {res['FPS']} FPS | {res['mAP50']} mAP | {res['Avg Power (W)']} W")
# =====================================================
# 5. OUTPUT
# =====================================================
df = pd.DataFrame(final_data)
print("\n" + "=" * 100)
print(f"{'HASIL EKSPERIMEN OPTIMASI ARTE-MIS (RPi 4)':^100}")
print("=" * 100)
print(df.to_string(index=False))
print("=" * 100)
df.to_csv(OUTPUT_CSV, index=False)
print(f"\n Data berhasil disimpan ke {OUTPUT_CSV}")
print("Gunakan data ini untuk tabel dan grafik analisis di tesis kamu.")
if __name__ == "__main__":
main()
import os
import time
import pandas as pd
import numpy as np
import threading
import subprocess
import re
from ultralytics import YOLO
# =====================================================
# CONFIGURATION
# =====================================================
MODEL_DIR = "../model/experimental_variants_instant"
DATASET_ROOT = "../dataset/01_raw_dataset"
OUTPUT_CSV = "../output/pi5_experimental_results.csv"
DATA_YAML = "pi5_dataset.yaml"
# =====================================================
# CREATE DATASET YAML (WAJIB ADA train & val)
# =====================================================
abs_dataset_path = os.path.abspath(DATASET_ROOT)
with open(DATA_YAML, "w") as f:
f.write(f"path: {abs_dataset_path}\n")
f.write("train: train/images\n")
f.write("val: valid/images\n")
f.write("test: test/images\n")
f.write("names:\n")
f.write(" 0: fire\n")
# =====================================================
# SENSOR FUNCTIONS
# =====================================================
def get_cpu_temp():
try:
with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
return float(f.read()) / 1000.0
except:
return 0.0
def read_pmic():
try:
return subprocess.check_output(
["vcgencmd", "pmic_read_adc"],
text=True
)
except:
return ""
def extract_value(label, text):
m = re.search(rf"{label}.*?=([0-9.]+)", text)
return float(m.group(1)) if m else 0.0
def get_core_power():
data = read_pmic()
v = extract_value("VDD_CORE_V", data)
c = extract_value("VDD_CORE_A", data)
return v * c
# =====================================================
# POWER MONITOR CLASS
# =====================================================
class PowerMonitorPi5:
def __init__(self):
self.keep_running = False
self.power_samples = []
def start(self):
self.keep_running = True
self.power_samples = []
self.thread = threading.Thread(target=self._monitor)
self.thread.start()
def _monitor(self):
while self.keep_running:
p = get_core_power()
if p > 0:
self.power_samples.append(p)
time.sleep(0.1)
def stop(self):
self.keep_running = False
self.thread.join()
return np.mean(self.power_samples) if self.power_samples else 0.0
# =====================================================
# MAIN BENCHMARK
# =====================================================
monitor = PowerMonitorPi5()
results = []
focus_models = ['float32.tflite', 'float16.tflite', 'full_integer']
print("--- Memulai Benchmark Final Raspberry Pi 5 ---")
for m_file in sorted(os.listdir(MODEL_DIR)):
if not any(target in m_file for target in focus_models):
continue
print(f"\nMenguji: {m_file}")
model = YOLO(os.path.join(MODEL_DIR, m_file), task='detect')
monitor.start()
val_res = model.val(
data=DATA_YAML,
split='test',
imgsz=640,
batch=1,
verbose=False
)
avg_power = monitor.stop()
curr_temp = get_cpu_temp()
speed = val_res.speed["inference"]
results.append({
"Model": m_file,
"mAP50": round(val_res.results_dict["metrics/mAP50(B)"], 4),
"mAP50-95": round(val_res.results_dict["metrics/mAP50-95(B)"], 4),
"Precision": round(val_res.results_dict["metrics/precision(B)"], 4),
"Recall": round(val_res.results_dict["metrics/recall(B)"], 4),
"Latency(ms)": round(speed, 2),
"FPS": round(1000 / speed, 2),
"CPU_Core_Power(W)": round(avg_power, 3),
"Energy_per_inference(J)": round(avg_power * (speed / 1000), 4),
"Temp(C)": round(curr_temp, 2)
})
df = pd.DataFrame(results)
print("\n" + "=" * 120 + "\n", df.to_string(index=False), "\n" + "=" * 120)
df.to_csv(OUTPUT_CSV, index=False)
print(f"\nHasil disimpan ke: {OUTPUT_CSV}")
Hasil dari optimasi, ada 3 file berikut: