Update app.py
Browse files1 unmodified line2345678910111213141516171 unmodified line1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441454 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761773 unmodified lines1811821831841851861871881891901914 unmodified lines1961971981992002012022032042052062072082092102112122132142151 unmodified lineimport pandas as pdfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_splitfrom tensorflow.keras.models import Sequential, Modelfrom tensorflow.keras.layers import Dense, Dropout, Input, LayerNormalization, MultiHeadAttention, GlobalAveragePooling1D, Embedding, Layer, LSTM, Bidirectional, Conv1Dfrom tensorflow.keras.optimizers import Adamfrom tensorflow.keras.utils import to_categoricalfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateauimport tensorflow as tfimport optunaimport gradio as gr# Combined data setdata = ["Double big 12", "Single big 11", "Single big 13", "Double big 12", "Double small 10","Double big 12", "Double big 12", "Single small 7", "Single small 5", "Single small 9",1 unmodified line"Double big 14", "Single big 17", "Triple 9", "Double small 6", "Single big 13","Double big 14", "Double small 8", "Double small 8", "Single big 13", "Single small 9","Double small 8", "Double small 8", "Single big 12", "Double small 8", "Double big 14","Double small 10", "Single big 13", "Single big 11", "Double big 14", "Double big 14","Double small", "Single big", "Double big", "Single small", "Single small","Double small", "Single small", "Single small", "Double small", "Double small","Double big", "Single big", "Triple", "Double big", "Single big", "Single big","Double small", "Single small", "Double big", "Double small", "Double big","Single small", "Single big", "Double small", "Double big", "Double big","Double small", "Single big", "Double big", "Triple", "Single big", "Double small","Single big", "Single small", "Double small", "Single big", "Single big","Single big", "Double small", "Double small", "Single big", "Single small","Single big", "Single small", "Single small", "Double small", "Single small","Single big"]# Counting the data pointsnum_data_points = len(data)print(f'Total number of data points: {num_data_points}')# Encoding the labelsencoder = LabelEncoder()encoded_data = encoder.fit_transform(data)# Create sequencessequence_length = 10X, y = [], []for i in range(len(encoded_data) - sequence_length):X.append(encoded_data[i:i + sequence_length])y.append(encoded_data[i + sequence_length])X = np.array(X)y = to_categorical(np.array(y), num_classes=len(encoder.classes_))print(f'Input shape: {X.shape}')print(f'Output shape: {y.shape}')class TransformerBlock(Layer):def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):super(TransformerBlock, self).__init__()self.att = MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim)self.ffn = Sequential([Dense(ff_dim, activation="relu"),Dense(embed_dim),])self.layernorm1 = LayerNormalization(epsilon=1e-6)self.layernorm2 = LayerNormalization(epsilon=1e-6)self.dropout1 = Dropout(rate)self.dropout2 = Dropout(rate)def call(self, inputs, training=False):attn_output = self.att(inputs, inputs)attn_output = self.dropout1(attn_output, training=training)out1 = self.layernorm1(inputs + attn_output)ffn_output = self.ffn(out1)ffn_output = self.dropout2(ffn_output, training=training)return self.layernorm2(out1 + ffn_output)def build_model(trial):embed_dim = trial.suggest_int('embed_dim', 64, 256, step=32)num_heads = trial.suggest_int('num_heads', 2, 8, step=2)ff_dim = trial.suggest_int('ff_dim', 128, 512, step=64)rate = trial.suggest_float('dropout', 0.1, 0.5, step=0.1)num_transformer_blocks = trial.suggest_int('num_transformer_blocks', 1, 3)inputs = Input(shape=(sequence_length,))embedding_layer = Embedding(input_dim=len(encoder.classes_), output_dim=embed_dim)x = embedding_layer(inputs)for _ in range(num_transformer_blocks):transformer_block = TransformerBlock(embed_dim, num_heads, ff_dim, rate)x = transformer_block(x)x = Conv1D(128, 3, activation='relu')(x)x = Bidirectional(LSTM(128, return_sequences=True))(x)x = GlobalAveragePooling1D()(x)x = Dropout(rate)(x)x = Dense(ff_dim, activation="relu")(x)x = Dropout(rate)(x)outputs = Dense(len(encoder.classes_), activation="softmax")(x)model = Model(inputs=inputs, outputs=outputs)optimizer = Adam(learning_rate=trial.suggest_float('lr', 1e-5, 1e-2, log=True))model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])return modeldef objective(trial):model = build_model(trial)early_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=1e-6)history = model.fit(X, y,epochs=100,batch_size=64,validation_split=0.2,callbacks=[early_stopping, reduce_lr],verbose=0)val_accuracy = max(history.history['val_accuracy'])return val_accuracy# Initialize the modelstudy = optuna.create_study(direction='maximize')study.optimize(lambda trial: objective(trial), n_trials=10)best_trial = study.best_trialprint(f'Best hyperparameters: {best_trial.params}')best_model = build_model(best_trial)early_stopping = EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=True)reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=10, min_lr=1e-6)history = best_model.fit(X, y,epochs=500,batch_size=64,validation_split=0.2,callbacks=[early_stopping, reduce_lr],verbose=2)def predict_next(model, data, sequence_length, encoder):last_sequence = data[-sequence_length:]4 unmodified linesdef update_data(data, new_outcome):data.append(new_outcome)if len(data) > sequence_length:data.pop(0)return datadef retrain_model(model, X, y, epochs=10):early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=1e-6)X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)model.fit(X_train, y_train,epochs=epochs,batch_size=64,validation_data=(X_val, y_val),callbacks=[early_stopping, reduce_lr],verbose=0)return modeldef gradio_predict(outcome):global data, best_modelif outcome not in encoder.classes_:return "Invalid outcome. Please try again."3 unmodified linesif len(data) < sequence_length:return "Not enough data to make a prediction."predicted_next = predict_next(best_model, data, sequence_length, encoder)return f'Predicted next outcome: {predicted_next}'def gradio_update(actual_next):global data, X, y, best_modelif actual_next not in encoder.classes_:return "Invalid outcome. Please try again."4 unmodified linesreturn "Not enough data to update the model."# Update X and ynew_X = encoder.transform(data[-sequence_length-1:-1]).reshape(1, -1)new_y = to_categorical(encoder.transform([data[-1]]), num_classes=len(encoder.classes_))X = np.vstack([X, new_X])y = np.vstack([y, new_y])# Retrain the modelbest_model = retrain_model(best_model, X, y, epochs=10)return "Model updated with new data."# Gradio interfacewith gr.Blocks() as demo:gr.Markdown("## Outcome Prediction with Enhanced Transformer")with gr.Row():outcome_input = gr.Textbox(label="Current Outcome")predict_button = gr.Button("Predict Next")1 unmodified line234567891011121314151 unmodified line171819202122232425262728293031323334353637383940414243444546474849505152535455564 unmodified lines6162636465666768697071727374753 unmodified lines79808182838485868788894 unmodified lines9495969798991001011021031041051061071081091101111121131141151161 unmodified lineimport pandas as pdfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_splitfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, LSTM, Embeddingfrom tensorflow.keras.optimizers import Adamfrom tensorflow.keras.utils import to_categoricalfrom tensorflow.keras.callbacks import EarlyStoppingimport gradio as gr# Initial data setdata = ["Double big 12", "Single big 11", "Single big 13", "Double big 12", "Double small 10","Double big 12", "Double big 12", "Single small 7", "Single small 5", "Single small 9",1 unmodified line"Double big 14", "Single big 17", "Triple 9", "Double small 6", "Single big 13","Double big 14", "Double small 8", "Double small 8", "Single big 13", "Single small 9","Double small 8", "Double small 8", "Single big 12", "Double small 8", "Double big 14","Double small 10", "Single big 13", "Single big 11", "Double big 14", "Double big 14"]# Encoding the labelsencoder = LabelEncoder()encoded_data = encoder.fit_transform(data)# Create sequencessequence_length = 5X, y = [], []for i in range(len(encoded_data) - sequence_length):X.append(encoded_data[i:i + sequence_length])y.append(encoded_data[i + sequence_length])X = np.array(X)y = to_categorical(y, num_classes=len(encoder.classes_))# Build the modeldef build_model(vocab_size, sequence_length):model = Sequential([Embedding(vocab_size, 50, input_length=sequence_length),LSTM(100),Dense(vocab_size, activation='softmax')])model.compile(loss='categorical_crossentropy', optimizer=Adam(learning_rate=0.001), metrics=['accuracy'])return model# Initialize the modelvocab_size = len(encoder.classes_)model = build_model(vocab_size, sequence_length)# Train the modelearly_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)history = model.fit(X, y, epochs=100, validation_split=0.2, callbacks=[early_stopping], verbose=0)def predict_next(model, data, sequence_length, encoder):last_sequence = data[-sequence_length:]4 unmodified linesdef update_data(data, new_outcome):data.append(new_outcome)return datadef retrain_model(model, X, y, epochs=10):early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)model.fit(X, y, epochs=epochs, validation_split=0.2, callbacks=[early_stopping], verbose=0)return modeldef gradio_predict(outcome):global data, modelif outcome not in encoder.classes_:return "Invalid outcome. Please try again."3 unmodified linesif len(data) < sequence_length:return "Not enough data to make a prediction."predicted_next = predict_next(model, data, sequence_length, encoder)return f'Predicted next outcome: {predicted_next}'def gradio_update(actual_next):global data, X, y, modelif actual_next not in encoder.classes_:return "Invalid outcome. Please try again."4 unmodified linesreturn "Not enough data to update the model."# Update X and ynew_X = []new_y = []for i in range(len(data) - sequence_length):new_X.append(encoder.transform(data[i:i + sequence_length]))new_y.append(encoder.transform([data[i + sequence_length]])[0])X = np.array(new_X)y = to_categorical(new_y, num_classes=len(encoder.classes_))# Retrain the modelmodel = retrain_model(model, X, y, epochs=10)return "Model updated with new data."# Gradio interfacewith gr.Blocks() as demo:gr.Markdown("## Outcome Prediction Model")with gr.Row():outcome_input = gr.Textbox(label="Current Outcome")predict_button = gr.Button("Predict Next")
app.py+35-134