Streamlit为什么不显示我的模型预测?

huangapple go评论112阅读模式
英文:

Why Streamlit does not show me my model prediction?

问题

我正在构建一个Streamlit应用程序,以进行欺诈预测。思路是当用户输入所需信息时,应用程序会显示交易是否是欺诈。然而,每次尝试时,它都不显示任何预测,而是返回到主页。下面是我的代码:

  1. if col2.button('Manual Data Entry'):
  2. # Within the context of the form
  3. with st.form('Manual Data Entry'):
  4. # Transaction day selection
  5. day = st.slider('Transaction Day', 1, 31)
  6. # Input box for hours
  7. hour = st.slider('Transaction Hour', 1, 24)
  8. # Input box for amount
  9. amount = st.number_input('Transaction Amount', min_value=1)
  10. # Input box for cash withdrawal
  11. type_CASH_OUT = st.radio("Is it a cash withdrawal?", ('Yes', 'No'))
  12. # Input box for transfers
  13. type_TRANSFER = st.radio("Is it a transfer?", ('Yes', 'No'))
  14. # Input box for who initiates the transaction
  15. nameorig_C = st.radio("Who initiates the transaction?", ('Customer', 'Merchant'))
  16. # Input box for beneficiary
  17. namedest_C = st.radio("Is the beneficiary another customer?", ('Yes', 'No'))
  18. # Input box for beneficiary
  19. namedest_M = st.radio("Is the beneficiary a merchant?", ('Yes', 'No'))
  20. submitted = st.form_submit_button("Submit")
  21. if submitted:
  22. X_test = pd.DataFrame({
  23. 'day': [day],
  24. 'hour': [hour],
  25. 'amount': [amount],
  26. 'type_CASH_OUT': [type_CASH_OUT],
  27. 'type_TRANSFER': [type_TRANSFER],
  28. 'nameorig_C': [nameorig_C],
  29. 'namedest_C': [namedest_C],
  30. 'namedest_M': [namedest_M]
  31. })
  32. # Print test data
  33. st.write("Test Data:")
  34. st.write(X_test)
  35. # 2. Perform data transformations
  36. # Load PCA and scaler
  37. pca_path = 'C:/Users/lydia/OneDrive/Escritorio/Proyecto final_fraude/src/modelos/pca.pkl'
  38. scaler_path = 'C:/Users/lydia/OneDrive/Escritorio/Proyecto final_fraude/src/modelos/scaler.pkl'
  39. # Scale
  40. scaler = pickle.load(open(scaler_path, 'rb'))
  41. scaled_X_test = scaler.transform(X_test)
  42. # PCA
  43. pca = pickle.load(open(pca_path, 'rb'))
  44. X_test_pca = pd.DataFrame(pca.transform(scaled_X_test), columns=['PC1', 'PC2', 'PC3', 'PC4', 'PC5'])
  45. # Print transformed data
  46. st.write("Transformed Data (X_test_pca):")
  47. st.write(X_test_pca)
  48. # 3. Load the model and other related objects
  49. my_model = pickle.load(open('C:/Users/lydia/OneDrive/Escritorio/Proyecto final_fraude/src/modelos/my_model.pkl', 'rb'))
  50. # 4. Make predictions using the model and transformed data
  51. y_pred = my_model.predict(X_test_pca)
  52. # Print the prediction
  53. st.write("Prediction (y_pred):")
  54. st.write(y_pred)
  55. # Get the prediction label
  56. prediction_label = "It's a fraudulent transaction" if y_pred[0] == 1 else "It's a safe transaction"
  57. # Show the prediction result to the user
  58. st.write("Prediction Result:", prediction_label)

我尝试了不同的方法,在"if submitted:"之后注释整个代码,以检查是否可以打印"谢谢"之类的内容,但没有成功。

英文:

I'm building a Streamlit app in order to make fraud predictions. The idea is that when the user inputs the requested information, the app shows the if the transaction is a fraud or not.However, every time I try it, it does not show me any predictions, but it returns to the main page instead. Below you can see my code :

