Este guia ajuda a resolver problemas comuns ao trabalhar com o currículo de Machine Learning para Iniciantes. Se não encontrar uma solução aqui, consulte as nossas Discussões no Discord ou abra um problema.
- Problemas de Instalação
- Problemas com o Jupyter Notebook
- Problemas com Pacotes Python
- Problemas com o Ambiente R
- Problemas com a Aplicação de Questionários
- Problemas com Dados e Caminhos de Ficheiros
- Mensagens de Erro Comuns
- Problemas de Desempenho
- Ambiente e Configuração
Problema: python: command not found
Solução:
- Instale o Python 3.8 ou superior a partir de python.org
- Verifique a instalação:
python --versionoupython3 --version - No macOS/Linux, pode ser necessário usar
python3em vez depython
Problema: Múltiplas versões do Python a causar conflitos
Solução:
# Use virtual environments to isolate projects
python -m venv ml-env
# Activate virtual environment
# On Windows:
ml-env\Scripts\activate
# On macOS/Linux:
source ml-env/bin/activateProblema: jupyter: command not found
Solução:
# Install Jupyter
pip install jupyter
# Or with pip3
pip3 install jupyter
# Verify installation
jupyter --versionProblema: O Jupyter não abre no navegador
Solução:
# Try specifying the browser
jupyter notebook --browser=chrome
# Or copy the URL with token from terminal and paste in browser manually
# Look for: http://localhost:8888/?token=...Problema: Os pacotes R não instalam
Solução:
# Ensure you have the latest R version
# Install packages with dependencies
install.packages(c("tidyverse", "tidymodels", "caret"), dependencies = TRUE)
# If compilation fails, try installing binary versions
install.packages("package-name", type = "binary")Problema: IRkernel não está disponível no Jupyter
Solução:
# In R console
install.packages('IRkernel')
IRkernel::installspec(user = TRUE)Problema: O kernel continua a falhar ou reiniciar
Solução:
- Reinicie o kernel:
Kernel → Restart - Limpe a saída e reinicie:
Kernel → Restart & Clear Output - Verifique problemas de memória (consulte Problemas de Desempenho)
- Tente executar as células individualmente para identificar o código problemático
Problema: Kernel Python errado selecionado
Solução:
- Verifique o kernel atual:
Kernel → Change Kernel - Selecione a versão correta do Python
- Se o kernel estiver ausente, crie-o:
python -m ipykernel install --user --name=ml-envProblema: O kernel não inicia
Solução:
# Reinstall ipykernel
pip uninstall ipykernel
pip install ipykernel
# Register the kernel again
python -m ipykernel install --userProblema: As células estão a executar, mas não mostram saída
Solução:
- Verifique se a célula ainda está a executar (procure o indicador
[*]) - Reinicie o kernel e execute todas as células:
Kernel → Restart & Run All - Verifique o console do navegador para erros de JavaScript (F12)
Problema: Não é possível executar células - sem resposta ao clicar em "Run"
Solução:
- Verifique se o servidor Jupyter ainda está a executar no terminal
- Atualize a página do navegador
- Feche e reabra o notebook
- Reinicie o servidor Jupyter
Problema: ModuleNotFoundError: No module named 'sklearn'
Solução:
pip install scikit-learn
# Common ML packages for this course
pip install scikit-learn pandas numpy matplotlib seabornProblema: ImportError: cannot import name 'X' from 'sklearn'
Solução:
# Update scikit-learn to latest version
pip install --upgrade scikit-learn
# Check version
python -c "import sklearn; print(sklearn.__version__)"Problema: Erros de incompatibilidade de versão de pacotes
Solução:
# Create a new virtual environment
python -m venv fresh-env
source fresh-env/bin/activate # or fresh-env\Scripts\activate on Windows
# Install packages fresh
pip install jupyter scikit-learn pandas numpy matplotlib seaborn
# If specific version needed
pip install scikit-learn==1.3.0Problema: pip install falha com erros de permissão
Solução:
# Install for current user only
pip install --user package-name
# Or use virtual environment (recommended)
python -m venv venv
source venv/bin/activate
pip install package-nameProblema: FileNotFoundError ao carregar ficheiros CSV
Solução:
import os
# Check current working directory
print(os.getcwd())
# Use relative paths from notebook location
df = pd.read_csv('../../data/filename.csv')
# Or use absolute paths
df = pd.read_csv('/full/path/to/data/filename.csv')Problema: A instalação de pacotes falha com erros de compilação
Solução:
# Install binary version (Windows/macOS)
install.packages("package-name", type = "binary")
# Update R to latest version if packages require it
# Check R version
R.version.string
# Install system dependencies (Linux)
# For Ubuntu/Debian, in terminal:
# sudo apt-get install r-base-devProblema: tidyverse não instala
Solução:
# Install dependencies first
install.packages(c("rlang", "vctrs", "pillar"))
# Then install tidyverse
install.packages("tidyverse")
# Or install components individually
install.packages(c("dplyr", "ggplot2", "tidyr", "readr"))Problema: O RMarkdown não renderiza
Solução:
# Install/update rmarkdown
install.packages("rmarkdown")
# Install pandoc if needed
install.packages("pandoc")
# For PDF output, install tinytex
install.packages("tinytex")
tinytex::install_tinytex()Problema: npm install falha
Solução:
# Clear npm cache
npm cache clean --force
# Remove node_modules and package-lock.json
rm -rf node_modules package-lock.json
# Reinstall
npm install
# If still fails, try with legacy peer deps
npm install --legacy-peer-depsProblema: Porta 8080 já está em uso
Solução:
# Use different port
npm run serve -- --port 8081
# Or find and kill process using port 8080
# On Linux/macOS:
lsof -ti:8080 | xargs kill -9
# On Windows:
netstat -ano | findstr :8080
taskkill /PID <PID> /FProblema: npm run build falha
Solução:
# Check Node.js version (should be 14+)
node --version
# Update Node.js if needed
# Then clean install
rm -rf node_modules package-lock.json
npm install
npm run buildProblema: Erros de linting impedem a construção
Solução:
# Fix auto-fixable issues
npm run lint -- --fix
# Or temporarily disable linting in build
# (not recommended for production)Problema: Ficheiros de dados não encontrados ao executar notebooks
Solução:
-
Execute sempre os notebooks a partir do diretório onde estão localizados
cd /path/to/lesson/folder jupyter notebook -
Verifique os caminhos relativos no código
# Correct path from notebook location df = pd.read_csv('../data/filename.csv') # Not from your terminal location
-
Use caminhos absolutos, se necessário
import os base_path = os.path.dirname(os.path.abspath(__file__)) data_path = os.path.join(base_path, 'data', 'filename.csv')
Problema: Ficheiros de conjuntos de dados estão em falta
Solução:
- Verifique se os dados deveriam estar no repositório - a maioria dos conjuntos de dados está incluída
- Algumas lições podem exigir o download de dados - consulte o README da lição
- Certifique-se de que puxou as alterações mais recentes:
git pull origin main
Erro: MemoryError ou kernel falha ao processar dados
Solução:
# Load data in chunks
for chunk in pd.read_csv('large_file.csv', chunksize=10000):
process(chunk)
# Or read only needed columns
df = pd.read_csv('file.csv', usecols=['col1', 'col2'])
# Free memory when done
del large_dataframe
import gc
gc.collect()Aviso: ConvergenceWarning: Maximum number of iterations reached
Solução:
from sklearn.linear_model import LogisticRegression
# Increase max iterations
model = LogisticRegression(max_iter=1000)
# Or scale your features first
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)Problema: Gráficos não aparecem no Jupyter
Solução:
# Enable inline plotting
%matplotlib inline
# Import pyplot
import matplotlib.pyplot as plt
# Show plot explicitly
plt.plot(data)
plt.show()Problema: Gráficos do Seaborn aparecem diferentes ou geram erros
Solução:
import warnings
warnings.filterwarnings('ignore', category=UserWarning)
# Update to compatible version
# pip install --upgrade seaborn matplotlibProblema: UnicodeDecodeError ao ler ficheiros
Solução:
# Specify encoding explicitly
df = pd.read_csv('file.csv', encoding='utf-8')
# Or try different encoding
df = pd.read_csv('file.csv', encoding='latin-1')
# For errors='ignore' to skip problematic characters
df = pd.read_csv('file.csv', encoding='utf-8', errors='ignore')Problema: Notebooks muito lentos para executar
Solução:
- Reinicie o kernel para liberar memória:
Kernel → Restart - Feche notebooks não utilizados para liberar recursos
- Use amostras de dados menores para testes:
# Work with subset during development df_sample = df.sample(n=1000)
- Faça o perfil do seu código para encontrar gargalos:
%time operation() # Time single operation %timeit operation() # Time with multiple runs
Problema: Sistema a ficar sem memória
Solução:
# Check memory usage
df.info(memory_usage='deep')
# Optimize data types
df['column'] = df['column'].astype('int32') # Instead of int64
# Drop unnecessary columns
df = df[['col1', 'col2']] # Keep only needed columns
# Process in batches
for batch in np.array_split(df, 10):
process(batch)Problema: Ambiente virtual não ativa
Solução:
# Windows
python -m venv venv
venv\Scripts\activate.bat
# macOS/Linux
python3 -m venv venv
source venv/bin/activate
# Check if activated (should show venv name in prompt)
which python # Should point to venv pythonProblema: Pacotes instalados, mas não encontrados no notebook
Solução:
# Ensure notebook uses the correct kernel
# Install ipykernel in your venv
pip install ipykernel
python -m ipykernel install --user --name=ml-env --display-name="Python (ml-env)"
# In Jupyter: Kernel → Change Kernel → Python (ml-env)Problema: Não é possível puxar as alterações mais recentes - conflitos de merge
Solução:
# Stash your changes
git stash
# Pull latest
git pull origin main
# Reapply your changes
git stash pop
# If conflicts, resolve manually or:
git checkout --theirs path/to/file # Take remote version
git checkout --ours path/to/file # Keep your versionProblema: Notebooks Jupyter não abrem no VS Code
Solução:
- Instale a extensão Python no VS Code
- Instale a extensão Jupyter no VS Code
- Selecione o interpretador Python correto:
Ctrl+Shift+P→ "Python: Select Interpreter" - Reinicie o VS Code
- Discussões no Discord: Faça perguntas e partilhe soluções no canal #ml-for-beginners
- Microsoft Learn: Módulos de ML para Iniciantes
- Tutoriais em Vídeo: Playlist no YouTube
- Rastreador de Problemas: Reporte bugs
Se tentou as soluções acima e ainda está a enfrentar problemas:
- Pesquise problemas existentes: GitHub Issues
- Verifique discussões no Discord: Discussões no Discord
- Abra um novo problema: Inclua:
- O seu sistema operativo e versão
- Versão do Python/R
- Mensagem de erro (stack trace completo)
- Passos para reproduzir o problema
- O que já tentou
Estamos aqui para ajudar! 🚀
Aviso Legal:
Este documento foi traduzido utilizando o serviço de tradução por IA Co-op Translator. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automáticas podem conter erros ou imprecisões. O documento original no seu idioma nativo deve ser considerado a fonte autoritativa. Para informações críticas, recomenda-se uma tradução profissional realizada por humanos. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações incorretas resultantes do uso desta tradução.