我只想對那些高于閾值的值應用計算。使用布爾索引完成后,值會四舍五入。如何預防?
starting_score = 1
threshold = 5
x = np.array([0,1,2,3,4,5,6,7,8,9,10])
gt_idx = x > threshold
le_idx = x <= threshold
decay = math.log(2) / 10
y = starting_score * np.exp(-decay * x)
x[gt_idx] = starting_score * np.exp(-decay * x[gt_idx])
y
array([1. , 0.93303299, 0.87055056, 0.8122524 , 0.75785828,
0.70710678, 0.65975396, 0.61557221, 0.57434918, 0.53588673,
0.5 ])
x
array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0])
當應用于完整陣列時,我得到正確的y陣列。當應用于 x 的一部分時,值會被正確選擇,但四舍五入為 0
我的預期輸出是
array([0, 1, 2, 3, 4, 5, 0.65975396, 0.61557221, 0.57434918, 0.53588673, 0.5])
uj5u.com熱心網友回復:
np.int32當您使用整數創建 NumPy 陣列時,它被視為默認型別x。要在結果中獲取其他型別,您有兩種方法:
# np.float32 or np.float64
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float64) # way 1
x = x.astype(np.float64) # way 2
不需要這樣的操作,y因為 in 乘以一個浮點型別值 ie np.exp(-decay * x),所以它變成了浮點型別。
uj5u.com熱心網友回復:
numpy 自動將整數資料型別分配給x. 要保留您的浮點數,您需要更改x陣列的型別
x.dtype
# Out: dtype('int64')
x = x.astype('float64')
或宣告x為一個陣列float64
x = np.array([0,1,2,3,4,5,6,7,8,9,10], dtype='float64')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/448672.html
上一篇:根據元素與給定值的距離排列串列
下一篇:numpy中未定義變數
