import json
import os
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import cv2
# File to store user preferences
PREFERENCES_FILE = "json/user_preferences.json"
class AIModel:
def __init__(self):
self.model = RandomForestClassifier(n_estimators=100, random_state=42)
self.scaler = StandardScaler()
self.data = []
self.labels = []
self.load_preferences()
def load_preferences(self):
"""Load user preferences from a JSON file."""
if os.path.exists(PREFERENCES_FILE):
with open(PREFERENCES_FILE, "r", encoding="utf-8") as file:
try:
data = json.load(file)
self.data = data.get("features", [])
self.labels = data.get("labels", [])
except json.JSONDecodeError:
self.data, self.labels = [], []
def save_preferences(self):
"""Save user preferences to a JSON file."""
with open(PREFERENCES_FILE, "w", encoding="utf-8") as file:
json.dump({"features": self.data, "labels": self.labels}, file, indent=4)
def extract_features(self, image_path):
"""Extract image features using color histograms."""
image = cv2.imread(image_path)
if image is None:
return None
image = cv2.resize(image, (100, 100)) # Resize for consistency
hist = cv2.calcHist([image], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
return hist.flatten()
def train_model(self):
"""Train the AI model if there is enough data."""
if len(self.data) < 10: # Ensure enough data
return
X = np.array(self.data)
y = np.array(self.labels)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train = self.scaler.fit_transform(X_train)
X_test = self.scaler.transform(X_test)
self.model.fit(X_train, y_train)
def predict(self, image_path):
"""Predict the likelihood of an image being accepted as a percentage."""
features = self.extract_features(image_path)
if features is None or len(self.data) < 10:
return 0 # Default to neutral if no model is trained
scaled_features = self.scaler.transform([features])
# Get probability estimates from the model
if hasattr(self.model, "predict_proba"):
probability = self.model.predict_proba(scaled_features)[0][1] # Probability of class 1
return round(probability * 100, 2) # Convert to percentage (0-100)
# If model doesn't support predict_proba, fall back to a binary prediction
return 100 if self.model.predict(scaled_features)[0] == 1 else 0
def update_model(self, image_path, accepted):
"""Update the model with a new image decision."""
features = self.extract_features(image_path)
if features is not None:
self.data.append(features.tolist())
self.labels.append(1 if accepted else 0)
self.save_preferences()
self.train_model()
# Example usage
if __name__ == "__main__":
ai = AIModel()
ai.train_model()
test_image = "temp/example.jpg" # Replace with an actual image path
print(f"Predicted: {ai.predict(test_image)}")
Gracias por el aporte tio, la verdad que de IA se lo basico de lo basico, parto desde 0, por eso ando buscando algun "curso" o algo para aprender. Basicamente lo que me gustaria hacer es crear cuentas de influencers y tal con IAEspecifica un poco. Quieres generar imagenes, videos, entrenarlos, aprender a hacerlos, etc...
Si quieres entrenar una IA desde 0 quiero que sepas que lo jodido no es crearla, es entrenarla. Yo intenté entrenar una en python usando como base sklearn y costó muchiiisimo para que diera un resultado un poco acertado.
Te dejo por aquí el codigo por si te sirve, es basicamente para que identifique las imagenes que me gustan y las que no pero te aconsejo usarlo solo de referencia, si copias y pegas no vas a aprender. Está todo medio comentado.
Python:import json import os import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import cv2 # File to store user preferences PREFERENCES_FILE = "json/user_preferences.json" class AIModel: def __init__(self): self.model = RandomForestClassifier(n_estimators=100, random_state=42) self.scaler = StandardScaler() self.data = [] self.labels = [] self.load_preferences() def load_preferences(self): """Load user preferences from a JSON file.""" if os.path.exists(PREFERENCES_FILE): with open(PREFERENCES_FILE, "r", encoding="utf-8") as file: try: data = json.load(file) self.data = data.get("features", []) self.labels = data.get("labels", []) except json.JSONDecodeError: self.data, self.labels = [], [] def save_preferences(self): """Save user preferences to a JSON file.""" with open(PREFERENCES_FILE, "w", encoding="utf-8") as file: json.dump({"features": self.data, "labels": self.labels}, file, indent=4) def extract_features(self, image_path): """Extract image features using color histograms.""" image = cv2.imread(image_path) if image is None: return None image = cv2.resize(image, (100, 100)) # Resize for consistency hist = cv2.calcHist([image], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256]) return hist.flatten() def train_model(self): """Train the AI model if there is enough data.""" if len(self.data) < 10: # Ensure enough data return X = np.array(self.data) y = np.array(self.labels) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) X_train = self.scaler.fit_transform(X_train) X_test = self.scaler.transform(X_test) self.model.fit(X_train, y_train) def predict(self, image_path): """Predict the likelihood of an image being accepted as a percentage.""" features = self.extract_features(image_path) if features is None or len(self.data) < 10: return 0 # Default to neutral if no model is trained scaled_features = self.scaler.transform([features]) # Get probability estimates from the model if hasattr(self.model, "predict_proba"): probability = self.model.predict_proba(scaled_features)[0][1] # Probability of class 1 return round(probability * 100, 2) # Convert to percentage (0-100) # If model doesn't support predict_proba, fall back to a binary prediction return 100 if self.model.predict(scaled_features)[0] == 1 else 0 def update_model(self, image_path, accepted): """Update the model with a new image decision.""" features = self.extract_features(image_path) if features is not None: self.data.append(features.tolist()) self.labels.append(1 if accepted else 0) self.save_preferences() self.train_model() # Example usage if __name__ == "__main__": ai = AIModel() ai.train_model() test_image = "temp/example.jpg" # Replace with an actual image path print(f"Predicted: {ai.predict(test_image)}")
Eso es aprender IA? por favor jaja
Nada, pero lo que dice @Matamataos es cierto. Para aprender como funciona de verdad, le tienes que echar mucho tiempo. Y para lo que has dicho pues...Busca cualquier modelo que te guste para generar imagenes y ya.