jjzjj

python - Numpy.dot 错误?不一致的 NaN 行为

coder 2023-08-19 原文

当涉及到 nan 和 zeros 时,我注意到 numpy.dot 中存在不一致的行为。

有人能理解它吗?这是一个错误吗?这是否特定于 dot 函数?

我正在使用 numpy v1.6.1,64 位,在 linux 上运行(也在 v1.6.2 上测试过)。我还在 32 位 Windows 上的 v1.8.0 上进行了测试(所以我无法判断差异是由于版本、操作系统还是 arch 造成的)。

from numpy import *
0*nan, nan*0
=> (nan, nan)  # makes sense

#1
a = array([[0]])
b = array([[nan]])
dot(a, b)
=> array([[ nan]])  # OK

#2 -- adding a value to b. the first value in the result is
#     not expected to be affected.
a = array([[0]])
b = array([[nan, 1]])
dot(a, b)
=> array([[ 0.,  0.]])  # EXPECTED : array([[ nan,  0.]])
# (also happens in 1.6.2 and 1.8.0)
# Also, as @Bill noted, a*b works as expected, but not dot(a,b)

#3 -- changing a from 0 to 1, the first value in the result is
#     not expected to be affected.
a = array([[1]])
b = array([[nan, 1]])
dot(a, b)
=> array([[ nan,   1.]])  # OK

#4 -- changing shape of a, changes nan in result
a = array([[0],[0]])
b = array([[ nan, 1.]])
dot(a, b)
=> array([[ 0.,  0.], [ 0.,  0.]])  # EXPECTED : array([[ nan,  0.], [ nan,  0.]])
# (works as expected in 1.6.2 and 1.8.0)

案例 #4 似乎在 v1.6.2 和 v1.8.0 中正常工作,但案例 #2 则不然...


编辑:@seberg 指出这是一个 blas 问题,所以这是我通过运行 from numpy.distutils.system_info import get_info; 找到的关于 blas 安装的信息; get_info('blas_opt'):

1.6.1 linux 64bit
/usr/lib/python2.7/dist-packages/numpy/distutils/system_info.py:1423: UserWarning: 
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  warnings.warn(AtlasNotFoundError.__doc__)
{'libraries': ['blas'], 'library_dirs': ['/usr/lib'], 'language': 'f77', 'define_macros': [('NO_ATLAS_INFO', 1)]}

1.8.0 windows 32bit (anaconda)
c:\Anaconda\Lib\site-packages\numpy\distutils\system_info.py:1534: UserWarning:
   Blas (http://www.netlib.org/blas/) sources not found.
   Directories to search for the sources can be specified in the
   numpy/distutils/site.cfg file (section [blas_src]) or by setting
   the BLAS_SRC environment variable.
 warnings.warn(BlasSrcNotFoundError.__doc__)
{}

(我个人不知道该怎么做)

最佳答案

我认为,正如 seberg 所建议的,这是所使用的 BLAS 库的问题。如果你看看 numpy.dot 是如何实现的 herehere对于 double 矩阵乘以矩阵的情况,您会发现对 cblas_dgemm() 的调用。

此 C 程序重现了您的一些示例,在使用“普通”BLAS 时给出相同的输出,在使用 ATLAS 时给出正确答案。

#include <stdio.h>
#include <math.h>

#include "cblas.h"

void onebyone(double a11, double b11, double expectc11)
{
  enum CBLAS_ORDER order=CblasRowMajor;
  enum CBLAS_TRANSPOSE transA=CblasNoTrans;
  enum CBLAS_TRANSPOSE transB=CblasNoTrans;
  int M=1;
  int N=1;
  int K=1;
  double alpha=1.0;
  double A[1]={a11};
  int lda=1;
  double B[1]={b11};
  int ldb=1;
  double beta=0.0;
  double C[1];
  int ldc=1;

  cblas_dgemm(order, transA, transB,
              M, N, K,
              alpha,A,lda,
              B, ldb,
              beta, C, ldc);

  printf("dot([ %.18g],[%.18g]) -> [%.18g]; expected [%.18g]\n",a11,b11,C[0],expectc11);
}

void onebytwo(double a11, double b11, double b12,
              double expectc11, double expectc12)
{
  enum CBLAS_ORDER order=CblasRowMajor;
  enum CBLAS_TRANSPOSE transA=CblasNoTrans;
  enum CBLAS_TRANSPOSE transB=CblasNoTrans;
  int M=1;
  int N=2;
  int K=1;
  double alpha=1.0;
  double A[]={a11};
  int lda=1;
  double B[2]={b11,b12};
  int ldb=2;
  double beta=0.0;
  double C[2];
  int ldc=2;

  cblas_dgemm(order, transA, transB,
              M, N, K,
              alpha,A,lda,
              B, ldb,
              beta, C, ldc);

  printf("dot([ %.18g],[%.18g, %.18g]) -> [%.18g, %.18g]; expected [%.18g, %.18g]\n",
         a11,b11,b12,C[0],C[1],expectc11,expectc12);
}

int
main()
{
  onebyone(0, 0, 0);
  onebyone(2, 3, 6);
  onebyone(NAN, 0, NAN);
  onebyone(0, NAN, NAN);
  onebytwo(0, 0,0, 0,0);
  onebytwo(2, 3,5, 6,10);
  onebytwo(0, NAN,0, NAN,0);
  onebytwo(NAN, 0,0, NAN,NAN);
  return 0;
}

使用 BLAS 的输出:

dot([ 0],[0]) -> [0]; expected [0]
dot([ 2],[3]) -> [6]; expected [6]
dot([ nan],[0]) -> [nan]; expected [nan]
dot([ 0],[nan]) -> [0]; expected [nan]
dot([ 0],[0, 0]) -> [0, 0]; expected [0, 0]
dot([ 2],[3, 5]) -> [6, 10]; expected [6, 10]
dot([ 0],[nan, 0]) -> [0, 0]; expected [nan, 0]
dot([ nan],[0, 0]) -> [nan, nan]; expected [nan, nan]

用 ATLAS 输出:

dot([ 0],[0]) -> [0]; expected [0]
dot([ 2],[3]) -> [6]; expected [6]
dot([ nan],[0]) -> [nan]; expected [nan]
dot([ 0],[nan]) -> [nan]; expected [nan]
dot([ 0],[0, 0]) -> [0, 0]; expected [0, 0]
dot([ 2],[3, 5]) -> [6, 10]; expected [6, 10]
dot([ 0],[nan, 0]) -> [nan, 0]; expected [nan, 0]
dot([ nan],[0, 0]) -> [nan, nan]; expected [nan, nan]

当第一个操作数为 NaN 时,BLAS 似乎有预期的行为,而当第一个操作数为零而第二个操作数为 NaN 时,BLAS 似乎有预期的行为。

无论如何,我认为这个错误不在 Numpy 层中;它在 BLAS 中。似乎可以通过使用 ATLAS 来解决。

以上在 Ubuntu 14.04 上生成,使用 Ubuntu 提供的 gcc、BLAS 和 ATLAS。

关于python - Numpy.dot 错误?不一致的 NaN 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23374524/

有关python - Numpy.dot 错误?不一致的 NaN 行为的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  3. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  4. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  5. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  6. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  7. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  8. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  9. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  10. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

随机推荐