import pandas as pd import numpy as np import os import tensorflow as tf from…
- User
import pandas as pd import numpy as np import os import tensorflow as tf from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score from sklearn.cluster import KMeans import matplotlib.pyplot as plt
etichette_disponibili = ["BA", "CA", "FI", "GE", "MI", "NA", "PA", "RM", "TO", "VE"]
etichetta_selezionata = input("Inserisci l'etichetta desiderata (es. BA, CA, FI, ...): ").upper()
if etichetta_selezionata.upper() not in map(str.upper, etichette_disponibili): print("Etichetta non valida. Inserisci un'etichetta valida.") else: file_path = 'c:/dati/storico.txt'
if os.path.exists(file_path): with open(file_path, 'r') as file: righe = [riga for riga in file.readlines() if riga.split()[1].upper() == etichetta_selezionata] num_estr_eliminate = int(input("A quante estrazioni dall'ultima disponibile vuoi limitare lo storico? ")) if num_estr_eliminate > 0: righe = righe[:-num_estr_eliminate] data = [] for riga in righe: parti = riga.split() dizionario = { 'Data': pd.to_datetime(parti[0]), 'Giorno': pd.to_datetime(parti[0]).day, 'Mese': pd.to_datetime(parti[0]).month, 'Anno': pd.to_datetime(parti[0]).year, 'Ruota': 'RM' if parti[1].upper() == 'RO' else parti[1], '1 Estratto': int(parti[2]), '2 Estratto': int(parti[3]), '3 Estratto': int(parti[4]), '4 Estratto': int(parti[5]), '5 Estratto': int(parti[6]) } data.append(dizionario) df = pd.DataFrame(data) print(df) numerical_data = df.iloc[:, 5:].values # Utilizza tutte le colonne dalla 6ª in poi (considerando la 1ª colonna come 0) kmeans = KMeans(n_clusters=3) cluster_labels = kmeans.fit_predict(numerical_data) df['Cluster'] = cluster_labels print(df) df.info() print(df.head()) cluster_labels = df['Cluster'].values X_train_with_clusters, y_train = [], [] for i in range(len(train_data) - sequence_length): X_train_with_clusters.append(np.concatenate([train_data[i:i + sequence_length], cluster_labels[i:i + sequence_length]])) y_train.append(train_data[i + sequence_length]) X_train_with_clusters, y_train = np.array(X_train_with_clusters), np.array(y_train) model = tf.keras.Sequential() model.add(tf.keras.layers.LSTM(100, activation='relu', return_sequences=True, input_shape=(sequence_length + 1, numerical_data.shape[1]))) model.add(tf.keras.layers.BatchNormalization()) model.add(tf.keras.layers.Dropout(0.2)) model.add(tf.keras.layers.LSTM(50, activation='relu', return_sequences=True, kernel_regularizer=tf.keras.regularizers.l1_l2(l1=1e-5, l2=1e-4))) model.add(tf.keras.layers.BatchNormalization()) model.add(tf.keras.layers.Dropout(0.2)) model.add(tf.keras.layers.LSTM(50, activation='relu', return_sequences=False, kernel_regularizer=tf.keras.regularizers.l1_l2(l1=1e-5, l2=1e-4))) model.add(tf.keras.layers.Dense(numerical_data.shape[1], activation='linear')) # Output con il numero di colonne di numerical_data optimizer = tf.keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=optimizer, loss='mean_absolute_error') class MAEEarlyStopping(tf.keras.callbacks.Callback): def __init__(self, monitor='val_loss', patience=10, restore_best_weights=True): super(MAEEarlyStopping, self).__init__() self.monitor = monitor self.patience = patience self.restore_best_weights = restore_best_weights self.best_mae = np.inf self.wait = 0 self.best_weights = None def on_epoch_end(self, epoch, logs=None): current_mae = logs.get(self.monitor) if current_mae is None: return if current_mae < self.best_mae: self.best_mae = current_mae self.wait = 0 if self.restore_best_weights: self.best_weights = self.model.get_weights() else: self.wait += 1 if self.wait >= self.patience: print(f'\nEpoch {epoch + 1}: Early stopping due to no improvement in MAE.') self.model.stop_training = True if self.restore_best_weights and self.best_weights is not None: print('Restoring model weights from the end of the best epoch.') self.model.set_weights(self.best_weights) mae_early_stopping = MAEEarlyStopping(monitor='val_mean_absolute_error', patience=10, restore_best_weights=True) history = model.fit(X_train_with_clusters, y_train, epochs=100, batch_size=16, validation_split=0.2, callbacks=[mae_early_stopping]) plt.plot(history.history['loss'], label='Training Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.title('Training and Validation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() X_test_with_clusters = np.concatenate([test_data[-sequence_length:], cluster_labels[-sequence_length:]]).reshape(1, sequence_length + 1, numerical_data.shape[1]) predicted_values = [] for _ in range(5): prediction = model.predict(X_test_with_clusters) predicted_value = scaler.inverse_transform(prediction)[0, 0] predicted_values.append(predicted_value) X_test_with_clusters = np.append(X_test_with_clusters[:, 1:], prediction).reshape(1, sequence_length + 1, numerical_data.shape[1]) total_probability = sum(predicted_values) probability_distribution = [value / total_probability for value in predicted_values] predicted_with_probabilities = [(valore, probabilità) for valore, probabilità in zip(predicted_values, probability_distribution)] predicted_with_probabilities.sort(key=lambda x: x[1], reverse=True) for i, (valore, probabilità) in enumerate(predicted_with_probabilities): print(f"Numero previsto {i + 1}: {int(round(valore))} - Probabilità: {probabilità:.4%}") X_test, y_test = [], [] for i in range(len(test_data) - sequence_length): X_test.append(test_data[i:i + sequence_length]) y_test.append(test_data[i + sequence_length]) X_test, y_test = np.array(X_test), np.array(y_test) y_pred = model.predict(X_test) mse = mean_squared_error(y_test, y_pred) print(f"\nErrore quadratico medio (MSE): {mse:.4f}") mae = mean_absolute_error(y_test, y_pred) print(f"Errore assoluto medio (MAE): {mae:.4f}") total_variance = np.sum((y_test - np.mean(y_test))**2) explained_variance = np.sum((y_pred - np.mean(y_test))**2) r_squared = 1 - (explained_variance / total_variance) print(f"Coefficiente di determinazione (R²): {r_squared:.4f}") else: print(f"Il file {file_path} non esiste.") - Assistant
- User
puoi riscrivere in italiano tutto il codice dall' inizio ala fine corretto per favore? senza omissioni
- Assistant
- User
puoi riscrivere lo stesso codice implementato con early stopping huber loss?
- Assistant
- User
inserisci anche la parte di prrevisione dei numeri
- Assistant
- User
deve prevedere i 5 numeri più probabili con le metriche definiute prima nel codice che ti ho inserito. Puoi riscrivere tutto conprensivo anche dell' ultima parte delle previsioni e delle metriche per favore? non vorrei commettere errori di trascrizione. grazie mille
- Assistant
- User
riscrivilo evitando il carattere SyntaxError: invalid character '“' (U+201C) ma usa il carattere '
- Assistant
- User
non hai sostituito tutti i caratteri '‘' (U+2018) con il carattere ' fallo e riscrivi
- Assistant
- User
- Assistant