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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Untitled20.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colaboratory.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1XZbCNfIzuxHNNECK_uGluXC65NH9yulc
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
def greet(name):
|
| 11 |
+
return "Hello " + name + "!"
|
| 12 |
+
|
| 13 |
+
greet("World")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
import gradio
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
from sklearn.decomposition import PCA
|
| 25 |
+
from sklearn.preprocessing import StandardScaler
|
| 26 |
+
from sklearn.pipeline import Pipeline
|
| 27 |
+
|
| 28 |
+
import multiprocessing as mp
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
#catboost
|
| 33 |
+
from catboost import Pool, CatBoostRegressor
|
| 34 |
+
|
| 35 |
+
modelos_cargados = []
|
| 36 |
+
for i in range(3):
|
| 37 |
+
model = CatBoostRegressor()
|
| 38 |
+
model.load_model(f'./model_{i}.cbm')
|
| 39 |
+
modelos_cargados.append(model)
|
| 40 |
+
|
| 41 |
+
def load_npz_file(filepath,
|
| 42 |
+
masked = True,
|
| 43 |
+
pad_mask = True):
|
| 44 |
+
'''load in numpy zipped files. Use masked =True to mask masked values (pad with 0's)'''
|
| 45 |
+
with np.load(filepath) as npz:
|
| 46 |
+
arr = np.ma.MaskedArray(**npz)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if masked == True:
|
| 50 |
+
if pad_mask : # pad masked pixels with 0's to preserve shape
|
| 51 |
+
mask = arr.mask
|
| 52 |
+
return np.where(mask==True,0,arr.data)
|
| 53 |
+
|
| 54 |
+
return arr
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
return arr.data
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def load_and_reshape(filepath):
|
| 61 |
+
'''load and reshape array'''
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
#load array
|
| 65 |
+
arr = load_npz_file(filepath,
|
| 66 |
+
masked=False,
|
| 67 |
+
pad_mask=False)
|
| 68 |
+
|
| 69 |
+
depth,height,width = arr.shape
|
| 70 |
+
|
| 71 |
+
# reshape to depth last format
|
| 72 |
+
arr = arr.reshape((height,width,depth))
|
| 73 |
+
|
| 74 |
+
#scale values
|
| 75 |
+
# arr = arr / scaling_values
|
| 76 |
+
|
| 77 |
+
#resize
|
| 78 |
+
# arr = cv2.resize(arr,CFG.img_size)
|
| 79 |
+
|
| 80 |
+
return arr
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def get_array_properties(arr):
|
| 84 |
+
'''get reduced properties for array with shape (h,w,channels==150)'''
|
| 85 |
+
|
| 86 |
+
#area of array
|
| 87 |
+
area_arr = arr[:,:,0].size
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
#max min range
|
| 91 |
+
arr_max = arr.max(axis=(0,1))
|
| 92 |
+
arr_range = arr_max - arr.min(axis=(0,1))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
#central tendencies
|
| 97 |
+
mean_arr = arr.mean(axis=(0,1))
|
| 98 |
+
std_arr = arr.std(axis=(0,1))
|
| 99 |
+
|
| 100 |
+
median_arr = np.median(arr,axis=(0,1))
|
| 101 |
+
|
| 102 |
+
#first 25 %
|
| 103 |
+
q1 = np.percentile(a=arr,q=25,axis=(0,1))
|
| 104 |
+
#last 25 %
|
| 105 |
+
q3 = np.percentile(a=arr,q=75,axis=(0,1))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
#iqr
|
| 109 |
+
iqr = q3 - q1
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
#first 10
|
| 114 |
+
d1 = np.percentile(a=arr,q=10,axis=(0,1))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
#last 10
|
| 118 |
+
d10 = np.percentile(a=arr,q=90,axis=(0,1))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
return np.array((area_arr,*mean_arr,*std_arr,*median_arr,*q1,*q3,*arr_max,*arr_range,*d1,*d10,*iqr))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def get_agg_properties(filepath):
|
| 127 |
+
arr = load_and_reshape(filepath)
|
| 128 |
+
|
| 129 |
+
# properties of each band(range of each band)
|
| 130 |
+
|
| 131 |
+
properties = get_array_properties(arr)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
return properties
|
| 135 |
+
|
| 136 |
+
array_cols = ['array_area',
|
| 137 |
+
*[f'mean_{i}' for i in range(1,151)],
|
| 138 |
+
*[f'std_{i}' for i in range(1,151)],
|
| 139 |
+
*[f'med_{i}' for i in range(1,151)],
|
| 140 |
+
*[f'q1_{i}' for i in range(1,151)],
|
| 141 |
+
*[f'q3_{i}' for i in range(1,151)],
|
| 142 |
+
*[f'max_{i}' for i in range(1,151)],
|
| 143 |
+
*[f'range_{i}' for i in range(1,151)],
|
| 144 |
+
*[f'D1_{i}' for i in range(1,151)],
|
| 145 |
+
*[f'D10_{i}' for i in range(1,151)],
|
| 146 |
+
*[f'IQR_{i}' for i in range(1,151)]]
|
| 147 |
+
|
| 148 |
+
print(array_cols)
|
| 149 |
+
|
| 150 |
+
def pca_on_band(df, band_num, n_components=2):
|
| 151 |
+
"""
|
| 152 |
+
get pca features for a particular band
|
| 153 |
+
"""
|
| 154 |
+
pca_pipe = Pipeline(steps=[('standard_scaler', StandardScaler()),
|
| 155 |
+
('pca', PCA(n_components=min(n_components, df.shape[0])))])
|
| 156 |
+
|
| 157 |
+
band_cols = [col for col in df.columns if str(band_num) in col]
|
| 158 |
+
# Si solo hay una muestra, no realizar PCA y en su lugar devolver la muestra despu茅s del escalado
|
| 159 |
+
if df.shape[0] == 1:
|
| 160 |
+
scaler = StandardScaler()
|
| 161 |
+
scaled_features = scaler.fit_transform(df[band_cols])
|
| 162 |
+
return pd.DataFrame(scaled_features,
|
| 163 |
+
columns=[f'B{band_num}_PC{i+1}' for i in range(scaled_features.shape[1])])
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
pca_pipe.fit(df[band_cols])
|
| 168 |
+
features = pca_pipe.transform(df[band_cols])
|
| 169 |
+
|
| 170 |
+
return pd.DataFrame(features,
|
| 171 |
+
columns=[f'B{band_num}_PC{i+1}' for i in range(n_components)])
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def get_pca_dataset(df):
|
| 175 |
+
|
| 176 |
+
all_df = []
|
| 177 |
+
|
| 178 |
+
for band in range(1,151):
|
| 179 |
+
band_pca = pca_on_band(df,band)
|
| 180 |
+
|
| 181 |
+
all_df.append(band_pca)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
return pd.concat(objs=all_df, axis=1, join='outer', ignore_index=False)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
derived_cols = ['array_area',*[f'q1_{i}' for i in range(1,151)],*[f'q3_{i}' for i in range(1,151)]]
|
| 190 |
+
|
| 191 |
+
def predecir_desde_archivo_npz(ruta_archivo_npz, modelos, array_cols, derived_cols):
|
| 192 |
+
"""
|
| 193 |
+
Carga un archivo .npz, procesa los datos y utiliza los modelos para predecir los valores.
|
| 194 |
+
|
| 195 |
+
:param ruta_archivo_npz: String con la ruta al archivo .npz.
|
| 196 |
+
:param modelos: Lista de modelos entrenados para hacer las predicciones.
|
| 197 |
+
:param array_cols: Columnas esperadas despu茅s de obtener las propiedades agregadas.
|
| 198 |
+
:param derived_cols: Columnas derivadas que se usan junto con PCA para la entrada del modelo.
|
| 199 |
+
:return: Predicci贸n para el archivo dado.
|
| 200 |
+
"""
|
| 201 |
+
# Cargar y procesar los datos del archivo .npz
|
| 202 |
+
propiedades_agregadas = get_agg_properties(ruta_archivo_npz)
|
| 203 |
+
datos_df = pd.DataFrame([propiedades_agregadas], columns=array_cols)
|
| 204 |
+
|
| 205 |
+
print(datos_df)
|
| 206 |
+
|
| 207 |
+
# Aplicar PCA a los datos procesados
|
| 208 |
+
pca_datos = get_pca_dataset(datos_df)
|
| 209 |
+
|
| 210 |
+
# Combinar con las columnas derivadas
|
| 211 |
+
datos_finales = pca_datos.merge(datos_df[derived_cols], left_index=True, right_index=True)
|
| 212 |
+
|
| 213 |
+
# Realizar predicciones con los modelos
|
| 214 |
+
predicciones = [modelo.predict(datos_finales) for modelo in modelos]
|
| 215 |
+
predicciones = np.array(predicciones).reshape(len(modelos), -1)
|
| 216 |
+
|
| 217 |
+
# Calcular la mediana de las predicciones
|
| 218 |
+
mediana_predicciones = np.median(predicciones, axis=0)
|
| 219 |
+
return mediana_predicciones
|
| 220 |
+
|
| 221 |
+
# Aqu铆 asumimos que `array_cols` y `derived_cols` ya est谩n definidos en tu entorno como se ve en tu c贸digo.
|
| 222 |
+
# Tambi茅n asumimos que los modelos ya est谩n entrenados y contenidos en la lista `modelos`.
|
| 223 |
+
|
| 224 |
+
ruta_archivo_npz = "./1.npz" # Sustituir con la ruta real al archivo .npz
|
| 225 |
+
prediccion = predecir_desde_archivo_npz(ruta_archivo_npz, modelos_cargados, array_cols, derived_cols)
|
| 226 |
+
if len(prediccion) == 4:
|
| 227 |
+
fosforo_predicho, potasio_predicho, magnesio_predicho, pH_predicho = prediccion
|
| 228 |
+
print(f"F贸sforo Predicho: {fosforo_predicho}")
|
| 229 |
+
print(f"Potasio Predicho: {potasio_predicho}")
|
| 230 |
+
print(f"Magnesio Predicho: {magnesio_predicho}")
|
| 231 |
+
print(f"pH Predicho: {pH_predicho}")
|
| 232 |
+
else:
|
| 233 |
+
print("La predicci贸n no contiene el n煤mero esperado de componentes.")
|
| 234 |
+
|
| 235 |
+
import gradio as gr
|
| 236 |
+
|
| 237 |
+
# Aseg煤rate de que las funciones de predicci贸n y carga de modelos est茅n definidas aqu铆 o est茅n siendo importadas correctamente.
|
| 238 |
+
|
| 239 |
+
# Supongamos que la funci贸n 'predecir_desde_archivo_npz' est谩 definida correctamente y funciona.
|
| 240 |
+
# Tambi茅n asumimos que 'modelos_cargados' es una lista de modelos CatBoost ya cargados.
|
| 241 |
+
|
| 242 |
+
def predecir_desde_archivo_npz_interface(archivo):
|
| 243 |
+
# Gradio pasa el archivo cargado como un objeto temporal, que puedes leer directamente
|
| 244 |
+
datos = archivo
|
| 245 |
+
# Asumimos que tus funciones de procesamiento esperan recibir un array numpy y devuelven las predicciones como un array
|
| 246 |
+
predicciones = predecir_desde_archivo_npz(datos, modelos_cargados, array_cols, derived_cols)
|
| 247 |
+
return {
|
| 248 |
+
'F贸sforo (P)': float(predicciones[0]),
|
| 249 |
+
'Potasio (K)': float(predicciones[1]),
|
| 250 |
+
'Magnesio (Mg)': float(predicciones[2]),
|
| 251 |
+
'pH': float(predicciones[3])
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
demo = gr.Interface(
|
| 255 |
+
fn=predecir_desde_archivo_npz_interface,
|
| 256 |
+
inputs=gr.File(label="Sube tu archivo NPZ",file_types = [".npz"]
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
),
|
| 260 |
+
outputs=gr.JSON(label="Predicciones", )
|
| 261 |
+
)
|
| 262 |
+
demo.launch(
|
| 263 |
+
share=True
|
| 264 |
+
)
|