SQL y Bases de Datos — Curso Completo
Análisis de Datos con Python — Curso Profesional
Python Fundamentals
Machine Learning with Python
Django Web Development
IA (Inteligencia Artificial)
La IA permite que las maquinas realicen tareas que normalmente requieren inteligencia humana, como clasificacion y prediccion.
# Simple threshold classifier
loans = [1200, 3400, 900, 5100, 2200]
threshold = 2500
labels = ["high" if x >= threshold else "low" for x in loans]
print("Loans:", loans)
print("Risk labels:", labels)
Paso a paso
Define a rule and a threshold.
Compute one label per observation.
Compare output labels with your expected risk classes.
This is a deterministic classifier baseline before neural models.
Un LLM es un modelo de lenguaje entrenado con grandes volumenes de texto para generar, resumir y transformar contenido.
# Tiny toy language model with bigram counts
text = "ai helps teams make better decisions with data"
words = text.split()
bigrams = {}
for i in range(len(words) - 1):
pair = (words[i], words[i + 1])
bigrams[pair] = bigrams.get(pair, 0) + 1
print("Bigrams:")
for pair, count in sorted(bigrams.items()):
print(f"{pair}: {count}")
Paso a paso
Split text into tokens.
Count each adjacent token pair.
Use counts to estimate next-word likelihood.
This is the conceptual bridge to autoregressive LLM decoding.
Ejemplo simple con capas lineales para ver tensores de entrada y salida.
# Minimal PyTorch forward pass
try:
import torch
except Exception as e:
print("PyTorch not available:", e)
else:
torch.manual_seed(0)
x = torch.randn(4, 3)
model = torch.nn.Sequential(
torch.nn.Linear(3, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 1),
)
y = model(x)
print("Input shape:", tuple(x.shape))
print("Output shape:", tuple(y.shape))
print("First output:", float(y[0, 0]))
Paso a paso
Create input tensor x with shape [batch, features].
Apply linear layer, non-linearity, then output layer.
Inspect output shape and first prediction value.
Matematica detras
y = W2 * ReLU(W1 * x + b1) + b2
Salida esperada:
Input shape: (4, 3)
Output shape: (4, 1)
First output: valor numerico
TensorFlow (Keras minimo)
Ejemplo Sequential sencillo para entender inferencia por lotes.
# Minimal TensorFlow/Keras forward pass
try:
import tensorflow as tf
except Exception as e:
print("TensorFlow not available:", e)
else:
tf.random.set_seed(0)
x = tf.random.normal((4, 3))
model = tf.keras.Sequential([
tf.keras.layers.Dense(4, activation="relu"),
tf.keras.layers.Dense(1),
])
y = model(x)
print("Input shape:", x.shape)
print("Output shape:", y.shape)
print("First output:", float(y[0, 0]))
Paso a paso
Build a Sequential model with Dense layers.
Feed batch tensor and run forward inference.
Read tensor shape and sample output.
Matematica detras
Dense(x) = activation(x * W + b)
Salida esperada:
Input shape: (4, 3)
Output shape: (4, 1)
First output: valor numerico
Mini LLM pedagogico
Modelo de lenguaje muy pequeno (bigramas) para ensenar tokens, logits y probabilidades.
# Tiny LLM teaching model (char-level bigram logits)
try:
import torch
except Exception as e:
print("PyTorch not available:", e)
else:
text = "hello llm"
vocab = sorted(set(text))
stoi = {c: i for i, c in enumerate(vocab)}
itos = {i: c for c, i in stoi.items()}
ids = torch.tensor([stoi[c] for c in text], dtype=torch.long)
model = torch.nn.Embedding(len(vocab), len(vocab))
logits = model(ids)
probs = torch.softmax(logits[-1], dim=-1)
top_p, top_i = torch.topk(probs, k=min(3, len(vocab)))
print("Vocab:", vocab)
print("Last input token:", repr(itos[int(ids[-1])]))
print("Top next-token probabilities:")
for p, i in zip(top_p, top_i):
print(itos[int(i)], round(float(p), 4))
Paso a paso
Build a character vocabulary and token IDs.
Use embedding table as learnable logits producer.
Apply softmax and read top-k next-token probabilities.
Matematica detras
p(next) = softmax(logits_last_token)
Salida esperada:
Vocab: [...]
Last input token: ...
Top next-token probabilities: 3 lineas token-probabilidad
RAG (Retrieval-Augmented Generation)
RAG combina recuperacion de contexto + generacion para respuestas mas precisas y auditables.
# Tiny RAG demo (keyword overlap retrieval + prompt assembly)
docs = [
"LGPD requires lawful basis, consent management, and data subject rights.",
"Dedicated AI servers provide tenant isolation and private GPU workloads.",
"RAG improves answer grounding by injecting retrieved context into prompts.",
]
query = "How to run AI servers with LGPD compliance?"
q_terms = set(w.strip('.,!?').lower() for w in query.split())
scored = []
for d in docs:
d_terms = set(w.strip('.,!?').lower() for w in d.split())
score = len(q_terms & d_terms)
scored.append((score, d))
scored.sort(reverse=True, key=lambda x: x[0])
top_doc = scored[0][1]
prompt = f"Question: {query}\nContext: {top_doc}\nAnswer:"
print("Query:", query)
print("Top document:", top_doc)
print("Prompt preview:", prompt[:120] + "...")
Paso a paso
1) Indexa una pequena base de conocimiento (documentos).
2) Recupera el mejor contexto para la consulta.
3) Construye el prompt final con pregunta + contexto recuperado.