The prediction API allows you to integrate the fake news detector into your Python applications. This guide demonstrates how to load the trained model and vectorizer, preprocess text, and generate predictions.
Load the pre-trained model and TF-IDF vectorizer from disk:
try: modelo = joblib.load('modelo_fake_news.pkl') vectorizer = joblib.load('vectorizer_tfidf.pkl') stop_words = set(stopwords.words("english")) print("Modelos cargados exitosamente. Listo para clasificar. ✅")except FileNotFoundError: print("Error: Los archivos .pkl no se encontraron.") print("Asegúrate de ejecutar 'fake_news_ia.py' primero.") sys.exit()
Make sure you have the modelo_fake_news.pkl and vectorizer_tfidf.pkl files in your working directory. These are generated by training the model first.
3
Define Text Preprocessing Function
The limpiar_texto function must be identical to the one used during training:
def limpiar_texto(texto): # 1. Remove metadata/source (e.g., WASHINGTON (REUTERS) - ) texto = re.sub(r'([A-Z\s]+)\s*\((REUTERS|AP|AFP)\)\s*\-\s*', '', str(texto), flags=re.IGNORECASE) # 2. Convert to lowercase texto = str(texto).lower() # 3. Remove punctuation, numbers, and special characters texto = re.sub(r'[^a-z\s]', '', texto) # 4. Tokenize with split() tokens = texto.split() # 5. Filter stopwords and single-letter tokens tokens = [t for t in tokens if t not in stop_words and len(t) > 1] return " ".join(tokens)
The preprocessing function must match the training pipeline exactly to ensure consistent results.
4
Make a Prediction
Process and classify a single news article:
# Example news articlenoticia = "The Federal Reserve announced on Wednesday that it will maintain the benchmark interest rate within the current range of 5.25% to 5.50%, citing steady economic growth and easing inflation."# 1. Clean the textnoticia_limpia = limpiar_texto(noticia)# 2. Vectorize the text using the trained vectorizernoticia_vec = vectorizer.transform([noticia_limpia])# 3. Make predictionprediccion = modelo.predict(noticia_vec)[0]# 4. Display resultprint(f"Predicción: {prediccion.upper()}")