import numpy as np
from urllib.request import urlopen
import matplotlib.pyplot as plt
# === Carregar dados ===
url = 'https://raw.githubusercontent.com/allanspadini/numpy/dados/citrus.csv'
dados = np.loadtxt(urlopen(url), delimiter=',', skiprows=1, usecols=[1, 2])
# === Interpolar NaNs se houver ===
def interpolar_nans(arr):
for j in range(arr.shape[1]):
col = arr[:, j]
nans = np.isnan(col)
if nans.any():
idx = np.arange(len(col))
col[nans] = np.interp(idx[nans], idx[~nans], col[~nans])
return arr
if np.isnan(dados).any():
dados = interpolar_nans(dados)
laranja_x = np.arange(5000)
laranja_y = dados[:5000, 0]
toranja_x = np.arange(5000)
toranja_y = dados[5000:, 0]
# === Ajuste polinomial grau 3 (fixo) ===
grau = 3
# Ajustar polinômios aos dados reais
coef_laranja = np.polyfit(laranja_x, laranja_y, grau)
coef_toranja = np.polyfit(toranja_x, toranja_y, grau)
# Gerar coeficientes aleatórios com seed 17 (se quiser para comparação)
np.random.seed(17)
coef_aleatorio_lar = np.random.rand(100)
coef_aleatorio_tor = np.random.rand(100)
# Função para projeção linear dos coeficientes
def projecao_linear(coef):
x = np.arange(len(coef))
a, b = np.polyfit(x, coef, 1)
proj = a * (len(coef)) + b
return a, b, proj
a_lar, b_lar, proj_lar = projecao_linear(coef_laranja)
a_tor, b_tor, proj_tor = projecao_linear(coef_toranja)
# Função para métricas de ajuste
def mse(y_true, y_pred):
return np.mean((y_true - y_pred)**2)
def r2_score(y_true, y_pred):
ss_res = np.sum((y_true - y_pred)**2)
ss_tot = np.sum((y_true - np.mean(y_true))**2)
return 1 - ss_res/ss_tot
# Previsão dos valores originais usando polinômios ajustados
poly_lar = np.poly1d(coef_laranja)
poly_tor = np.poly1d(coef_toranja)
laranja_pred = poly_lar(laranja_x)
toranja_pred = poly_tor(toranja_x)
# Calcular métricas reais
mse_lar = mse(laranja_y, laranja_pred)
r2_lar = r2_score(laranja_y, laranja_pred)
mse_tor = mse(toranja_y, toranja_pred)
r2_tor = r2_score(toranja_y, toranja_pred)
print(f'Laranja - MSE: {mse_lar:.4f}, R²: {r2_lar:.4f}')
print(f'Toranja - MSE: {mse_tor:.4f}, R²: {r2_tor:.4f}')
# Pegar os 3 maiores coeficientes em valor absoluto (mais relevantes)
top3_lar_idx = np.argsort(np.abs(coef_laranja))[-3:]
top3_tor_idx = np.argsort(np.abs(coef_toranja))[-3:]
# === Gráfico unificado ===
fig, ax1 = plt.subplots(figsize=(12, 7))
# Plot dados reais
ax1.plot(laranja_x, laranja_y, label='Laranja - Dados', color='blue')
ax1.plot(toranja_x, toranja_y, label='Toranja - Dados', color='green')
# Plot ajuste polinomial
ax1.plot(laranja_x, laranja_pred, linestyle='--', color='cyan', label='Laranja - Ajuste Grau 3')
ax1.plot(toranja_x, toranja_pred, linestyle='--', color='lime', label='Toranja - Ajuste Grau 3')
ax1.set_xlabel('Índice')
ax1.set_ylabel('Valores')
ax1.grid(True)
# Eixo y secundário para coeficientes
ax2 = ax1.twinx()
x_coef = np.arange(len(coef_laranja))
ax2.plot(x_coef, coef_laranja, color='orange', alpha=0.6, label='Coef. Laranja')
ax2.plot(x_coef, coef_toranja, color='darkgreen', alpha=0.6, label='Coef. Toranja')
# Destacar top 3 coeficientes
ax2.scatter(top3_lar_idx, coef_laranja[top3_lar_idx], color='red', s=100, edgecolors='black', label='Laranja - Top 3 Coef')
ax2.scatter(top3_tor_idx, coef_toranja[top3_tor_idx], color='darkred', s=100, edgecolors='black', label='Toranja - Top 3 Coef')
# Plot ajuste linear dos coeficientes
ax2.plot(x_coef, a_lar * x_coef + b_lar, linestyle='--', color='orange', alpha=0.8, label='Proj. Linear Laranja')
ax2.plot(x_coef, a_tor * x_coef + b_tor, linestyle='--', color='darkgreen', alpha=0.8, label='Proj. Linear Toranja')
# Plot projeções
ax2.scatter(len(coef_laranja), proj_lar, color='red', s=120, edgecolors='black', label='Projeção Laranja')
ax2.scatter(len(coef_toranja), proj_tor, color='darkred', s=120, edgecolors='black', label='Projeção Toranja')
ax2.set_ylabel('Coeficientes Polinomiais')
ax2.grid(False)
# Combinar legendas dos dois eixos
lines_1, labels_1 = ax1.get_legend_handles_labels()
lines_2, labels_2 = ax2.get_legend_handles_labels()
ax1.legend(lines_1 + lines_2, labels_1 + labels_2, loc='upper left', bbox_to_anchor=(1.05, 1))
fig.tight_layout()
plt.title('Análise de Ajuste Polinomial e Coeficientes - Laranja e Toranja')
plt.show()