SlideShare una empresa de Scribd logo
1 de 6
Descargar para leer sin conexión
Q3: Sum with NaN and Inf

nanやInfを含む値の列x = numpy.array([[1,0,nan,1,Inf,1,....]])が与えられたとき、NaNやInf以外のx の要素の合計を計算す
る方法が直ぐに思い浮かびますか?


  In [1]: # 準備
          i m p o r t numpy
          i m p o r t numpy a s np
          x = numpy.array([[1,0,nan,1,Inf,1]])
          x

  Out[1]: array([[    1.,    0.,   nan,    1.,   inf,    1.]])


  In [2]: # 回答者1
          x[isnan(x)]=0
          x[isinf(x)]=0
          sum(x)

  Out[2]: 3.0


  In [3]: % timeit x[isnan(x)]=0
          % timeit x[isinf(x)]=0
          % timeit sum(x)

           100000 loops, best of 3: 4.47 us per loop
           100000 loops, best of 3: 4.31 us per loop
           100000 loops, best of 3: 3.46 us per loop

  In [4]: # 回答者2
           # どういうときに Inf を除きたいのかわからないけど
           sum_with_finite = x[numpy.isfinite(x)].sum()
           sum_with_finite
           # NaN を除くだけなら sum_without_nan = numpy.nansum(x)

  Out[4]: 3.0


  In [5]: % timeit x[numpy.isfinite(x)].sum()

           100000 loops, best of 3: 7.47 us per loop

  In [6]: # 回答者4
          sum(filter(l a m b d a x: x! = float('inf') a n d x= = x, x[0]))
                     l               !                       =

  Out[6]: 3.0


  In [7]: % timeit sum(filter(l a m b d a x: x! = float('inf') a n d x= = x, x[0]))
                              l               !                       =

           10000 loops, best of 3: 39 us per loop

  In [8]: # 回答者5
          np.nansum(x[x! = np.inf])
                       !

  Out[8]: 3.0
Out[8]: 3.0


  In [9]: % timeit np.nansum(x[x! = np.inf])
                                !

          10000 loops, best of 3: 29.3 us per loop

 In [10]: # 回答者6
          x[numpy.isfinite(x)].sum()

 Out[10]: 3.0


 In [11]: % timeit x[numpy.isfinite(x)].sum()

          100000 loops, best of 3: 8.33 us per loop

 In [12]: # 回答者8
          numpy.sum(x[numpy.isfinite(x)])

 Out[12]: 3.0


 In [13]: % timeit numpy.sum(x[numpy.isfinite(x)])

          100000 loops, best of 3: 10.2 us per loop

 In [14]: # 回答者9
          np.sum(x[np.isfinite(x)])

 Out[14]: 3.0


 In [15]: % timeit np.sum(x[np.isfinite(x)])

          100000 loops, best of 3: 10.1 us per loop



Q4: Missing values in ndarray

nanを含む4x2行列m = numpy.array([[1,nan,-1,0],[0,0,nan,1]])が与えられたとき、nanを含む行を削除して2x2行列にする
方法が直ぐに思い浮かびますか?


 In [16]: # 準備
          i m p o r t numpy
          i m p o r t numpy a s np
          m = numpy.array([[1,nan,- 1,0],[0,0,nan,1]])
                                   -
          m

 Out[16]: array([[   1.,    nan,   -1.,   0.],
                 [   0.,     0.,   nan,   1.]])


 In [17]: # 回答者1
          delete(m,argmax(isnan(m),axis=1),axis=1)

 Out[17]: array([[ 1.,     0.],
                 [ 0.,     1.]])


 In [18]: % timeit delete(m,argmax(isnan(m),axis=1),axis=1)
In [18]: % timeit delete(m,argmax(isnan(m),axis=1),axis=1)

         10000 loops, best of 3: 110 us per loop

In [19]: # 回答者2
         selected_m = m[:,numpy.isfinite(m.sum(axis=0))]
         selected_m

Out[19]: array([[ 1.,   0.],
                [ 0.,   1.]])


In [20]: % timeit m[:,numpy.isfinite(m.sum(axis=0))]

         100000 loops, best of 3: 11.2 us per loop

In [21]: # 回答者4
         index = [xx f o r xx i n range(len(m[0])) i f sum(m[:,xx])= = sum(m[:,xx])]
                                                                   =
         m[:,index]

Out[21]: array([[ 1.,   0.],
                [ 0.,   1.]])


In [22]: % timeit index = [xx f o r xx i n range(len(m[0])) i f sum(m[:,xx])= = sum(m[:,xx])]
                                                                            =
         % timeit m[:,index]

         10000 loops, best of 3: 38.9 us per loop
         100000 loops, best of 3: 12.8 us per loop

In [23]: # 回答者6
         nans = logical_or(isnan(m[0]), isnan(m[1]))
         mask = tile(logical_not(nans), (2,1))
         res = m[mask].reshape(2,2)
         res

Out[23]: array([[ 1.,   0.],
                [ 0.,   1.]])


In [24]: % timeit nans = logical_or(isnan(m[0]), isnan(m[1]))
         % timeit mask = tile(logical_not(nans), (2,1))
         % timeit res = m[mask].reshape(2,2)

         100000 loops, best of 3: 5.46 us per loop
         100000 loops, best of 3: 13.2 us per loop
         100000 loops, best of 3: 4.46 us per loop

In [25]: # 回答者8
         m[:,numpy.apply_along_axis(numpy.all,0,numpy.isfinite(m))]

Out[25]: array([[ 1.,   0.],
                [ 0.,   1.]])


