slogan3

Ontwikkel een Python-script voor machine learning model training en evaluatie

description

Met deze prompt kan de gebruiker een volledig machine learning pipeline in Python opzetten, inclusief data preprocessing, modeltraining en evaluatie. Het helpt gebruikers die willen leren hoe ze machine learning modellen praktisch kunnen implementeren en optimaliseren met populaire Python-bibliotheken. Dit is nuttiger dan simpele codevoorbeelden omdat het een compleet proces behandelt en uitleg geeft over de gebruikte technieken.

prompt

Help me een Python-script te schrijven dat een machine learning model traint en evalueert op basis van de volgende dataset: <voer de datasetbeschrijving of URL in>. Gebruik hierbij algoritmes zoals <voer het gewenste algoritme in, bijvoorbeeld Random Forest, ...

try_prompt

generate_helper
disclaimerOnPageApi

ai_answers

provider: openai
model: gpt-4.1-nano
Hier is een voorbeeld van een Python-script dat een Random Forest-model traint en evalueert op de Iris-dataset van UCI, inclusief data preprocessing, modeltraining, validatie en prestatie-indicatoren. ```python import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, classification_report # Stap 1: Data laden iris = load_iris() X = iris.data y = iris.target # Stap 2: Data splitsen in training- en testset X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y) # Stap 3: Model trainen model = RandomForestClassifier(n_estimators=100, random_state=42) model.fit(X_train, y_train) # Stap 4: Voorspellingen maken y_pred = model.predict(X_test) # Stap 5: Model evalueren accuracy = accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred, average='macro') recall = recall_score(y_test, y_pred, average='macro') report = classification_report(y_test, y_pred, target_names=iris.target_names) # Resultaten tonen print("Nauwkeurigheid:", accuracy) print("Precisie:", precision) print("Recall:", recall) print("Gedetailleerd rapport:\n", report) ``` **Uitleg over bibliotheken:** - **scikit-learn**: Een uitgebreide bibliotheek voor machine learning in Python. In dit script worden onder andere `load_iris` voor datasets, `train_test_split` voor data verdeling, `RandomForestClassifier` voor modeltraining en `accuracy_score`, `precision_score`, `recall_score`, `classification_report` voor evaluatie gebruikt. - **TensorFlow of PyTorch**: Deze bibliotheken worden meestal gebruikt voor deep learning en neurale netwerken. Voor eenvoudige modellen zoals Random Forest is scikit-learn meestal voldoende en makkelijker te gebruiken. Wil je toch een neuraal netwerk bouwen, dan kun je TensorFlow of PyTorch gebruiken. Bijvoorbeeld, met TensorFlow kun je een model definiëren en trainen met `tf.keras.Sequential`. **Kort overzicht:** - Installeer benodigde bibliotheken indien nog niet aanwezig: ``` pip install scikit-learn pandas ``` Voor TensorFlow: ``` pip install tensorflow ``` Voor PyTorch: ``` pip install torch torchvision ``` **Samenvatting:** Het script laadt de Iris-dataset, splitst deze in training en test, traint een Random Forest classifier, maakt voorspellingen, en geeft een evaluatierapport met nauwkeurigheid, precisie en recall. Voor complexere modellen of deep learning kan TensorFlow of PyTorch worden gebruikt, afhankelijk van de complexiteit van de taak.
provider: deepseek
model: deepseek-chat
Hier is een compleet Python-script voor de Iris dataset met Random Forest: ```python # Vereiste bibliotheken importeren import pandas as pd import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import (accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report) import matplotlib.pyplot as plt import seaborn as sns # 1. DATA INLADEN EN VERKENNEN print("=== IRIS DATASET ANALYSE ===") # Data inladen iris = load_iris() X = iris.data # Features y = iris.target # Target variabele feature_names = iris.feature_names target_names = iris.target_names # DataFrame maken voor betere visualisatie df = pd.DataFrame(X, columns=feature_names) df['species'] = y df['species_name'] = [target_names[i] for i in y] print("Dataset vorm:", X.shape) print("Features:", feature_names) print("Klassen:", target_names) print("\nEerste 5 rijen:") print(df.head()) # 2. DATA PREPROCESSING print("\n=== DATA PREPROCESSING ===") # Controleren op ontbrekende waarden print("Ontbrekende waarden:", df.isnull().sum().sum()) # Features en target scheiden X = df.drop(['species', 'species_name'], axis=1) y = df['species'] # Data splitsen in train en test sets X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y ) # Feature scaling (normaliseren) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) print("Train set grootte:", X_train.shape) print("Test set grootte:", X_test.shape) # 3. MODEL TRAINING print("\n=== MODEL TRAINING ===") # Random Forest model initialiseren rf_model = RandomForestClassifier( n_estimators=100, random_state=42, max_depth=3 ) # Model trainen rf_model.fit(X_train_scaled, y_train) print("Model succesvol getraind!") # 4. MODEL EVALUATIE print("\n=== MODEL EVALUATIE ===") # Voorspellingen maken y_pred = rf_model.predict(X_test_scaled) y_pred_proba = rf_model.predict_proba(X_test_scaled) # Prestatiemetrics berekenen accuracy = accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred, average='weighted') recall = recall_score(y_test, y_pred, average='weighted') f1 = f1_score(y_test, y_pred, average='weighted') print(f"Nauwkeurigheid (Accuracy): {accuracy:.4f}") print(f"Precisie (Precision): {precision:.4f}") print(f"Recall: {recall:.4f}") print(f"F1-Score: {f1:.4f}") # Gedetailleerd classificatierapport print("\n=== GEDETAILLEERD CLASSIFICATIERAPPORT ===") print(classification_report(y_test, y_pred, target_names=target_names)) # Confusion matrix print("\n=== CONFUSION MATRIX ===") cm = confusion_matrix(y_test, y_pred) plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=target_names, yticklabels=target_names) plt.title('Confusion Matrix - Random Forest') plt.ylabel('Werkelijke waarde') plt.xlabel('Voorspelde waarde') plt.show() # 5. FEATURE IMPORTANCE print("\n=== FEATURE IMPORTANCE ===") feature_importance = pd.DataFrame({ 'feature': feature_names, 'importance': rf_model.feature_importances_ }).sort_values('importance', ascending=False) print(feature_importance) # Visualisatie feature importance plt.figure(figsize=(10, 6)) plt.barh(feature_importance['feature'], feature_importance['importance']) plt.title('Feature Importance - Random Forest') plt.xlabel('Importance') plt.show() # 6. CROSS-VALIDATIE (optioneel maar aanbevolen) from sklearn.model_selection import cross_val_score cv_scores = cross_val_score(rf_model, X_train_scaled, y_train, cv=5) print(f"\nCross-Validation Scores: {cv_scores}") print(f"Gemiddelde CV Score: {cv_scores.mean():.4f} (+/- {cv_scores.std()*2:.4f})") ``` ## Bibliotheken Uitleg: ### **scikit-learn** (aanbevolen voor dit project): - **Gebruik**: `from sklearn.ensemble import RandomForestClassifier` - **Voordelen**: Eenvoudig, uitgebreide documentatie, perfect voor traditionele ML - **Installatie**: `pip install scikit-learn` ### **TensorFlow**: ```python # Voorbeeld met TensorFlow/Keras import tensorflow as tf from tensorflow import keras model = keras.Sequential([ keras.layers.Dense(64, activation='relu', input_shape=(4,)), keras.layers.Dense(32, activation='relu'), keras.layers.Dense(3, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) ``` ### **PyTorch**: ```python # Voorbeeld met PyTorch import torch import torch.nn as nn import torch.optim as optim class IrisNet(nn.Module): def __init__(self): super(IrisNet, self).__init__() self.fc1 = nn.Linear(4, 64) self.fc2 = nn.Linear(64, 32) self.fc3 = nn.Linear(32, 3) def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) return self.fc3(x) ``` ## Aanbevelingen: 1. **Start met scikit-learn** - meest geschikt voor dit project 2. **TensorFlow/PyTorch** zijn beter voor complexe deep learning projecten 3. **Altijd data preprocessing** doen (scaling, missing values) 4. **Gebruik cross-validatie** voor betrouwbaardere resultaten ## Installatie commando's: ```bash pip install pandas numpy scikit-learn matplotlib seaborn # Optioneel: pip install tensorflow pip install torch ``` Dit script geeft je een complete pipeline van data loading tot model evaluatie met gedetailleerde prestatiemetrics!