`if col2.button('Entrada manual de datos'):
# Dentro del contexto del formulario
with st.form('Entrada manual de datos'):
# Selección del día de la transacción
day = st.slider('Día de la transacción', 1, 31)

  1. # Caja de entrada para números
  2. hour = st.slider('Hora de la transacción', 1, 24)
  3. # Caja de entrada para cantidad
  4. amount = st.number_input('Cantidad de la transacción', min_value=1)
  5. # Caja de entrada para retirada de fondos
  6. type_CASH_OUT = st.radio("¿Es una retirada de fondos?", ('Sí', 'No'))
  7. # Caja de entrada para transferencias
  8. type_TRANSFER = st.radio("¿Es una transferencia?", ('Sí', 'No'))
  9. # Caja de entrada para quien inicia la transacción
  10. nameorig_C = st.radio("¿Quién origina la transacción?", ('Cliente', 'Comercio'))
  11. # Caja de entrada para beneficiario
  12. namedest_C = st.radio("¿El beneficiario de la transacción es otro cliente?", ('Sí', 'No'))
  13. # Caja de entrada para beneficiario
  14. namedest_M = st.radio("¿El beneficiario de la transacción es un comercio?", ('Sí', 'No'))
  15. submitted = st.form_submit_button("Submit")
  16. if submitted:
  17. X_test = pd.DataFrame({
  18. 'day': [day],
  19. 'hour': [hour],
  20. 'amount': [amount],
  21. 'type_CASH_OUT': [type_CASH_OUT],
  22. 'type_TRANSFER': [type_TRANSFER],
  23. 'nameorig_C': [nameorig_C],
  24. 'namedest_C': [namedest_C],
  25. 'namedest_M': [namedest_M]
  26. })
  27. # Imprimir los datos de prueba
  28. st.write("Datos de prueba:")
  29. st.write(X_test)
  30. # 2. Realizar transformaciones de los datos
  31. # Cargamos el PCA y el scaler
  32. ruta_pca = 'C:/Users/lydia/OneDrive/Escritorio/Proyecto final_fraude/src/modelos/pca.pkl'
  33. ruta_scaler = 'C:/Users/lydia/OneDrive/Escritorio/Proyecto final_fraude/src/modelos/scaler.pkl'
  34. # Escalamos
  35. scaler = pickle.load(open(ruta_scaler, 'rb'))
  36. scaled_X_test = scaler.transform(X_test)
  37. # PCA
  38. pca = pickle.load(open(ruta_pca, 'rb'))
  39. X_test_pca = pd.DataFrame(pca.transform(scaled_X_test), columns=['PC1', 'PC2', 'PC3', 'PC4', 'PC5'])
  40. # Imprimir los datos transformados
  41. st.write("Datos transformados (X_test_pca):")
  42. st.write(X_test_pca)
  43. # 3. Cargar el modelo y otros objetos relacionados
  44. my_model = pickle.load(open('C:/Users/lydia/OneDrive/Escritorio/Proyecto final_fraude/src/modelos/my_model.pkl', 'rb'))
  45. # 4. Realizar predicción utilizando el modelo y los datos transformados
  46. y_pred = my_model.predict(X_test_pca)
  47. # Imprimir la predicción
  48. st.write("Predicción (y_pred):")
  49. st.write(y_pred)
  50. # Obtener la etiqueta de predicción
  51. prediction_label = "Es una transacción fraudulenta" if y_pred[0] == 1 else "Es una transacción segura"
  52. # Mostrar el resultado de la predicción al usuario
  53. st.write("Resultado de la predicción:", prediction_label)`

I've tried different to comment the whole code after " if submitted:" to check if it could print like "thank you", but it couldn't.

答案1

得分: 1

根据我对你的代码的猜测,submitted 对象在一个代码块中被定义(因为代码行有缩进),是吗?
如果是这样的话,你需要使用 session_state

尝试替换:

  1. submitted = st.form_submit_button("Submit")
  2. if submitted:

为:

  1. st.session_state["submitted"] = st.form_submit_button("Submit")
  2. if st.session_state["submitted"]:
英文:

From what I can guess in your code, submitted object is defined in a block (as lines are indented), right ?
If that's the case, you need to use session_state.

Try to replace:

  1. submitted = st.form_submit_button("Submit")
  2. if submitted:

by:

  1. st.session_state["submitted"] = st.form_submit_button("Submit")
  2. if st.session_state["submitted"]:

huangapple
  • 本文由 发表于 2023年7月20日 21:43:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76730526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定