[英]While infinite loop python
我理解這里發生了什么,我只想知道在進入無限循環之前如何捕捉我的程序。 這是我的代碼:
while abs(error) > 50:
if Co > To:
c = c + 0.1
else:
c = c - 0.1
##Here I recalculate Co, the function is Co = 1/b type curve
##Here I recalculate To, the function is To = e^b type curve
error = Co - To
問題在於,根據問題,我有時需要更精確(我需要將迭代線更改為例如c + 0.00001),因為錯誤會從低於50的值跳轉到每個循環上超過50的值。 我怎么能抓住這樣一個無限循環。
我想這是一個收斂的問題。 我的數學foo現在讓我失望了一些,但是如果你擔心你可能最終處於一個你可能無法收斂的位置,你可以在你的循環中添加一些計數器。
limit = 1000
while abs(error) > 50:
limit -= 1
if limit == 0:
raise SomeError
your_calcs
它有點殘酷,但至少它解決了懸掛的問題。 聽起來好像你無法保證這個循環會因為不斷變化的代碼/數據的性質而完成。 如果發生無限循環情況,我想看到一個錯誤,所以我可以調查它。 真的取決於你的問題域。
如果我理解你的要求,我認為你正在尋找某種自適應學習率,就像你可能會看到應用於ANN中的梯度下降法,以及如果事情不再改善就停止的方法。
基本的想法是,當你沒有看到abs誤差的變化同時保持整個過程的穩定性時,慢慢減少擾亂你的值的數量。 如果你降低了你的學習率並且你仍然沒有看到任何改善,那么你已經完成了(或至少在某種地方最低限度)。 這個方法可能會慢一點,並且有不同的方法來計算我輸入的變量(例如,sigErrChange),所以你必須稍微玩弄它。 還有其他一些我無法想到的警告,但希望這能得到一般的想法。
例如,
lR = 1.0
updatedLR = False # Have we updated the learning rate this iteration?
while abs(error) > 50 and ( sigErrChange or updatedLR ):
sigErrChange = False # Has there been a significant improvement in the error? (Probably shouldn't just use a single iteration for this...)
# Are we adding or subtracting
if C > T:
sign = 1.
else:
sign = -1.
# Should we update the learning rate?
if (~sigErrChange)
updatedLR = True
lR = .95 * lR
# Calculate our values
c = c + sign*lR*.001
C = calcC(c, C, T)
T = calcT(c, C, T)
error = C - T
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.