In [26]: % timeit m[:,numpy.apply_along_axis(numpy.all,0,numpy.isfinite(m))]

         1000 loops, best of 3: 160 us per loop

In [27]: # 回答者9
         m[:, np.isfinite(np.sum(m, axis=0))]

Out[27]: array([[ 1.,   0.],
Out[27]: array([[ 1.,      0.],
                 [ 0.,      1.]])


 In [28]: % timeit m[:, np.isfinite(np.sum(m, axis=0))]

           100000 loops, best of 3: 12.8 us per loop



Q5: 1-of-K representation

numpy.array([[1,3,2]])を、1-of-K表記法変換してnumpy.array([[1,0,0],[0,0,1],[0,1,0]])にする処理方法が直ぐに思い浮か
びますか?


 In [29]: # 準備
          i m p o r t numpy
          i m p o r t numpy a s np
          y = numpy.array([[1,3,2]])
          y

 Out[29]: array([[1, 3, 2]])


 In [30]: #回答者1
          t = numpy.array([1,3,2])
           # pattern 1
           z = numpy.fromfunction(l a m b d a i,j:j= = t[i]- 1,(t.size,t.max()),dtype=int)+ 0
                                  l                =       -                              +
           p r i n t (z)
           # pattern 2
           z = numpy.array([numpy.identity(t.max())[x- 1,:] f o r x i n t])
                                                     -
           p r i n t (z)
           # pattern 3(numpy 1.6 以降)
           z = numpy.array([numpy.bincount([x- 1],minlength=t.max()) f o r x i n t])
                                             -
           p r i n t (z)

           [[1 0   0]
            [0 0   1]
            [0 1   0]]
           [[ 1.    0.   0.]
            [ 0.    0.   1.]
            [ 0.    1.   0.]]
           [[1 0   0]
            [0 0   1]
            [0 1   0]]

 In [31]: % timeit z = numpy.fromfunction(l a m b d a i,j:j= = t[i]- 1,(t.size,t.max()),dtype=int)+ 0
                                          l                =       -                              +
          % timeit z = numpy.array([numpy.identity(t.max())[x- 1,:] f o r x i n t])
                                                                   -
          % timeit z = numpy.array([numpy.bincount([x- 1],minlength=t.max()) f o r x i n t])
                                                         -

           10000 loops, best of 3: 61.7 us per loop
           10000 loops, best of 3: 55.3 us per loop
           10000 loops, best of 3: 65.6 us per loop

 In [32]: #回答者2
          N=y.shape[1]
          yy=zeros(N* * 2)
                     *
          yy[N* arange(N)+ y- 1]=1 #編集者注:yy[N*arange(N)+y-1].reshape(N,N)では動かず
              *           + -
          yy.reshape(N,N)
Out[32]: array([[ 1.,    0.,   0.],
                [ 0.,    0.,   1.],
                [ 0.,    1.,   0.]])


In [33]: % timeit   N=y.shape[1]
         % timeit   yy=zeros(N* * 2)
                               *
         % timeit   yy[N* arange(N)+ y- 1]=1 #編集者注:yy[N*arange(N)+y-1].reshape(N,N)では動かず
                        *           + -
         % timeit   yy.reshape(N,N)


          10000000 loops, best of 3: 203 ns per loop
          1000000 loops, best of 3: 1.37 us per loop
          10000 loops, best of 3: 14.6 us per loop
          1000000 loops, best of 3: 846 ns per loop

In [34]: #回答者4
         K=3
         d e f my_func(i):
               z = numpy.zeros(K,dtype=int)
               z[i- 1] = 1
                  -
               return z
         numpy.array(map(my_func,y[0]))


Out[34]: array([[1, 0, 0],
                [0, 0, 1],
                [0, 1, 0]])


In [35]: % timeit numpy.array(map(my_func,y[0]))

          10000 loops, best of 3: 29.8 us per loop

In [36]: #回答者6
         res = zeros((3, 3))
         indices = [i* 3+ c- 1 f o r i, c i n enumerate(y[0])]
                     * + -
         res.put(indices, 1)
         res

Out[36]: array([[ 1.,    0.,   0.],
                [ 0.,    0.,   1.],
                [ 0.,    1.,   0.]])


In [37]: % timeit res = zeros((3, 3))
         % timeit indices = [i* 3+ c- 1 f o r i, c i n enumerate(y[0])]
                              * + -
         % timeit res.put(indices, 1)

          1000000 loops, best of 3: 814 ns per loop
          100000 loops, best of 3: 10.2 us per loop
          100000 loops, best of 3: 10.3 us per loop

In [38]: #回答者8
         numpy.fromfunction(l a m b d a i, j: numpy.array(y[0][i]= = j+ 1, dtype=int), (3, 3), dtype
                            l                                    = +


Out[38]: array([[1, 0, 0],
                [0, 0, 1],
                [0, 1, 0]])
In [39]: % timeit numpy.fromfunction(l a m b d a i, j: numpy.array(y[0][i]= = j+ 1, dtype=int), (3, 3
                                     l                                    = +


          10000 loops, best of 3: 44.3 us per loop

In [40]: #回答者9
          #これは逆の方が問題だな…
          ans = np.zeros((3, 3))
          ans[np.arange(3, dtype=np.int), y- 1] = 1 #編集者注:0-origin対応でy-1とした
                                           -
          ans

Out[40]: array([[ 1.,     0.,   0.],
                [ 0.,     0.,   1.],
                [ 0.,     1.,   0.]])


In [41]: % timeit ans = np.zeros((3, 3))
         % timeit ans[np.arange(3, dtype=np.int), y- 1] = 1
                                                   -

          1000000 loops, best of 3: 761 ns per loop
          100000 loops, best of 3: 7.97 us per loop



Q6: Useful snippets

In [45]: d e f _main():
               pass

          i f __name__= = _main():
                       =
               _main()

Más contenido relacionado

La actualidad más candente

Lesson 16: Derivatives of Exponential and Logarithmic Functions
Lesson 16: Derivatives of Exponential and Logarithmic FunctionsLesson 16: Derivatives of Exponential and Logarithmic Functions
Lesson 16: Derivatives of Exponential and Logarithmic FunctionsMatthew Leingang
 
Statistics for Economics Midterm 2 Cheat Sheet
Statistics for Economics Midterm 2 Cheat SheetStatistics for Economics Midterm 2 Cheat Sheet
Statistics for Economics Midterm 2 Cheat SheetLaurel Ayuyao
 
실용주의 머신러닝 CNN MNIST TENSORBOARD
실용주의 머신러닝 CNN MNIST TENSORBOARD실용주의 머신러닝 CNN MNIST TENSORBOARD
실용주의 머신러닝 CNN MNIST TENSORBOARDSeongHyun Ahn
 
Lesson 28: The Fundamental Theorem of Calculus
Lesson 28: The Fundamental Theorem of CalculusLesson 28: The Fundamental Theorem of Calculus
Lesson 28: The Fundamental Theorem of CalculusMatthew Leingang
 
Statistics for Economics Final Exam Cheat Sheet
Statistics for Economics Final Exam Cheat SheetStatistics for Economics Final Exam Cheat Sheet
Statistics for Economics Final Exam Cheat SheetLaurel Ayuyao
 
The width of an ideal chain
The width of an ideal chainThe width of an ideal chain
The width of an ideal chaincypztm
 
Using R Tool for Probability and Statistics
Using R Tool for Probability and Statistics Using R Tool for Probability and Statistics
Using R Tool for Probability and Statistics nazlitemu
 
Lesson 8: Derivatives of Polynomials and Exponential functions
Lesson 8: Derivatives of Polynomials and Exponential functionsLesson 8: Derivatives of Polynomials and Exponential functions
Lesson 8: Derivatives of Polynomials and Exponential functionsMatthew Leingang
 
Lesson 16: Derivatives of Logarithmic and Exponential Functions
Lesson 16: Derivatives of Logarithmic and Exponential FunctionsLesson 16: Derivatives of Logarithmic and Exponential Functions
Lesson 16: Derivatives of Logarithmic and Exponential FunctionsMatthew Leingang
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practiceindico data
 
Probabilistic Programming in Scala
Probabilistic Programming in ScalaProbabilistic Programming in Scala
Probabilistic Programming in ScalaBeScala
 
Glm talk Tomas
Glm talk TomasGlm talk Tomas
Glm talk TomasSri Ambati
 
Calculus B Notes (Notre Dame)
Calculus B Notes (Notre Dame)Calculus B Notes (Notre Dame)
Calculus B Notes (Notre Dame)Laurel Ayuyao
 
Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Khor SoonHin
 

La actualidad más candente (19)

Lesson 16: Derivatives of Exponential and Logarithmic Functions
Lesson 16: Derivatives of Exponential and Logarithmic FunctionsLesson 16: Derivatives of Exponential and Logarithmic Functions
Lesson 16: Derivatives of Exponential and Logarithmic Functions
 
Ism et chapter_3
Ism et chapter_3Ism et chapter_3
Ism et chapter_3
 
Statistics for Economics Midterm 2 Cheat Sheet
Statistics for Economics Midterm 2 Cheat SheetStatistics for Economics Midterm 2 Cheat Sheet
Statistics for Economics Midterm 2 Cheat Sheet
 
실용주의 머신러닝 CNN MNIST TENSORBOARD
실용주의 머신러닝 CNN MNIST TENSORBOARD실용주의 머신러닝 CNN MNIST TENSORBOARD
실용주의 머신러닝 CNN MNIST TENSORBOARD
 
Lesson 28: The Fundamental Theorem of Calculus
Lesson 28: The Fundamental Theorem of CalculusLesson 28: The Fundamental Theorem of Calculus
Lesson 28: The Fundamental Theorem of Calculus
 
Statistics for Economics Final Exam Cheat Sheet
Statistics for Economics Final Exam Cheat SheetStatistics for Economics Final Exam Cheat Sheet
Statistics for Economics Final Exam Cheat Sheet
 
The width of an ideal chain
The width of an ideal chainThe width of an ideal chain
The width of an ideal chain
 
Using R Tool for Probability and Statistics
Using R Tool for Probability and Statistics Using R Tool for Probability and Statistics
Using R Tool for Probability and Statistics
 
Lesson 8: Derivatives of Polynomials and Exponential functions
Lesson 8: Derivatives of Polynomials and Exponential functionsLesson 8: Derivatives of Polynomials and Exponential functions
Lesson 8: Derivatives of Polynomials and Exponential functions
 
Lesson 16: Derivatives of Logarithmic and Exponential Functions
Lesson 16: Derivatives of Logarithmic and Exponential FunctionsLesson 16: Derivatives of Logarithmic and Exponential Functions
Lesson 16: Derivatives of Logarithmic and Exponential Functions
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practice
 
Probabilistic Programming in Scala
Probabilistic Programming in ScalaProbabilistic Programming in Scala
Probabilistic Programming in Scala
 
MUMS Undergraduate Workshop - Quantifying Uncertainty in Hazard Forecasting -...
MUMS Undergraduate Workshop - Quantifying Uncertainty in Hazard Forecasting -...MUMS Undergraduate Workshop - Quantifying Uncertainty in Hazard Forecasting -...
MUMS Undergraduate Workshop - Quantifying Uncertainty in Hazard Forecasting -...
 
Glm talk Tomas
Glm talk TomasGlm talk Tomas
Glm talk Tomas
 
Calculus B Notes (Notre Dame)
Calculus B Notes (Notre Dame)Calculus B Notes (Notre Dame)
Calculus B Notes (Notre Dame)
 
Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2
 
Signals and Systems Assignment Help
Signals and Systems Assignment HelpSignals and Systems Assignment Help
Signals and Systems Assignment Help
 
Signals and Systems Assignment Help
Signals and Systems Assignment HelpSignals and Systems Assignment Help
Signals and Systems Assignment Help
 
Neural networks using tensor flow in amazon deep learning server
Neural networks using tensor flow in amazon deep learning serverNeural networks using tensor flow in amazon deep learning server
Neural networks using tensor flow in amazon deep learning server
 

Destacado

111015 tokyo scipy2_additionaldemo_pandas
111015 tokyo scipy2_additionaldemo_pandas111015 tokyo scipy2_additionaldemo_pandas
111015 tokyo scipy2_additionaldemo_pandasShohei Hido
 
ICML2013読み会 開会宣言
ICML2013読み会 開会宣言ICML2013読み会 開会宣言
ICML2013読み会 開会宣言Shohei Hido
 
今年のKDDベストペーパーを実装・公開しました
今年のKDDベストペーパーを実装・公開しました今年のKDDベストペーパーを実装・公開しました
今年のKDDベストペーパーを実装・公開しましたShohei Hido
 
ビッグデータはどこまで効率化できるか?
ビッグデータはどこまで効率化できるか?ビッグデータはどこまで効率化できるか?
ビッグデータはどこまで効率化できるか?Shohei Hido
 
Jubatusが目指すインテリジェンス基盤
Jubatusが目指すインテリジェンス基盤Jubatusが目指すインテリジェンス基盤
Jubatusが目指すインテリジェンス基盤Shohei Hido
 
機械学習CROSS 後半資料
機械学習CROSS 後半資料機械学習CROSS 後半資料
機械学習CROSS 後半資料Shohei Hido
 
NIPS2013読み会: More Effective Distributed ML via a Stale Synchronous Parallel P...
NIPS2013読み会: More Effective Distributed ML via a Stale Synchronous Parallel P...NIPS2013読み会: More Effective Distributed ML via a Stale Synchronous Parallel P...
NIPS2013読み会: More Effective Distributed ML via a Stale Synchronous Parallel P...Shohei Hido
 
プロダクトマネージャのお仕事
プロダクトマネージャのお仕事プロダクトマネージャのお仕事
プロダクトマネージャのお仕事Shohei Hido
 
PFIセミナー "「失敗の本質」を読む"発表資料
PFIセミナー "「失敗の本質」を読む"発表資料PFIセミナー "「失敗の本質」を読む"発表資料
PFIセミナー "「失敗の本質」を読む"発表資料Shohei Hido
 
Software for Edge Heavy Computing @ INTEROP 2016 Tokyo
Software for Edge Heavy Computing @ INTEROP 2016 TokyoSoftware for Edge Heavy Computing @ INTEROP 2016 Tokyo
Software for Edge Heavy Computing @ INTEROP 2016 TokyoShohei Hido
 
機械学習CROSS 前半資料
機械学習CROSS 前半資料機械学習CROSS 前半資料
機械学習CROSS 前半資料Shohei Hido
 
データサイエンティスト協会スキル委員会2ndシンポジウム講演資料
データサイエンティスト協会スキル委員会2ndシンポジウム講演資料データサイエンティスト協会スキル委員会2ndシンポジウム講演資料
データサイエンティスト協会スキル委員会2ndシンポジウム講演資料The Japan DataScientist Society
 
Chainer GTC 2016
Chainer GTC 2016Chainer GTC 2016
Chainer GTC 2016Shohei Hido
 
NIPS2015概要資料
NIPS2015概要資料NIPS2015概要資料
NIPS2015概要資料Shohei Hido
 
データサイエンティスト スキルチェックリスト
データサイエンティスト スキルチェックリストデータサイエンティスト スキルチェックリスト
データサイエンティスト スキルチェックリストThe Japan DataScientist Society
 
How AI revolutionizes robotics and automotive industries
How AI revolutionizes robotics and automotive industriesHow AI revolutionizes robotics and automotive industries
How AI revolutionizes robotics and automotive industriesShohei Hido
 
機械学習モデルフォーマットの話:さようならPMML、こんにちはPFA
機械学習モデルフォーマットの話:さようならPMML、こんにちはPFA機械学習モデルフォーマットの話:さようならPMML、こんにちはPFA
機械学習モデルフォーマットの話:さようならPMML、こんにちはPFAShohei Hido
 
あなたの業務に機械学習を活用する5つのポイント
あなたの業務に機械学習を活用する5つのポイントあなたの業務に機械学習を活用する5つのポイント
あなたの業務に機械学習を活用する5つのポイントShohei Hido
 
Jubatus Casual Talks #2 異常検知入門
Jubatus Casual Talks #2 異常検知入門Jubatus Casual Talks #2 異常検知入門
Jubatus Casual Talks #2 異常検知入門Shohei Hido
 
データサイエンティストのつくり方
データサイエンティストのつくり方データサイエンティストのつくり方
データサイエンティストのつくり方Shohei Hido
 

Destacado (20)

111015 tokyo scipy2_additionaldemo_pandas
111015 tokyo scipy2_additionaldemo_pandas111015 tokyo scipy2_additionaldemo_pandas
111015 tokyo scipy2_additionaldemo_pandas
 
ICML2013読み会 開会宣言
ICML2013読み会 開会宣言ICML2013読み会 開会宣言
ICML2013読み会 開会宣言
 
今年のKDDベストペーパーを実装・公開しました
今年のKDDベストペーパーを実装・公開しました今年のKDDベストペーパーを実装・公開しました
今年のKDDベストペーパーを実装・公開しました
 
ビッグデータはどこまで効率化できるか?
ビッグデータはどこまで効率化できるか?ビッグデータはどこまで効率化できるか?
ビッグデータはどこまで効率化できるか?
 
Jubatusが目指すインテリジェンス基盤
Jubatusが目指すインテリジェンス基盤Jubatusが目指すインテリジェンス基盤
Jubatusが目指すインテリジェンス基盤
 
機械学習CROSS 後半資料
機械学習CROSS 後半資料機械学習CROSS 後半資料
機械学習CROSS 後半資料
 
NIPS2013読み会: More Effective Distributed ML via a Stale Synchronous Parallel P...
NIPS2013読み会: More Effective Distributed ML via a Stale Synchronous Parallel P...NIPS2013読み会: More Effective Distributed ML via a Stale Synchronous Parallel P...
NIPS2013読み会: More Effective Distributed ML via a Stale Synchronous Parallel P...
 
プロダクトマネージャのお仕事
プロダクトマネージャのお仕事プロダクトマネージャのお仕事
プロダクトマネージャのお仕事
 
PFIセミナー "「失敗の本質」を読む"発表資料
PFIセミナー "「失敗の本質」を読む"発表資料PFIセミナー "「失敗の本質」を読む"発表資料
PFIセミナー "「失敗の本質」を読む"発表資料
 
Software for Edge Heavy Computing @ INTEROP 2016 Tokyo
Software for Edge Heavy Computing @ INTEROP 2016 TokyoSoftware for Edge Heavy Computing @ INTEROP 2016 Tokyo
Software for Edge Heavy Computing @ INTEROP 2016 Tokyo
 
機械学習CROSS 前半資料
機械学習CROSS 前半資料機械学習CROSS 前半資料
機械学習CROSS 前半資料
 
データサイエンティスト協会スキル委員会2ndシンポジウム講演資料
データサイエンティスト協会スキル委員会2ndシンポジウム講演資料データサイエンティスト協会スキル委員会2ndシンポジウム講演資料
データサイエンティスト協会スキル委員会2ndシンポジウム講演資料
 
Chainer GTC 2016
Chainer GTC 2016Chainer GTC 2016
Chainer GTC 2016
 
NIPS2015概要資料
NIPS2015概要資料NIPS2015概要資料
NIPS2015概要資料
 
データサイエンティスト スキルチェックリスト
データサイエンティスト スキルチェックリストデータサイエンティスト スキルチェックリスト
データサイエンティスト スキルチェックリスト
 
How AI revolutionizes robotics and automotive industries
How AI revolutionizes robotics and automotive industriesHow AI revolutionizes robotics and automotive industries
How AI revolutionizes robotics and automotive industries
 
機械学習モデルフォーマットの話:さようならPMML、こんにちはPFA
機械学習モデルフォーマットの話:さようならPMML、こんにちはPFA機械学習モデルフォーマットの話:さようならPMML、こんにちはPFA
機械学習モデルフォーマットの話:さようならPMML、こんにちはPFA
 
あなたの業務に機械学習を活用する5つのポイント
あなたの業務に機械学習を活用する5つのポイントあなたの業務に機械学習を活用する5つのポイント
あなたの業務に機械学習を活用する5つのポイント
 
Jubatus Casual Talks #2 異常検知入門
Jubatus Casual Talks #2 異常検知入門Jubatus Casual Talks #2 異常検知入門
Jubatus Casual Talks #2 異常検知入門
 
データサイエンティストのつくり方
データサイエンティストのつくり方データサイエンティストのつくり方
データサイエンティストのつくり方
 

Similar a 111015 tokyo scipy2_discussionquestionaire_i_python

BUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdfBUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdfkarthikaparthasarath
 
NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxJohnWilliam111370
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
TENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONTENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONAndré Panisson
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdfkesav24
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)PyData
 
Introduction to NumPy
Introduction to NumPyIntroduction to NumPy
Introduction to NumPyHuy Nguyen
 
Tutorial on convolutional neural networks
Tutorial on convolutional neural networksTutorial on convolutional neural networks
Tutorial on convolutional neural networksHojin Yang
 
Algorithm Design and Analysis - Practical File
Algorithm Design and Analysis - Practical FileAlgorithm Design and Analysis - Practical File
Algorithm Design and Analysis - Practical FileKushagraChadha1
 
Clonal Selection: an Immunological Algorithm for Global Optimization over Con...
Clonal Selection: an Immunological Algorithm for Global Optimization over Con...Clonal Selection: an Immunological Algorithm for Global Optimization over Con...
Clonal Selection: an Immunological Algorithm for Global Optimization over Con...Mario Pavone
 
Advanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part IIAdvanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part IIDr. Volkan OBAN
 
Working with tf.data (TF 2)
Working with tf.data (TF 2)Working with tf.data (TF 2)
Working with tf.data (TF 2)Oswald Campesato
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02Abdul Samee
 
Frsa
FrsaFrsa
Frsa_111
 
Replica exchange MCMC
Replica exchange MCMCReplica exchange MCMC
Replica exchange MCMC. .
 

Similar a 111015 tokyo scipy2_discussionquestionaire_i_python (20)

BUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdfBUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdf
 
NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptx
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
TENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONTENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHON
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
 
Google TensorFlow Tutorial
Google TensorFlow TutorialGoogle TensorFlow Tutorial
Google TensorFlow Tutorial
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Introduction to NumPy
Introduction to NumPyIntroduction to NumPy
Introduction to NumPy
 
Tutorial on convolutional neural networks
Tutorial on convolutional neural networksTutorial on convolutional neural networks
Tutorial on convolutional neural networks
 
Digital signal processing
Digital signal processingDigital signal processing
Digital signal processing
 
Algorithm Design and Analysis - Practical File
Algorithm Design and Analysis - Practical FileAlgorithm Design and Analysis - Practical File
Algorithm Design and Analysis - Practical File
 
Clonal Selection: an Immunological Algorithm for Global Optimization over Con...
Clonal Selection: an Immunological Algorithm for Global Optimization over Con...Clonal Selection: an Immunological Algorithm for Global Optimization over Con...
Clonal Selection: an Immunological Algorithm for Global Optimization over Con...
 
Advanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part IIAdvanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part II
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
Working with tf.data (TF 2)
Working with tf.data (TF 2)Working with tf.data (TF 2)
Working with tf.data (TF 2)
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
 
Frsa
FrsaFrsa
Frsa
 
NODDEA2012_VANKOVA
NODDEA2012_VANKOVANODDEA2012_VANKOVA
NODDEA2012_VANKOVA
 
Glowworm Swarm Optimisation
Glowworm Swarm OptimisationGlowworm Swarm Optimisation
Glowworm Swarm Optimisation
 
Replica exchange MCMC
Replica exchange MCMCReplica exchange MCMC
Replica exchange MCMC
 

Más de Shohei Hido

CuPy: A NumPy-compatible Library for GPU
CuPy: A NumPy-compatible Library for GPUCuPy: A NumPy-compatible Library for GPU
CuPy: A NumPy-compatible Library for GPUShohei Hido
 
Deep Learning Lab 異常検知入門
Deep Learning Lab 異常検知入門Deep Learning Lab 異常検知入門
Deep Learning Lab 異常検知入門Shohei Hido
 
ディープラーニングの産業応用とそれを支える技術
ディープラーニングの産業応用とそれを支える技術ディープラーニングの産業応用とそれを支える技術
ディープラーニングの産業応用とそれを支える技術Shohei Hido
 
さらば!データサイエンティスト
さらば!データサイエンティストさらば!データサイエンティスト
さらば!データサイエンティストShohei Hido
 
(道具としての)データサイエンティストのつかい方
(道具としての)データサイエンティストのつかい方(道具としての)データサイエンティストのつかい方
(道具としての)データサイエンティストのつかい方Shohei Hido
 
FIT2012招待講演「異常検知技術のビジネス応用最前線」
FIT2012招待講演「異常検知技術のビジネス応用最前線」FIT2012招待講演「異常検知技術のビジネス応用最前線」
FIT2012招待講演「異常検知技術のビジネス応用最前線」Shohei Hido
 
Travis E. Oliphant, "NumPy and SciPy: History and Ideas for the Future"
Travis E. Oliphant, "NumPy and SciPy: History and Ideas for the Future"Travis E. Oliphant, "NumPy and SciPy: History and Ideas for the Future"
Travis E. Oliphant, "NumPy and SciPy: History and Ideas for the Future"Shohei Hido
 
111015 tokyo scipy2_ディスカッション
111015 tokyo scipy2_ディスカッション111015 tokyo scipy2_ディスカッション
111015 tokyo scipy2_ディスカッションShohei Hido
 
110828 tokyo scipy1_hido_dist
110828 tokyo scipy1_hido_dist110828 tokyo scipy1_hido_dist
110828 tokyo scipy1_hido_distShohei Hido
 
110901 tokyo scipy1_アンケート結果
110901 tokyo scipy1_アンケート結果110901 tokyo scipy1_アンケート結果
110901 tokyo scipy1_アンケート結果Shohei Hido
 

Más de Shohei Hido (11)

CuPy: A NumPy-compatible Library for GPU
CuPy: A NumPy-compatible Library for GPUCuPy: A NumPy-compatible Library for GPU
CuPy: A NumPy-compatible Library for GPU
 
Deep Learning Lab 異常検知入門
Deep Learning Lab 異常検知入門Deep Learning Lab 異常検知入門
Deep Learning Lab 異常検知入門
 
NIPS2017概要
NIPS2017概要NIPS2017概要
NIPS2017概要
 
ディープラーニングの産業応用とそれを支える技術
ディープラーニングの産業応用とそれを支える技術ディープラーニングの産業応用とそれを支える技術
ディープラーニングの産業応用とそれを支える技術
 
さらば!データサイエンティスト
さらば!データサイエンティストさらば!データサイエンティスト
さらば!データサイエンティスト
 
(道具としての)データサイエンティストのつかい方
(道具としての)データサイエンティストのつかい方(道具としての)データサイエンティストのつかい方
(道具としての)データサイエンティストのつかい方
 
FIT2012招待講演「異常検知技術のビジネス応用最前線」
FIT2012招待講演「異常検知技術のビジネス応用最前線」FIT2012招待講演「異常検知技術のビジネス応用最前線」
FIT2012招待講演「異常検知技術のビジネス応用最前線」
 
Travis E. Oliphant, "NumPy and SciPy: History and Ideas for the Future"
Travis E. Oliphant, "NumPy and SciPy: History and Ideas for the Future"Travis E. Oliphant, "NumPy and SciPy: History and Ideas for the Future"
Travis E. Oliphant, "NumPy and SciPy: History and Ideas for the Future"
 
111015 tokyo scipy2_ディスカッション
111015 tokyo scipy2_ディスカッション111015 tokyo scipy2_ディスカッション
111015 tokyo scipy2_ディスカッション
 
110828 tokyo scipy1_hido_dist
110828 tokyo scipy1_hido_dist110828 tokyo scipy1_hido_dist
110828 tokyo scipy1_hido_dist
 
110901 tokyo scipy1_アンケート結果
110901 tokyo scipy1_アンケート結果110901 tokyo scipy1_アンケート結果
110901 tokyo scipy1_アンケート結果
 

Último

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Último (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

111015 tokyo scipy2_discussionquestionaire_i_python

  • 1. Q3: Sum with NaN and Inf nanやInfを含む値の列x = numpy.array([[1,0,nan,1,Inf,1,....]])が与えられたとき、NaNやInf以外のx の要素の合計を計算す る方法が直ぐに思い浮かびますか? In [1]: # 準備 i m p o r t numpy i m p o r t numpy a s np x = numpy.array([[1,0,nan,1,Inf,1]]) x Out[1]: array([[ 1., 0., nan, 1., inf, 1.]]) In [2]: # 回答者1 x[isnan(x)]=0 x[isinf(x)]=0 sum(x) Out[2]: 3.0 In [3]: % timeit x[isnan(x)]=0 % timeit x[isinf(x)]=0 % timeit sum(x) 100000 loops, best of 3: 4.47 us per loop 100000 loops, best of 3: 4.31 us per loop 100000 loops, best of 3: 3.46 us per loop In [4]: # 回答者2 # どういうときに Inf を除きたいのかわからないけど sum_with_finite = x[numpy.isfinite(x)].sum() sum_with_finite # NaN を除くだけなら sum_without_nan = numpy.nansum(x) Out[4]: 3.0 In [5]: % timeit x[numpy.isfinite(x)].sum() 100000 loops, best of 3: 7.47 us per loop In [6]: # 回答者4 sum(filter(l a m b d a x: x! = float('inf') a n d x= = x, x[0])) l ! = Out[6]: 3.0 In [7]: % timeit sum(filter(l a m b d a x: x! = float('inf') a n d x= = x, x[0])) l ! = 10000 loops, best of 3: 39 us per loop In [8]: # 回答者5 np.nansum(x[x! = np.inf]) ! Out[8]: 3.0
  • 2. Out[8]: 3.0 In [9]: % timeit np.nansum(x[x! = np.inf]) ! 10000 loops, best of 3: 29.3 us per loop In [10]: # 回答者6 x[numpy.isfinite(x)].sum() Out[10]: 3.0 In [11]: % timeit x[numpy.isfinite(x)].sum() 100000 loops, best of 3: 8.33 us per loop In [12]: # 回答者8 numpy.sum(x[numpy.isfinite(x)]) Out[12]: 3.0 In [13]: % timeit numpy.sum(x[numpy.isfinite(x)]) 100000 loops, best of 3: 10.2 us per loop In [14]: # 回答者9 np.sum(x[np.isfinite(x)]) Out[14]: 3.0 In [15]: % timeit np.sum(x[np.isfinite(x)]) 100000 loops, best of 3: 10.1 us per loop Q4: Missing values in ndarray nanを含む4x2行列m = numpy.array([[1,nan,-1,0],[0,0,nan,1]])が与えられたとき、nanを含む行を削除して2x2行列にする 方法が直ぐに思い浮かびますか? In [16]: # 準備 i m p o r t numpy i m p o r t numpy a s np m = numpy.array([[1,nan,- 1,0],[0,0,nan,1]]) - m Out[16]: array([[ 1., nan, -1., 0.], [ 0., 0., nan, 1.]]) In [17]: # 回答者1 delete(m,argmax(isnan(m),axis=1),axis=1) Out[17]: array([[ 1., 0.], [ 0., 1.]]) In [18]: % timeit delete(m,argmax(isnan(m),axis=1),axis=1)
  • 3. In [18]: % timeit delete(m,argmax(isnan(m),axis=1),axis=1) 10000 loops, best of 3: 110 us per loop In [19]: # 回答者2 selected_m = m[:,numpy.isfinite(m.sum(axis=0))] selected_m Out[19]: array([[ 1., 0.], [ 0., 1.]]) In [20]: % timeit m[:,numpy.isfinite(m.sum(axis=0))] 100000 loops, best of 3: 11.2 us per loop In [21]: # 回答者4 index = [xx f o r xx i n range(len(m[0])) i f sum(m[:,xx])= = sum(m[:,xx])] = m[:,index] Out[21]: array([[ 1., 0.], [ 0., 1.]]) In [22]: % timeit index = [xx f o r xx i n range(len(m[0])) i f sum(m[:,xx])= = sum(m[:,xx])] = % timeit m[:,index] 10000 loops, best of 3: 38.9 us per loop 100000 loops, best of 3: 12.8 us per loop In [23]: # 回答者6 nans = logical_or(isnan(m[0]), isnan(m[1])) mask = tile(logical_not(nans), (2,1)) res = m[mask].reshape(2,2) res Out[23]: array([[ 1., 0.], [ 0., 1.]]) In [24]: % timeit nans = logical_or(isnan(m[0]), isnan(m[1])) % timeit mask = tile(logical_not(nans), (2,1)) % timeit res = m[mask].reshape(2,2) 100000 loops, best of 3: 5.46 us per loop 100000 loops, best of 3: 13.2 us per loop 100000 loops, best of 3: 4.46 us per loop In [25]: # 回答者8 m[:,numpy.apply_along_axis(numpy.all,0,numpy.isfinite(m))] Out[25]: array([[ 1., 0.], [ 0., 1.]]) In [26]: % timeit m[:,numpy.apply_along_axis(numpy.all,0,numpy.isfinite(m))] 1000 loops, best of 3: 160 us per loop In [27]: # 回答者9 m[:, np.isfinite(np.sum(m, axis=0))] Out[27]: array([[ 1., 0.],
  • 4. Out[27]: array([[ 1., 0.], [ 0., 1.]]) In [28]: % timeit m[:, np.isfinite(np.sum(m, axis=0))] 100000 loops, best of 3: 12.8 us per loop Q5: 1-of-K representation numpy.array([[1,3,2]])を、1-of-K表記法変換してnumpy.array([[1,0,0],[0,0,1],[0,1,0]])にする処理方法が直ぐに思い浮か びますか? In [29]: # 準備 i m p o r t numpy i m p o r t numpy a s np y = numpy.array([[1,3,2]]) y Out[29]: array([[1, 3, 2]]) In [30]: #回答者1 t = numpy.array([1,3,2]) # pattern 1 z = numpy.fromfunction(l a m b d a i,j:j= = t[i]- 1,(t.size,t.max()),dtype=int)+ 0 l = - + p r i n t (z) # pattern 2 z = numpy.array([numpy.identity(t.max())[x- 1,:] f o r x i n t]) - p r i n t (z) # pattern 3(numpy 1.6 以降) z = numpy.array([numpy.bincount([x- 1],minlength=t.max()) f o r x i n t]) - p r i n t (z) [[1 0 0] [0 0 1] [0 1 0]] [[ 1. 0. 0.] [ 0. 0. 1.] [ 0. 1. 0.]] [[1 0 0] [0 0 1] [0 1 0]] In [31]: % timeit z = numpy.fromfunction(l a m b d a i,j:j= = t[i]- 1,(t.size,t.max()),dtype=int)+ 0 l = - + % timeit z = numpy.array([numpy.identity(t.max())[x- 1,:] f o r x i n t]) - % timeit z = numpy.array([numpy.bincount([x- 1],minlength=t.max()) f o r x i n t]) - 10000 loops, best of 3: 61.7 us per loop 10000 loops, best of 3: 55.3 us per loop 10000 loops, best of 3: 65.6 us per loop In [32]: #回答者2 N=y.shape[1] yy=zeros(N* * 2) * yy[N* arange(N)+ y- 1]=1 #編集者注:yy[N*arange(N)+y-1].reshape(N,N)では動かず * + - yy.reshape(N,N)
  • 5. Out[32]: array([[ 1., 0., 0.], [ 0., 0., 1.], [ 0., 1., 0.]]) In [33]: % timeit N=y.shape[1] % timeit yy=zeros(N* * 2) * % timeit yy[N* arange(N)+ y- 1]=1 #編集者注:yy[N*arange(N)+y-1].reshape(N,N)では動かず * + - % timeit yy.reshape(N,N) 10000000 loops, best of 3: 203 ns per loop 1000000 loops, best of 3: 1.37 us per loop 10000 loops, best of 3: 14.6 us per loop 1000000 loops, best of 3: 846 ns per loop In [34]: #回答者4 K=3 d e f my_func(i): z = numpy.zeros(K,dtype=int) z[i- 1] = 1 - return z numpy.array(map(my_func,y[0])) Out[34]: array([[1, 0, 0], [0, 0, 1], [0, 1, 0]]) In [35]: % timeit numpy.array(map(my_func,y[0])) 10000 loops, best of 3: 29.8 us per loop In [36]: #回答者6 res = zeros((3, 3)) indices = [i* 3+ c- 1 f o r i, c i n enumerate(y[0])] * + - res.put(indices, 1) res Out[36]: array([[ 1., 0., 0.], [ 0., 0., 1.], [ 0., 1., 0.]]) In [37]: % timeit res = zeros((3, 3)) % timeit indices = [i* 3+ c- 1 f o r i, c i n enumerate(y[0])] * + - % timeit res.put(indices, 1) 1000000 loops, best of 3: 814 ns per loop 100000 loops, best of 3: 10.2 us per loop 100000 loops, best of 3: 10.3 us per loop In [38]: #回答者8 numpy.fromfunction(l a m b d a i, j: numpy.array(y[0][i]= = j+ 1, dtype=int), (3, 3), dtype l = + Out[38]: array([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
  • 6. In [39]: % timeit numpy.fromfunction(l a m b d a i, j: numpy.array(y[0][i]= = j+ 1, dtype=int), (3, 3 l = + 10000 loops, best of 3: 44.3 us per loop In [40]: #回答者9 #これは逆の方が問題だな… ans = np.zeros((3, 3)) ans[np.arange(3, dtype=np.int), y- 1] = 1 #編集者注:0-origin対応でy-1とした - ans Out[40]: array([[ 1., 0., 0.], [ 0., 0., 1.], [ 0., 1., 0.]]) In [41]: % timeit ans = np.zeros((3, 3)) % timeit ans[np.arange(3, dtype=np.int), y- 1] = 1 - 1000000 loops, best of 3: 761 ns per loop 100000 loops, best of 3: 7.97 us per loop Q6: Useful snippets In [45]: d e f _main(): pass i f __name__= = _main(): = _main()