numpy.vstack丢失精度float16
我正在尝试使用仅作为精确数字的数字进行线性回归的精确计算。没有numpy,它的工作正常,但是对于大量项目,numpy的性能更好,这就是为什么我需要使用numpy。 但是问题是,当我为X轴构建矩阵时,我会看到Bellow时失去了小数的精度。
我该如何修复?我的意思是,对于矩阵变量,仅返回一个数字作为精确的数字。
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
I'm trying to perform a precise calculation for linear regression using only one digit as precise number. without numpy it works just fine but numpy performs better for large amount of items that's why I need use numpy.
But the issue is that when I build the matrix for the X axis I lose my decimal precision as you can see bellow.
How can I fix it? I mean, to the matrix variable return only one digit as precise number.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要控制
dtype
在condenate
(以及所有'stack')中,参数必须匹配:nones
的默认dtype isfloat64 < /code>:
但是如注释中所述,使用
float16
在表面上是一个圆形。转置不会更改值或dtype。
To control
dtype
inconcatenate
(and all 'stack'), the arguments have to match:Default dtype for
ones
isfloat64
:But as noted in the comments, use of
float16
is only superficially a rounding.The transpose does not change values or dtype.