Могу ли я положиться на свою функцию и решили не использовать библиотечную функцию?
Код: Выделить всё
import matplotlib.pyplot as plt
def plot_gpx_segments(segments):
import matplotlib.pyplot as plt
if not segments:
return
for i, segment in enumerate(segments):
x = [point.time.timestamp() for point in segment]
y = calculate_segment_distances(segment,17.7055238932,83.2780107111)
xsum=0
x2sum=0
ysum=0
xysum=0
n=len(x)
for i in range(n):
xsum+=x[i]
ysum+=y[i]
x2sum+=x[i]**2
xysum+=x[i]*y[i]
numerator = (n*xysum-xsum*ysum)
deno= (n*x2sum-xsum**2)
if deno==0:
a=0;
else:
a=numerator/deno
numerator = (x2sum*ysum-xsum*xysum)
deno= (x2sum*n-xsum*xsum)
if deno==0:
b=0
else:
b=numerator/deno
if a > 0:
trend = "increasing"
elif a < 0:
trend = "decreasing"
else:
trend = "no change"
y_fit=[a*xn + b for xn in x]
plt.scatter(x, y, color='blue', label='Original Data')
plt.plot(x, y_fit, color='red', label='Regression Line')
plt.xlabel('Time')
plt.ylabel('Distance')
plt.title(f'Linear Regression ({trend} trend)')
plt.legend()
plt.show()
Код: Выделить всё
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
def plot_gpx_segments(segments):
import matplotlib.pyplot as plt
if not segments:
return
for i, segment in enumerate(segments):
segment_times = [point.time.timestamp() for point in segment]
segment_distances = calculate_segment_distances(segment,17.7055238932,83.2780107111)
X = np.array(segment_times).reshape(-1, 1)
y = np.array(segment_distances)
model = LinearRegression()
model.fit(X, y)
predicted_distances = model.predict(X)
print(predicted_distances)
if model.coef_[0] > 0:
trend = "increasing"
elif model.coef_[0] < 0:
trend = "decreasing"
else:
trend = "no change"
plt.scatter(X, y, color='blue', label='Original Data')
plt.plot(X, predicted_distances, color='red', label='Regression Line')
plt.xlabel('Time')
plt.ylabel('Distance')
plt.title(f'Linear Regression ({trend} trend)')
plt.legend()
plt.show()
предсказанный библиотекой результат: [508.03153852 508.03144674 508.03135496 508.02795913 508.02639889 508.02428797 508.02291128 508.0208 9214 508.01914834 508.01722098 508.0153854 508.01364159 508.01180601 508.01042933 508.0087773 508.0070335 508.00510614 508.00 336233 508.003087 508.00143497 507.99758025 507.99418442 507.99161461 507.98876946 507.9841805 507.98151891 507.9784902 ]
Результат ручного расчета: [514.2593975670461, 514.2593053745222, 514.2592131819692, 514.2558020579454, 514.2542347847484, 514.2521143 562917, 514.2507314681716, 514.2487032322679, 514.246951573994, 514.2450155306433, 514.2431716798164, 514.2414200215135, 514. 2395761706866, 514.2381932825956, 514.2365338168456, 514.2347821585718, 514.2328461151919, 514.2310944569181, 514.2308178792882, 514.2291584135382, 514.2252863268077, 514.22187 52027838, 514.2192938116495, 514.2164358428563, 514.2118262157892, 514.2091526321019, 514.2061102782609]
Смотрите рисунки ниже:


Подробнее здесь: https://stackoverflow.com/questions/781 ... ression-wi