[英]numpy.vstack losing precision float16
我正在嘗試僅使用一位數字作為精確數字來執行線性回歸的精確計算。 沒有 numpy 它工作得很好,但 numpy 對大量項目表現更好,這就是我需要使用 numpy 的原因。 但問題是,當我為 X 軸構建矩陣時,我失去了十進制精度,如下所示。
我該如何解決? 我的意思是,矩陣變量只返回一位作為精確數字。
import numpy as np
import pandas as pd
dataset = [[17.3,71.7],[19.3,48.3],[19.5,88.3]]
df = pd.DataFrame({
'force': [item[0] for item in dataset],
'push_up':[item[1] for item in dataset]
})
df_x = np.array([item for item in df['force']],dtype=np.float16)
df_y = np.array([item for item in df['push_up']],dtype=np.float16)
print([np.round(item, decimals=1) for item in df['force']])
#check precision
#here is the issue! the return lose my 1 decimal point precision.
# notice !No matter if I use this printed array above.
# also tried using this array construction to reconvert to 1 decimal precision but no success
#print( [np.float16(np.format_float_positional(item, precision=1)) for item in df['force']] )
matrix = np.vstack([df_x, np.ones(len(df_x))]).T
print(matrix[0][0])
#this print "17.296875" that is totally different from 17.3
#print(matrix[2][0]) #uncomment this to see that the half precision is not lost at all
要控制concatenate
(以及所有“堆棧”)中的dtype
,參數必須匹配:
In [274]: np.vstack([np.array([1,2,3], 'float16'), np.ones(3,'float16')])
Out[274]:
array([[1., 2., 3.],
[1., 1., 1.]], dtype=float16)
ones
默認 dtype 是float64
:
In [275]: np.vstack([np.array([1,2,3], 'float16'), np.ones(3)])
Out[275]:
array([[1., 2., 3.],
[1., 1., 1.]])
In [276]: _.dtype
Out[276]: dtype('float64')
但正如評論中所指出的,使用float16
只是表面上的四舍五入。
In [278]: np.vstack([np.array([1.234235,2.9999,3], 'float16'), np.ones(3,'float16')])
Out[278]:
array([[1.234, 3. , 3. ],
[1. , 1. , 1. ]], dtype=float16)
轉置不會更改值或 dtype。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.