def predict(): prediction = py.predict_model(model,data=user_df)['Label'] predict_per_sqm = prediction/user_df['areaSqm'][0] final_prediction = 'ML prediction: '+'€'+str(np.round(py.predict_model(model,data=user_df)['Label'][0],2)) final_per_sqm = 'Price per sqm from model: '+ '€'+str(np.round(predict_per_sqm[0],2)) st.subheader('Monthly rental prediction') st.write(final_prediction) st.write(final_per_sqm) st.write('ML model error range: +/- '+'€'+str(108)+' monthly rent')
def predict_batch(): file_upload = st.file_uploader('upload a csv file for the predictions!', type='csv') if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
def run(): from PIL import Image image = Image.open('logo.png') image_hospital = Image.open('hospital.jpg') st.image(image, use_column_width=False) add_selectbox = st.sidebar.selectbox('How would you like to predict?', ('Online', 'Batch')) st.sidebar.info('This app is created to predict patient hospital charges') st.sidebar.success('https://www.pycaret.org') st.sidebar.success('http://justinboggs.us') st.sidebar.image(image_hospital) st.title('Insurance Charges Prediction App') if add_selectbox == 'Online': age = st.number_input('Age', min_value=1, max_value=100, value=25) sex = st.selectbox('Sex', ['male', 'female']) bmi = st.number_input('BMI', min_value=10, max_value=50, value=10) children = st.selectbox('Children', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) if st.checkbox('Smoker'): smoker = 'yes' else: smoker = 'no' region = st.selectbox( 'Region', ['southwest', 'northwest', 'northeast', 'southeast']) output = "" input_dict = { 'age': age, 'sex': sex, 'bmi': bmi, 'children': children, 'smoker': smoker, 'region': region } input_df = pd.DataFrame([input_dict]) if st.button('Predict'): output = predict(model=model, input_df=input_df) output = '$' + str(output) st.success('The output is {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader('Upload csv file for predictions', type=['csv']) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
def run(): from PIL import Image image = Image.open('logo.PNG') image_hospital = Image.open('hospital.jpg') st.image(image, use_column_width=False) add_selectbox = st.sidebar.selectbox("How would you like to predict?", ("Online", "Batch")) st.sidebar.info( 'Web application for insurance prediction using Health data') st.sidebar.success('Yash shah Project') st.sidebar.image(image_hospital) st.title("Insurance Charges Prediction App") if add_selectbox == 'Online': age = st.number_input('Age', min_value=1, max_value=100, value=25) sex = st.selectbox('Sex', ['male', 'female']) bmi = st.number_input('BMI', min_value=10, max_value=50, value=10) children = st.selectbox('Children', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) if st.checkbox('Smoker'): smoker = 'yes' else: smoker = 'no' region = st.selectbox( 'Region', ['southwest', 'northwest', 'northeast', 'southeast']) output = "" input_dict = { 'age': age, 'sex': sex, 'bmi': bmi, 'children': children, 'smoker': smoker, 'region': region } input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = '$' + str(output) st.success('The output is {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
def predict(): int_features = [x for x in request.form.values()] final = np.array(int_features) data_unseen = pd.DataFrame([final], columns=cols) prediction = predict_model(model, data=data_unseen, round=0) prediction = int(prediction.Label[0]) return render_template('home.html', pred='Expected Bill will be {}'.format(prediction))
def predict(): predics=load_model('Xgb_Model') json_data=flask.request.json a=pd.DataFrame.from_dict(json_data,orient='index') b=pd.DataFrame.transpose(a) prediction=predict_model(predics,data=b) return str(prediction['Label'][0])
def run(): from PIL import Image image = Image.open('iFood.png') st.set_page_config(page_title='ifood', page_icon=image) image_host = Image.open('imagen.png') st.sidebar.info('This app is created to predict campains Response') st.sidebar.success('https://www.ifood.com.co/') st.sidebar.image(image_host) st.image( image, use_column_width=True, width=100, ) password = st.text_input("Password 🔑 :", value="", type="password") if password == '123': add_selectbox = st.sidebar.selectbox( "How would you like to predict 🔮 ?", ("Campains Respose", "Nothing")) else: st.error('passwword incorrecto') return # st.title("Salario referencia App") if add_selectbox == 'Campains Respose': st.title("Campains Respose") st.warning( ' para utilizar esta app por favor cargar en el Browse file el documento enviado para la prueba .csv' ) file_upload = st.file_uploader("Upload csv file for predictions 📁", type=["csv"]) if st.checkbox("Show Summary of Dataset"): data = pd.read_csv(file_upload) st.write(data.describe()) if file_upload is not None: data = pd.read_csv(file_upload) data['Edad'] = 2020 - data['Year_Birth'] data.drop(['Year_Birth'], axis=1, inplace=True) data['Dt_Customer'] = pd.to_datetime(data['Dt_Customer'], format='%Y-%m-%d') data['Dt_Customer'] = round( pd.to_numeric( (pd.to_datetime('2021-05-01') - data['Dt_Customer']) / np.timedelta64(1, 'M'))) predictions = predict_model(estimator=model, data=data) predictions['Label'] = np.where(predictions['Label'] == 1, 'Acepta', 'Rechaza') st.write(predictions) st.write(get_table_download_link(predictions, 'profiles.csv', 'Download predictions 👨💻'), unsafe_allow_html=True)
def run(): from PIL import Image image = Image.open('logo.jpeg') image_hospital = Image.open('hospital.jpg') st.image(image, use_column_width=False) add_selectbox = st.sidebar.selectbox("How would you like to predict?", ("Online", "Batch")) st.sidebar.info( 'This Project is Developed by Mohd Aquib,Team SCRIPTHON.This app is created to predict patient hospital charges.' ) st.sidebar.success('https://github.com/AquibPy') st.sidebar.image(image_hospital) st.title("Insurance Charges Prediction App") if add_selectbox == "Online": age = st.number_input('Age', min_value=1, max_value=100, value=25) sex = st.selectbox('Sex', ['male', 'female']) bmi = st.number_input('BMI', min_value=10, max_value=50, value=10) children = st.selectbox('Children', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) if st.checkbox('Smoker'): smoker = 'yes' else: smoker = 'no' region = st.selectbox( 'Region', ['southwest', 'northwest', 'northeast', 'southeast']) output = "" input_dict = { 'age': age, 'sex': sex, 'bmi': bmi, 'children': children, 'smoker': smoker, 'region': region } input_df = pd.DataFrame([input_dict]) if st.button('Predict'): output = predict(model=model, input_df=input_df) output = "$" + str(output) st.success('The output is {}'.format(output)) if add_selectbox == "Batch": file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
def predict(carat_weight, cut, color, clarity, polish, symmetry, report): data = pd.DataFrame( [[carat_weight, cut, color, clarity, polish, symmetry, report]]) data.columns = [ 'Carat Weight', 'Cut', 'Color', 'Clarity', 'Polish', 'Symmetry', 'Report' ] predictions = predict_model(model, data=data) return {'prediction': int(predictions['Label'][0])}
def predict(): int_features = [x for x in request.form.values()] final = np.array(int_features) data_unseen = pd.DataFrame([final], columns=cols) prediction = predict_model(model, data=data_unseen) prediction = int(prediction.Label[0]) #loan = ' Approved ' if prediction == True else ' Rejected ' return render_template( 'home.html', prediction_text='Loan Percentage is {}'.format(prediction))
def run(): from PIL import Image image = Image.open('logo.png') image_hospital = Image.open('hospital.jpg') st.image(image,use_column_width=False) add_selectbox = st.sidebar.selectbox( "How would you like to predict?", ("Online", "Batch")) st.sidebar.info('This app is created to predict patient hospital charges') st.sidebar.success('https://www.pycaret.org') st.sidebar.image(image_hospital) st.title("Insurance Charges Prediction App") if add_selectbox == 'Online': Age = st.number_input('Age', min_value=0, max_value=100, value=6) Gender = st.selectbox(' Gender ', ['male', 'female']) Transport = st.selectbox(' Transport ', ['Other', ' Ambulance ', , ' Helicopter']) Visit_Reason = st.selectbox(Visit_Reason', ['Allergy (Including Anaphylaxis)', 'Infectious Disease', 'Diagnosis Not Classifiable', 'Gastrointestinal Conditions', 'Other Vascular Conditions', 'Respiratory Conditions', 'Burns and Scalds', 'Sprain/Ligament Injury', 'Nothing Abnormal Detected', 'Head Injury', 'Facio-Maxillary Conditions', 'ENT Conditions', 'Urological Conditions (Including Cystitis)', 'Local Infection', 'Soft Tissue Inflammation', 'Muscle/Tendon Injury', 'Central Nervous System Conditions (Excluding Strokes)', 'Psychiatric Conditions', 'Contusion/Abrasion', 'Dislocation/Fracture/Joint Injury/Amputation', 'Laceration', 'Dermatological Conditions', 'Poisoning (Including Overdose)', 'Diabetes and Other Endocrinological Conditions', 'Foreign Body', 'Social Problem (Includes Chronic Alcoholism and Homelessness)', 'Cardiac Conditions', 'Obstetric Conditions', 'Bites/Stings', 'Gynaecological Conditions', 'Ophthalmological Conditions', 'Haematological Conditions', 'Cerebro-Vascular Conditions', 'Visceral Injury', 'Vascular Injury', 'Nerve Injury', 'Near Drowning']) REFER_SOURCE= st.selectbox(' REFER_SOURCE', ['SELF', 'CONS IN HOSP', 'AE', 'OTHER']) AVPU = st.selectbox('AVPU', ['Alert', 'Verbal', 'Pain', 'Unresponsive']) PulseRate = st.number_input('PulseRate', min_value=10, max_value=250, value=70) RespiratoryRate = st.number_input('RespiratoryRate', min_value=10, max_value=100, value=25) SP02 = st.number_input('SP02', min_value=10, max_value=50, value=100) Temperature = st.number_input('Temperature', min_value=10, max_value=50, value=37) output="" input_dict = {'Age' : Age, 'Gender' : Gender, 'Transport' : Transport, 'Visit_Reason' : Visit_Reason, 'REFER_SOURCE' : REFER_SOURCE, 'AVPU' : AVPU, 'PulseRate' : PulseRate, 'RespiratoryRate' : RespiratoryRate , 'SP02' : SP02, 'Temperature' : Temperature } input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = '$' + str(output) st.success('The output is {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model,data=data) st.write(predictions)
def run(): from PIL import Image image = Image.open("picture.jfif") st.image(image, use_column_width=False) add_selectbox = st.sidebar.selectbox("How would you like to predict?", ("Online", "Batch")) st.sidebar.info("This app is to predict the insurance bill") st.sidebar.success("Some other text") st.title("The insurance app") if add_selectbox == "Online": age = st.number_input("Age", min_value=1, max_value=100, value=25) sex = st.selectbox("Sex", ["male", "female"]) bmi = st.number_input("BMI", min_value=10, max_value=40, value=20) children = st.selectbox("How many children?", [1, 2, 3, 4, 5]) if st.checkbox("Smoker"): smoker = "yes" else: smoker = "no" region = st.selectbox( "US Region", ["southwest", "northwest", "northeast", "southeast"]) output = "" input_dict = dict(age=age, sex=sex, bmi=bmi, children=children, smoker=smoker, region=region) input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model, input_df=input_df) output = "$" + str(output) st.success("The output is {}".format(output)) if add_selectbox == "Batch": file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
def _regression(self, combined_data): self._regression_setup(combined_data) # Train regresser = regression.create_model(self.task.pycaret_model, verbose=False) # Store if self.task.output_dir: self._store_regresser(regresser) # Predict on Test set predictions = regression.predict_model( regresser, verbose=False) # TODO get raw_scores for AUC return predictions
def run(): add_selectbox = st.sidebar.selectbox("How would you like to predict?", ("Online", "Batch")) st.sidebar.info('This app is created to predict patient hospital charges') st.sidebar.success('https://www.pycaret.org') st.title("Insurance Charges Prediction App") if add_selectbox == 'Online': age = st.number_input('Age', min_value=1, max_value=100, value=25) sex = st.selectbox('Sex', ['male', 'female']) bmi = st.number_input('BMI', min_value=10, max_value=50, value=10) children = st.selectbox('Children', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) if st.checkbox('Smoker'): smoker = 'yes' else: smoker = 'no' region = st.selectbox( 'Region', ['southwest', 'northwest', 'northeast', 'southeast']) output = "" input_dict = { 'age': age, 'sex': sex, 'bmi': bmi, 'children': children, 'smoker': smoker, 'region': region } input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = '$' + str(output) st.success('The output is {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
def run(): from PIL import Image image = Image.open('logo.png') image_hospital = Image.open('hospital.jpg') st.image(image,use_column_width=False) add_selectbox = st.sidebar.selectbox( "Como gostaria de fazer a previsão?", ("Online", "Batch")) st.sidebar.info('Esta aplicação foi desenvolvida para prever as despesas hospitalares de pacientes.') st.sidebar.success('http://sibylconsultoria.com.br ') st.sidebar.image(image_hospital) st.title("Aplicação de previsão de encargos de seguro") if add_selectbox == 'Online': age = st.number_input('Idade', min_value=1, max_value=100, value=25) sex = st.selectbox('Sexo', ['Masculino', 'Feminino']) bmi = st.number_input('BMI', min_value=10, max_value=50, value=10) children = st.selectbox('Filhos', [0,1,2,3,4,5,6,7,8,9,10]) if st.checkbox('Fumante'): smoker = 'sim' else: smoker = 'não' region = st.selectbox('Região', ['Sudeste', 'Nordeste', 'Suldoeste', 'Noroeste']) output="" input_dict = {'Idade': age, 'Sexo': sex, 'BMI': bmi,'Filhos': children, 'Fumante': smoker, 'Região': region} input_df = pd.DataFrame([input_dict]) if st.button("Prever"): output = predict(model=model, input_df=input_df) output = '$' + str(output) st.success('A saída é {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader("Faça o upload do arquivo em no formato CSV.", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model,data=data) st.write(predictions)
def run_pycaret(name, df_train, df_test, acc_func, target): pycaret_acc_func_str = 'Accuracy' for pycaret_metrics in [ 'Accuracy', 'AUC', 'Recall', 'Precision', 'F1', 'Kappa', 'MCC', 'MAE', 'MSE', 'RMSE', 'R2', 'RMSLE', 'MAPE' ]: if pycaret_metrics.lower() in str(acc_func).lower(): pycaret_acc_func_str = pycaret_metrics import traceback task_type = 'classification' if pycaret_acc_func_str in ['MAE', 'MSE', 'RMSE', 'R2', 'RMSLE', 'MAPE']: task_type = 'regression' from pycaret.regression import setup, compare_models, predict_model, blend_models, stack_models, automl, create_model else: from pycaret.classification import setup, compare_models, predict_model, blend_models, stack_models, automl, create_model setup_return = setup(data=df_train, target=target) top_models = compare_models(n_select=3, verbose=False, sort=pycaret_acc_func_str, turbo=True, blacklist=['catboost', 'xgboost']) # Ensemble the top models and optimize the resulting model blender = blend_models(estimator_list=top_models, verbose=False) stacker = stack_models(estimator_list=top_models, meta_model=top_models[0], verbose=False) best_model = automl(optimize=pycaret_acc_func_str) df_test_dropped = df_test.drop(columns=[target]) predictions = predict_model(best_model, data=df_test_dropped) try: accuracy = acc_func(list(predictions['Label']), list(df_test[target])) except Exception as e: traceback.print_exc() print(f'Exception computing accuracy (1): {e}') if task_type == 'classification': accuracy = acc_func([str(x) for x in list(predictions['Label'])], [str(x) for x in list(df_test[target])]) elif task_type == 'regression': accuracy = acc_func([float(x) for x in list(predictions['Label'])], [float(x) for x in list(df_test[target])]) return accuracy
def run(): #from PIL import Image #image = Image.open('logo.png') #image_hospital = Image.open('hospital.jpg') #st.image(image,use_column_width=False) add_selectbox = st.sidebar.selectbox( "How would you like to predict?", ("Online", "Batch")) st.sidebar.info('This app is created to predict car mileage') #st.sidebar.success('https://www.pycaret.org') #st.sidebar.image(image_hospital) st.title("Car Mileage Prediction App") if add_selectbox == 'Online': cylinders = st.number_input('Cylinders', min_value=1, max_value=100, value=8) displacement = st.number_input('Displacement', min_value = 0, max_value = 500, value = 100) horsepower = st.number_input('Horsepower',min_value = 0, max_value = 1000, value = 200) weight = st.number_input('Weight',min_value = 0,max_value = 6000, value = 3000) acceleration = st.number_input('Acceleration', min_value = 0,max_value = 100, value = 10) origin = st.selectbox('Origin (1:USA, 2:Europe, 3:Japan)',[1,2,3]) output="" input_dict = {'cylinders' : cylinders, 'displacement' : displacement, 'horsepower':horsepower, 'weight' : weight, 'acceleration' : acceleration, 'origin' : origin} input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = output st.success('The output is {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model,data=data) st.write(predictions)
def online_predict(model, input_df,target_type): """make prediction on online data Args: model (object): a trained model input_df (pd.DataFrame): the input dataframe for predicitons target_type (str): the type of training target Returns: str: predcition """ prediction_df = predict_model(model, data=input_df) if target_type == 'Regression' or target_type == 'Classification': predictions = prediction_df['Label'][0] else: predictions = prediction_df['Cluster'][0] return predictions
def run(): from PIL import Image image_hospital = Image.open('hospital.jpg') st.sidebar.info('This app is created using PyCaret and Strealit') st.sidebar.success('https://youtube.com/KunaalNaik') st.sidebar.image(image_hospital) st.title('Insurance Application') # Capture age = st.number_input('Age', min_value=1, max_value=100, value=21) sex = st.selectbox('Sex', ['male', 'female']) bmi = st.number_input('BMI', min_value=10, max_value=50, value=10) children = st.selectbox('Children', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) if st.checkbox('Smoker'): smoker = 'yes' else: smoker = 'no' region = st.selectbox('Region', ['southwest', 'northwest', 'northeast', 'southeast']) output = "" # Input Dict input_dict = { 'age': age, 'sex': sex, 'bmi': bmi, 'children': children, 'smoker': smoker, 'region': region } input_df = pd.DataFrame([input_dict]) # Predict if st.button('Predict'): output = predict_model(model, data=input_df) output = '$' + str(output['Label'][0]) # Display st.success('The Insurance amount is {}'.format(output))
def predict(model, input_df): predictions_df = predict_model(estimator=model, data=input_df) predictions = predictions_df['Label'][0] return predictions
def run(): from PIL import Image image = Image.open('panels.jpeg') st.image(image, use_column_width=True) add_selectbox = st.sidebar.selectbox( "Would you like to predict a single day or upload a .csv?", ("Single Day", "Upload .csv")) st.sidebar.info( 'Using a Machine Learning model to predict the kW production of Solar Panels in Antwerp, Belgium' ) st.sidebar.info( 'Please refer to the GitHub repo to view the Weather Mapping for the "Weather Condition" input' ) st.sidebar.success('https://tmplayground.com') st.sidebar.success('https://github.com/thabied') st.sidebar.image( 'https://media.giphy.com/media/l1J9Nd2okdiIq7K9O/giphy.gif', use_column_width=True) st.title("Solar Power Prediction Application") if add_selectbox == 'Single Day': year = st.number_input('Year', min_value=1990, max_value=2550, value=2014) month = st.number_input('Month', min_value=1, max_value=12, value=5) day = st.number_input('Day', min_value=1, max_value=31, value=16) temp = st.slider('Temperature (celsius)', min_value=-0, max_value=50, value=18, step=1) weather = st.number_input('Weather Condition', min_value=1, max_value=130, value=50) wind = st.number_input('Wind (km/h)', min_value=1, max_value=50, value=14) humidity = st.slider('Humidity (%)', min_value=0, max_value=100, value=0, step=1) barometer = st.number_input('Atmospheric Pressure (milibar)', min_value=1, max_value=2000, value=25) visibility = st.number_input('Visibility (km)', min_value=0, max_value=40, value=25) output = "" input_dict = { 'year': year, 'month': month, 'day': day, 'temp': temp, 'weather': weather, 'wind': wind, 'humidity': humidity, 'barometer': barometer, 'visibility': visibility } input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = str(output) + 'kWs' st.success('The output is {}'.format(output)) if add_selectbox == 'Upload .csv': file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
else: smoker = 'no' region = st.selectbox('Region', ['southwest', 'northwest', 'northeast', 'southeast']) output = "" input_dict = { 'age': age, 'sex': sex, 'bmi': bmi, 'children': children, 'smoker': smoker, 'region': region } input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = '$' + str(output) st.success('The output is {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
def write(state): if state.trained_model is not None: X_before_preprocess = state.X_before_preprocess target_name = state.y_before_preprocess df_X = X_before_preprocess.drop(target_name, axis=1) trained_model = state.trained_model min_value = X_before_preprocess[target_name].min() max_value = X_before_preprocess[target_name].max() mean_value = X_before_preprocess[target_name].mean() original_value = optimal_value = mean_value st.header("Knowledge Generation and Backward Analysis.") with st.beta_expander("Knowledge Generation"): st.markdown( '<p style="color:#1386fc">Please Select a Method to Generate Data.</p>', unsafe_allow_html=True) sdv_method = st.selectbox( 'Method to Generate Data', options=['GaussianCopula', 'CTGAN', 'CopulaGAN', 'TVAE']) sample = st.number_input('How Many Samples of Data to Generate?', min_value=1, value=df_X.shape[0], key=1) if sdv_method == 'GaussianCopula': model = GaussianCopula() else: is_tune = st.checkbox("Do You Want to Tune Hyperparameters?", value=False) if sdv_method == 'CopulaGAN' or sdv_method == 'CTGAN': epochs = 300 batch_size = 500 log_frequency = True embedding_dim = 128 generator_dim = (256, 256) discriminator_dim = (256, 256) generator_lr = 0.0002 generator_decay = 1e-6 discriminator_lr = 0.0002 discriminator_decay = 1e-6 discriminator_steps = 1 if is_tune: epochs = st.number_input( "Number of Training Epochs (int)", min_value=1, value=300, key=1) batch_size = st.number_input( "Number of Data Samples to Process, should be a multiple of 10 (int)", min_value=1, value=500, key=1) log_frequency = st.checkbox( 'Whether to Use Log Frequency', value=True) embedding_dim = st.number_input( "Size of the Random Sample Passed to the Generator (int)", min_value=1, value=128, key=1) generator_dim = st.text_input( "Size of the Generator Residual Layer (int)", value="256,256") discriminator_dim = st.text_input( "Size of the Discriminator Residual Layer (int)", value="256,256") generator_lr = st.number_input( "Learning Rate for the Generator", min_value=0.0, value=0.0002, format="%e") generator_decay = st.number_input( "Generator Weight Decay for the Adam Optimizer", min_value=0.0, value=1e-6, format="%e") discriminator_lr = st.number_input( "Learning Rate for the Discriminator", min_value=0.0, value=0.0002, format="%e") discriminator_decay = st.number_input( "Discriminator Weight Decay for the Adam Optimizer", min_value=0.0, value=1e-6, format="%e") discriminator_steps = st.number_input( "Number of Discriminator Updates to do for Each Generator Update (int)", min_value=1, value=1) generator_dim = convert_str_to_list(generator_dim) discriminator_dim = convert_str_to_list( discriminator_dim) if sdv_method == 'CopulaGAN': model = CopulaGAN( epochs=epochs, batch_size=batch_size, log_frequency=log_frequency, embedding_dim=embedding_dim, generator_dim=generator_dim, discriminator_dim=discriminator_dim, generator_lr=generator_lr, generator_decay=generator_decay, discriminator_lr=discriminator_lr, discriminator_decay=discriminator_decay, discriminator_steps=discriminator_steps) if sdv_method == 'CTGAN': model = CTGAN(epochs=epochs, batch_size=batch_size, log_frequency=log_frequency, embedding_dim=embedding_dim, generator_dim=generator_dim, discriminator_dim=discriminator_dim, generator_lr=generator_lr, generator_decay=generator_decay, discriminator_lr=discriminator_lr, discriminator_decay=discriminator_decay, discriminator_steps=discriminator_steps) else: compress_dims = decompress_dims = (128, 128) epochs = 300 batch_size = 500 embedding_dim = 128 l2_scale = 1e-5 if is_tune: epochs = st.number_input( "Number of Training Epochs (int)", min_value=1, value=300, key=2) batch_size = st.number_input( "Number of Data Samples to Process, should be a multiple of 10 (int)", min_value=1, value=500, key=2) embedding_dim = st.number_input( "Size of the Random Sample Passed to the Generator (int)", min_value=1, value=128, key=2) compress_dims = st.text_input( "Size of Each Hidden Layer in the Encoder (int)", value="128,128") decompress_dims = st.text_input( "Size of Each Hidden Layer in the Decoder (int)", value="128,128") l2_scale = st.number_input("Regularization term", min_value=0.0, value=1e-5, format="%e") compress_dims = convert_str_to_list(compress_dims) decompress_dims = convert_str_to_list(decompress_dims) model = TVAE(embedding_dim=embedding_dim, compress_dims=compress_dims, decompress_dims=decompress_dims, l2scale=l2_scale, batch_size=batch_size, epochs=epochs) button_generate = st.button("Generate") if button_generate: with st.spinner("Generating..."): model.fit(df_X) new_data = model.sample(sample) new_data_prediction = predict_model( trained_model, new_data) st.write(new_data_prediction) state.new_data_prediction = new_data_prediction button_download = st.button("Download Generated Data") if button_download: file_extension = st.selectbox( "Choose Csv or Excel File to Download", options=[".csv", ".xlsx"]) file_name = st.text_input("File Name", value="prediction", key=1) if file_name: href = download_button(state.new_data_prediction, file_name, "Download", file_extension) st.markdown(href, unsafe_allow_html=True) else: st.error("File Name cannot be empty!") st.markdown("---") with st.beta_expander("Backward Analysis"): col1, col2 = st.beta_columns(2) with col1: st.subheader("Please Select a Index for Data to Optimize") index = st.number_input("Index of Data", min_value=0, value=0, max_value=df_X.shape[0] - 1, key=1) st.write(X_before_preprocess.iloc[index]) original_value = X_before_preprocess.iloc[index].loc[ target_name] # st.write(original_value) with col2: st.subheader("Optimize") lower_bound = st.number_input( "The Lower Bound Value to Optimize", value=min_value) upper_bound = st.number_input( "The Upper Bound Value to Optimize", value=max_value) button_optimize = st.button("Optimizer") if button_optimize: if state.new_data_prediction is not None: new_prediction = state.new_data_prediction['Label'] indices = find_top_5_nearest(new_prediction, original_value) optimal_value = new_prediction[indices[0]] state.suggest_indices = indices state.optimal_value = optimal_value else: st.error("Please Generate New Data first!") with st.beta_container(): state.optimal_value = state.optimal_value if state.optimal_value is not None else 0 fig = gauge_plot(original_value, state.optimal_value, lower_bound, upper_bound, min_value, max_value) st.plotly_chart(fig) button_suggest = st.button("Show the Top 5 Suggestions") if button_suggest: suggestion = state.new_data_prediction.iloc[ state.suggest_indices[:5]] st.table(suggestion) else: st.error("Please Train a Model first!")
def run(): from PIL import Image image = Image.open('logo.png') image_hospital = Image.open('hospital.jpg') st.image(image, use_column_width=True) html_temp = """ <div style="background-color:midnightblue;padding:1.5px"> <h1 style="color:white;text-align:center;">Health Bucks </h1> </div><br>""" st.markdown(html_temp, unsafe_allow_html=True) add_selectbox = st.sidebar.selectbox("How would you like to predict?", ("Online", "Batch")) st.sidebar.info( 'This Web App is designed to predict patient hospitalization charges based on demographic and health risk metrics using Machine Learning.' ) st.sidebar.success('https://www.pycaret.org') st.sidebar.image(image_hospital) st.header("Hospitalization Charges Prediction Web App") if add_selectbox == 'Online': age = st.number_input('Age', min_value=1, max_value=100, value=25) sex = st.selectbox('Sex', ['male', 'female']) bmi = st.number_input('BMI', min_value=10, max_value=50, value=10) children = st.selectbox('Children', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) if st.checkbox('Smoker'): smoker = 'yes' else: smoker = 'no' region = st.selectbox( 'Region', ['southwest', 'northwest', 'northeast', 'southeast']) output = "" input_dict = { 'age': age, 'sex': sex, 'bmi': bmi, 'children': children, 'smoker': smoker, 'region': region } input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = 'Rs. ' + str(output) st.success('The output is {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
def run(): from PIL import Image image = Image.open('banglore_1.jpg') image_office = Image.open('banglore_2.jpg') st.image(image,use_column_width=True) add_selectbox = st.sidebar.selectbox( "How would you like to predict?", ("Online", "Batch")) st.sidebar.info('This app is created to predict the house prices at various locations in Bengaluru') st.sidebar.success('https://www.pycaret.org') st.sidebar.image(image_office) st.title("Predicting House Prices") if add_selectbox == 'Online': location=st.selectbox('location', ['Electronic City Phase II', 'Chikka Tirupathi', 'Uttarahalli', 'Lingadheeranahalli', 'Kothanur', 'Whitefield', 'Old Airport Road', 'Rajaji Nagar', 'Marathahalli', 'other', '7th Phase JP Nagar', 'Gottigere', 'Sarjapur', 'Mysore Road', 'Bisuvanahalli', 'Raja Rajeshwari Nagar', 'Kengeri', 'Binny Pete', 'Thanisandra', 'Bellandur', 'Electronic City', 'Ramagondanahalli', 'Yelahanka', 'Hebbal', 'Kasturi Nagar', 'Kanakpura Road', 'Electronics City Phase 1', 'Kundalahalli', 'Chikkalasandra', 'Murugeshpalya', 'Sarjapur Road', 'HSR Layout', 'Doddathoguru', 'KR Puram', 'Bhoganhalli', 'Lakshminarayana Pura', 'Begur Road', 'Devanahalli', 'Varthur', 'Bommanahalli', 'Gunjur', 'Hegde Nagar', 'Haralur Road', 'Hennur Road', 'Kothannur', 'Kalena Agrahara', 'Kaval Byrasandra', 'ISRO Layout', 'Garudachar Palya', 'EPIP Zone', 'Dasanapura', 'Kasavanhalli', 'Sanjay nagar', 'Domlur', 'Sarjapura - Attibele Road', 'Yeshwanthpur', 'Chandapura', 'Nagarbhavi', 'Ramamurthy Nagar', 'Malleshwaram', 'Akshaya Nagar', 'Shampura', 'Kadugodi', 'LB Shastri Nagar', 'Hormavu', 'Vishwapriya Layout', 'Kudlu Gate', '8th Phase JP Nagar', 'Bommasandra Industrial Area', 'Anandapura', 'Vishveshwarya Layout', 'Kengeri Satellite Town', 'Kannamangala', ' Devarachikkanahalli', 'Hulimavu', 'Mahalakshmi Layout', 'Hosa Road', 'Attibele', 'CV Raman Nagar', 'Kumaraswami Layout', 'Nagavara', 'Hebbal Kempapura', 'Vijayanagar', 'Nagasandra', 'Kogilu', 'Panathur', 'Padmanabhanagar', '1st Block Jayanagar', 'Kammasandra', 'Dasarahalli', 'Magadi Road', 'Koramangala', 'Dommasandra', 'Budigere', 'Kalyan nagar', 'OMBR Layout', 'Horamavu Agara', 'Ambedkar Nagar', 'Talaghattapura', 'Balagere', 'Jigani', 'Gollarapalya Hosahalli', 'Old Madras Road', 'Kaggadasapura', '9th Phase JP Nagar', 'Jakkur', 'TC Palaya', 'Giri Nagar', 'Singasandra', 'AECS Layout', 'Mallasandra', 'Begur', 'JP Nagar', 'Malleshpalya', 'Munnekollal', 'Kaggalipura', '6th Phase JP Nagar', 'Ulsoor', 'Thigalarapalya', 'Somasundara Palya', 'Basaveshwara Nagar', 'Bommasandra', 'Ardendale', 'Harlur', 'Kodihalli', 'Bannerghatta Road', 'Hennur', '5th Phase JP Nagar', 'Kodigehaali', 'Billekahalli', 'Jalahalli', 'Mahadevpura', 'Anekal', 'Sompura', 'Dodda Nekkundi', 'Hosur Road', 'Battarahalli', 'Sultan Palaya', 'Ambalipura', 'Hoodi', 'Brookefield', 'Yelenahalli', 'Vittasandra', '2nd Stage Nagarbhavi', 'Vidyaranyapura', 'Amruthahalli', 'Kodigehalli', 'Subramanyapura', 'Basavangudi', 'Kenchenahalli', 'Banjara Layout', 'Kereguddadahalli', 'Kambipura', 'Banashankari Stage III', 'Sector 7 HSR Layout', 'Rajiv Nagar', 'Arekere', 'Mico Layout', 'Kammanahalli', 'Banashankari', 'Chikkabanavar', 'HRBR Layout', 'Nehru Nagar', 'Kanakapura', 'Konanakunte', 'Margondanahalli', 'R.T. Nagar', 'Tumkur Road', 'GM Palaya', 'Jalahalli East', 'Hosakerehalli', 'Indira Nagar', 'Kodichikkanahalli', 'Varthur Road', 'Anjanapura', 'Abbigere', 'Tindlu', 'Gubbalala', 'Cunningham Road', 'Kudlu', 'Banashankari Stage VI', 'Cox Town', 'Kathriguppe', 'HBR Layout', 'Yelahanka New Town', 'Sahakara Nagar', 'Rachenahalli', 'Yelachenahalli', 'Green Glen Layout', 'Thubarahalli', 'Horamavu Banaswadi', '1st Phase JP Nagar', 'NGR Layout', 'Seegehalli', 'NRI Layout', 'ITPL', 'Babusapalaya', 'Iblur Village', 'Ananth Nagar', 'Channasandra', 'Choodasandra', 'Kaikondrahalli', 'Neeladri Nagar', 'Frazer Town', 'Cooke Town', 'Doddakallasandra', 'Chamrajpet', 'Rayasandra', '5th Block Hbr Layout', 'Pai Layout', 'Banashankari Stage V', 'Sonnenahalli', 'Benson Town', 'Poorna Pragna Layout', 'Judicial Layout', 'Banashankari Stage II', 'Karuna Nagar', 'Bannerghatta', 'Bommenahalli', 'Laggere', 'Prithvi Layout', 'Banaswadi', 'Sector 2 HSR Layout', 'Shivaji Nagar', 'Nagavarapalya', 'BTM Layout', 'BTM 2nd Stage', 'Hoskote', 'Doddaballapur', 'Sarakki Nagar', 'Bharathi Nagar', 'HAL 2nd Stage', 'Kadubeesanahalli']) bhk=st.number_input('bhk' , min_value=1, max_value=6, value=1) total_sqft =st.number_input('total_sqft',min_value=300, max_value=7000, value=300) bath = st.number_input('bath', min_value=1, max_value=6, value=1) output="" input_dict={'location':location,'bhk':bhk,'total_sqft':total_sqft,'bath':bath} input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = str(output) st.success('Price in Lakhs is {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model,data=data) st.write(predictions)
def run(): from PIL import Image image = Image.open('logo1.PNG') image_hospital = Image.open('house.jpeg') st.image(image, use_column_width=False) add_selectbox = st.sidebar.selectbox("How would you like to predict?", ("Online", "Batch")) st.sidebar.info( 'This app is created to predict the house loan using PyCaret Linear Regression by "Krishna Yarlagadda"' ) st.sidebar.success('https://www.pycaret.org') st.sidebar.image(image_hospital) st.title("House Prices Prediction Application") if add_selectbox == 'Online': LotArea = st.number_input('LotArea', min_value=1, max_value=100000, value=50) GarageArea = st.number_input('GarageArea', min_value=1, max_value=100000, value=50) FirstFloorSF = st.number_input('FirstFloorSF', min_value=1, max_value=100000, value=50) SecondFloorSF = st.number_input('SecondFloorSF', min_value=1, max_value=100000, value=50) PavedDrive = st.selectbox('PavedDrive', ['Y', 'N', 'P']) SaleCondition = st.selectbox( 'SaleCondition', ['Normal', 'Partial', 'Abnormal', 'Family', 'Alloca', 'AdjLand']) FullBath = st.selectbox('FullBath', [0, 1, 2, 3]) HalfBath = st.selectbox('HalfBath', [0, 1, 2, 3]) output = "" input_dict = { 'LotArea': LotArea, 'GarageArea': GarageArea, 'FirstFloorSF': FirstFloorSF, 'SecondFloorSF': SecondFloorSF, 'PavedDrive': PavedDrive, 'SaleCondition': SaleCondition, 'FullBath': FullBath, 'HalfBath': HalfBath } input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = '$' + str(output) st.success('The output is {}'.format(output)) if add_selectbox == 'Batch': file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions)
def run(): from PIL import Image with open("style.css") as f: st.markdown("<style>{}</style>".format(f.read()), unsafe_allow_html=True) # Load images into variable. image = Image.open("logo.png") image_hospital = Image.open("hospital.jpg") # Looks like you can add HTML in a hacky way st.markdown( "<h1>HTML title with custom CSS</h1>", unsafe_allow_html=True, ) # Loads image at the top of the app (align with hack) st.image(image, use_column_width=False, width=200) # This is awesome add_selectbox = st.sidebar.selectbox("How would you like to predict?", ("Online", "Batch", "YouTube")) st.sidebar.info("This app is created to predict patient hospital charges") st.sidebar.success( "https://medium.com/@moez_62905/build-and-deploy-machine-learning-web-app-using-pycaret-and-streamlit-28883a569104" ) st.sidebar.image(image_hospital) st.title("Insurance Charges Prediction App") if add_selectbox == "Online": age = st.number_input("Age", min_value=1, max_value=100, value=25) sex = st.selectbox("Sex", ["male", "female"]) bmi = st.number_input("BMI", min_value=10, max_value=50, value=10) children = st.selectbox("Children", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) if st.checkbox("Smoker"): smoker = "yes" else: smoker = "no" region = st.selectbox( "Region", ["southwest", "northwest", "northeast", "southeast"]) output = "" input_dict = { "age": age, "sex": sex, "bmi": bmi, "children": children, "smoker": smoker, "region": region, } input_df = pd.DataFrame([input_dict]) if st.button("Predict"): output = predict(model=model, input_df=input_df) output = "$" + str(output) st.success("The output is {}".format(output)) # Disable warning st.set_option("deprecation.showfileUploaderEncoding", False) if add_selectbox == "Batch": file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"]) if file_upload is not None: data = pd.read_csv(file_upload) predictions = predict_model(estimator=model, data=data) st.write(predictions) if add_selectbox == "YouTube": if st.button("Show video"): video_youtube()
import argparse import numpy as np import pandas as pd from main import pre_procces from pycaret.regression import load_model, predict_model parser = argparse.ArgumentParser(description='Process input') parser.add_argument('tsv_path', type=str, help='tsv file path') args = parser.parse_args() prediction_df = pre_procces(args.tsv_path) model = load_model('model') prediction_df = predict_model(model, prediction_df) prediction_df.loc[prediction_df['Label'] < 0, 'Label'] = 0 prediction_df[['movie_id', 'Label']].to_csv("prediction.csv", index=False, header=False)
'\n\n- Demanda de ACS (litros/día). *Demanda de agua caliente sanitaria conforme al CTE (en litros/día).*' '\n\n- Suma de superficies en fachada (m²). *Total de las superficies de fachada en contacto con el exterior y que forman parte de la envolvente térmica (en m²).*' '\n\n- Transmitancia térmica media en fachadas (W/m²K). *Valor medio de la transmitancia térmica de los cerramientos opacos que forman parte de la envolvente térmica (en W/m²K).*' '\n\n- Suma de superficies en cubierta (m²). *Total de las superficies de cubierta en contacto con el exterior y que forman parte de la envolvente térmica (en m²).*' '\n\n- Transmitancia térmica media en cubiertas (W/m²K). *Valor medio de la transmitancia térmica de las superficies de cubierta que forman parte de la envolvente térmica (en W/m²K).*' '\n\n- Suma de superficies en huecos (m²). *Total de las superficies de los huecos en contacto con el exterior y que forman parte de la envolvente térmica (en m²).*' '\n\n- Transmitancia térmica media en huecos (W/m²K). *Valor medio de la transmitancia térmica de las superficies de los huecos que forman parte de la envolvente térmica (en W/m²K).*' '\n\n- Factor solar promedio en huecos (g). *Valor medio del factor solar de las superficies acristaladas que forman parte de la envolvente térmica (g es un valor adimensional entre 0 y 1).*' '\n\n- Suma de longitudes con puentes térmicos (metros). *Total de las longitudes de los puentes térmicos en contacto con el exterior y que forman parte de la envolvente térmica (en metros).*' '\n\n- Transmitancia térmica media lineal en puentes térmicos (W/mK). *Valor medio de la transmitancia térmica de los puentes térmicos que forman parte de la envolvente térmica (en W/mK).*' '\n\n- Tipo de instalación para calefacción. *Se definen 6 posibles casos de instalaciones de calefacción: Sin definir, Efecto Joule, Caldera Estándar, Bomba de calor, Caldera de condensación, y Otros sistemas.*' '\n\n- Tipo de instalación para refrigeración. *Se definen 4 posibles casos de instalaciones de refrigeración: Sin definir, Maquina frigorífica, Bomba de calor, y Otros sistemas.*' '\n\n- Reducc_EPNoR (kWh/m²∙año). *Producción de energía renovable (en kWh/m²∙año).*' ) new_prediction = predict_model(final_model, data=df.iloc[[-1]]) predict = (new_prediction.iloc[0]['Label']) predict = np.round_(np.exp(predict), decimals=1) st.subheader('Predicción del Consumo de energía no renovable') st.write('Consumo de Energía ESTIMADO: **{:.1f}** kWh/m²año'.format(predict)) def plot_escala_letras(results, category_names, line_value): line_value = line_value labels = list(results.keys()) data = np.array(list(results.values())) data_cum = data.cumsum(axis=1) category_colors = plt.get_cmap('RdYlGn_r')(np.linspace( 0.15, 0.85, data.shape[1]))
Inc_Max = st.sidebar.number_input('Inclinacion Máxima De Todo El Pozo (Deg)', min_value=0,value=3,max_value=100) # Comenzamos con el tratamiento de la data de entrada Data = pd.DataFrame( {"Num BHA": SL_BHA, "MD": MD, "TVD": TVD, "DLS Mean": DLS_Mean, "Azi Mean": Azi_Mean, "Inc Max" : Inc_Max, "Azi Max": Azi_Max, "MW": SL_MW, "Duracion": Duracion*24, "Tipo Pozo": SB_Pozo, }, index=[0] ) # load the model from disk model = load_model('Model_NPT') # Realizar la Prediccion y_pred = predict_model(model,data=Data).Label st.subheader("El NPT Total De Tu Pozo Será: %.3f (Hrs)" % y_pred) image = Image.open('Image.jpg') st.image(image)