import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#url = 'https://raw.githubusercontent.com/allanspadini/numpy/dados/citrus.csv'
dados = np.loadtxt('citrus.csv', delimiter=',',usecols=np.arange(1,6,1),skiprows=1)
dl = dados[:5000,0]
pl = dados[:5000,1]
dt = dados[5000:, 0]
pt = dados[5000:,1]
def calcular_r2(y_real, y_pred):
ss_res = np.sum((y_real - y_pred)**2)
ss_tot = np.sum((y_real - np.mean(y_real))**2)
return 1 - (ss_res / ss_tot)
def ajuste_linear(x_array, y_array, nome_fruta='Fruta', cor='blue'):
# Coeficientes da reta de regressão
m = (np.sum(x_array * y_array) - (np.sum(x_array) * np.sum(y_array) / np.size(y_array))) / \
(np.sum(x_array**2) - (np.sum(x_array)**2) / np.size(x_array))
b = np.mean(y_array) - m * np.mean(x_array)
# Previsão e R²
y_pred = m * x_array + b
r2 = calcular_r2(y_array, y_pred)
# Gráfico
x_plot = np.linspace(np.min(x_array), np.max(x_array), 100)
y_plot = m * x_plot + b
plt.scatter(x_array, y_array, s=10, alpha=0.5, label=f'Dados - {nome_fruta}', color=cor)
plt.plot(x_plot, y_plot, color='black', label=f'Ajuste Linear - {nome_fruta}')
plt.text(np.min(x_array), np.max(y_array), f'$R^2$ = {r2:.3f}', color='black')
plt.xlabel('Diâmetro')
plt.ylabel('Peso')
plt.title(f'Ajuste Linear - {nome_fruta}')
plt.legend()
plt.grid(True)
plt.show()
# Exibir coeficientes
print(f'{nome_fruta} - Coeficiente angular (m): {m:.3f}')
print(f'{nome_fruta} - Intercepto (b): {b:.3f}')
print(f'{nome_fruta} - R²: {r2:.3f}')
# Chamar a função para cada conjunto
ajuste_linear(dl, pl, nome_fruta='Laranja', cor='orange')
ajuste_linear(dt, pt, nome_fruta='Toranja', cor='red')