Untitled
unknown
plain_text
2 years ago
1.5 kB
7
Indexable
import scipy.odr as o import pandas as pd import matplotlib.pyplot as plt import numpy as np def r_squared(y_true, y_pred): mean_y = np.mean(y_true) ss_total = np.sum((y_true - mean_y) ** 2) ss_residual = np.sum((y_true - y_pred) ** 2) r2 = 1 - (ss_residual / ss_total) return r2 exceldata = r'C:\Users\AhmadJami\Desktop\Neuer Ordner\Test - Kopie.xlsx' data_full = pd.read_excel(exceldata) # Work with the subset of data starting from row 13 data = data_full.iloc[12:].copy() x = data["Messzeitpunkt"] y = data["Wert"] xy = o.Data(x, y) r2_list = {} for n in range(len(x)): model = o.polynomial(n) odr_obj = o.ODR(xy, model) output = odr_obj.run() poly = np.poly1d(output.beta[::-1]) poly_y = poly(x) r2 = r_squared(y, poly_y) r2_list[n] = [r2, output] key_max = max(r2_list, key=lambda k: r2_list[k][0]) poly = np.poly1d(r2_list[key_max][1].beta[::-1]) poly_y = poly(x) plt.plot(x, y, label="input data") plt.plot(x, poly_y, label="polynomial ODR") plt.title(key_max) plt.legend() plt.show() koeff_list = np.polyfit(x, y, key_max)[::-1] func_str = "f(x) = " for i in range(0, key_max + 1): if i == key_max: func_str = func_str + str(koeff_list[i]) else: func_str = func_str + str(koeff_list[i]) + "x^{" + str(key_max - i) + "} + " print(func_str) # Write the entire DataFrame (including the first 12 rows) back to Excel data_full.to_excel(exceldata, index=False)
Editor is loading...
Leave a Comment