如何在每次 运行 回调或 运行 服务器时保持随机样本结果相同?
how to keep random sample result the same each time running callback or running server?
在我的回调中,有一个函数。在该函数中,我需要使用 random.sample(list, 10)
在一个循环中每次绘制 10 个样本。因此,我在 random.sample(list, 10)
.
循环之前的函数内部使用 random.seed(400)
每次运行回调时,样本都不一样。我不确定如何使随机样本相同。谢谢
def find_best(df,N_calculation):
random.seed(400)
for n_cal in tnrange(N_calculation):
RISKY_ASSETS = random.sample(stock_list_portfolio, n_assets)
回调中
@app.callback(
[
Output("portfolio-graph", "figure"),
],
[
Input('run-portfolio','n_clicks')
],
[
State('portfolio-data-year-num-slider','value'),
State('portfolio-opt-calc-log-num-slider','value'),
],
prevent_initial_call=True, # disable output in the first load
)
def change_portfolio(n_clicks,delta_year,n_calculation_log):
RISKY_ASSETS_BEST= find_best(df,N_calculation)
您所描述的内容应该有效,除非每次调用时输入 stock_list_portfolio
到 random.sample()
都不同。这是一个示例,它将使用 sample
和 seed
:
从列表中打印确定的元素集
import random
import dash
from dash import html
from dash.dependencies import Input, Output
app = dash.Dash()
app.layout = html.Div(
[
html.Div([html.P(id="paragraph_id", children=["Button not clicked"])]),
html.Button(id="button_id", children="Run smapler"),
]
)
@app.callback(
[Output("paragraph_id", "children")],
[Input("button_id", "n_clicks")],
prevent_initial_call=True,
)
def callback(_):
random.seed(4)
res_list = ""
df= [1,2,3,4,5,6]
for n_cal in range(4):
RISKY_ASSETS = random.sample(df, n_cal)
res_list += f"{RISKY_ASSETS}"
return [res_list]
if __name__ == "__main__":
app.run_server(debug=True)
在我的回调中,有一个函数。在该函数中,我需要使用 random.sample(list, 10)
在一个循环中每次绘制 10 个样本。因此,我在 random.sample(list, 10)
.
random.seed(400)
每次运行回调时,样本都不一样。我不确定如何使随机样本相同。谢谢
def find_best(df,N_calculation):
random.seed(400)
for n_cal in tnrange(N_calculation):
RISKY_ASSETS = random.sample(stock_list_portfolio, n_assets)
回调中
@app.callback(
[
Output("portfolio-graph", "figure"),
],
[
Input('run-portfolio','n_clicks')
],
[
State('portfolio-data-year-num-slider','value'),
State('portfolio-opt-calc-log-num-slider','value'),
],
prevent_initial_call=True, # disable output in the first load
)
def change_portfolio(n_clicks,delta_year,n_calculation_log):
RISKY_ASSETS_BEST= find_best(df,N_calculation)
您所描述的内容应该有效,除非每次调用时输入 stock_list_portfolio
到 random.sample()
都不同。这是一个示例,它将使用 sample
和 seed
:
import random
import dash
from dash import html
from dash.dependencies import Input, Output
app = dash.Dash()
app.layout = html.Div(
[
html.Div([html.P(id="paragraph_id", children=["Button not clicked"])]),
html.Button(id="button_id", children="Run smapler"),
]
)
@app.callback(
[Output("paragraph_id", "children")],
[Input("button_id", "n_clicks")],
prevent_initial_call=True,
)
def callback(_):
random.seed(4)
res_list = ""
df= [1,2,3,4,5,6]
for n_cal in range(4):
RISKY_ASSETS = random.sample(df, n_cal)
res_list += f"{RISKY_ASSETS}"
return [res_list]
if __name__ == "__main__":
app.run_server(debug=True)