[关闭]
@nrailgun 2017-09-04T16:40:56.000000Z 字数 3295 阅读 1667

Numpy Tricks

程序设计


Element Wise Max

  1. np.maximum.reduce([a,b])

Ground Truth

  1. Y = np.hstack([ np.eye(k), np.zeros(k, n - k) ])
  2. Y = Y[:, y]

Random Integer Matrix

  1. a = np.random.randint(10, size=(3,3))

Set Some Rows Zeros

  1. a[a < 0] = 0

Count True

  1. np.sum(a)

Stack Matrix

  1. np.tile(m, (w, h))

Bool Matrix To Binary Matrix

  1. np.array(b, dtype=int)

Add Rows With Same Classes

Add only rows with same classes, by convert row class vector to ground true table.

  1. n = 3
  2. m = 4
  3. k = 2
  4. X = np.random.randint(10, size=(n, m))
  5. y = [0, 1, 0]
  6. # Add row 0 and row 2 into one row, and row 1 into another row.
  7. Y = np.hstack([ np.eye(k), np.zeros(k, n - k) ])
  8. Y = Y[:, y]
  9. np.dot(Y, X.T)

Random Pickup

  1. np.random.choice(range, n)

Reverse array

  1. a[:, :, -1]

Diagonal line

  1. np.diag(M)

Make Read-only

  1. M.flags.writeable = False

Row Mean

  1. M.mean(axis=1, keepdims=True)

Sorted Index

  1. M.argsort()

Use Generator

  1. def gen():
  2. for i in xrange(10):
  3. yield i
  4. a = np.fromiter(gen(), dtype=float, count=-1)

Find Unique Elements

  1. np.unique(z)

Sum Over Axis

  1. A = np.random.randint(10, size=(2,2,3,4))
  2. B = A.reshape(A.shape[:, -2] + (-1,))
  3. print np.sum(B, axis=-1)

Diagonal of Matrix Product

  1. np.sum(A * B.T, axis=1)
  2. # Faster version
  3. np.einsum("ij,ji->i", A, B)

Swap 2 Rows

  1. A[[r1, r2]] = A[[r2, r1]]

Construct Gaussian Kernel

  1. import scipy.ndimage.filters as flt
  2. inp = np.zeros((ksize, ksize))
  3. inp[ksize / 2, ksize / 2] = 1
  4. kern = flt.gaussian_filter(inp, sigma)

SciPY Image Operations

NOTE: It's different from cv2 ops, DO NOT mix them.

  1. from scipy.misc import imread, imsave, imresize
  2. # imread('x.png', True) returns gray-scale
  3. img = imread('x.png')
  4. print img.dtype, img.shape # Prints "uint8 (400, 248, 3)"
  5. img_tinted = img * [1, 0.95, 0.9]
  6. img_tinted = imresize(img_tinted, (300, 300))
  7. imsave('y.png', img_tinted)

Matplotlib

Plot:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Compute the x and y coordinates for points on sine and cosine curves
  4. x = np.arange(0, 3 * np.pi, 0.1)
  5. y_sin = np.sin(x)
  6. y_cos = np.cos(x)
  7. # Plot the points using matplotlib
  8. plt.plot(x, y_sin)
  9. plt.plot(x, y_cos)
  10. plt.xlabel('x axis label')
  11. plt.ylabel('y axis label')
  12. plt.title('Sine and Cosine')
  13. plt.legend(['Sine', 'Cosine'])
  14. plt.show()

Subplot:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Compute the x and y coordinates for points on sine and cosine curves
  4. x = np.arange(0, 3 * np.pi, 0.1)
  5. y_sin = np.sin(x)
  6. y_cos = np.cos(x)
  7. # Set up a subplot grid that has height 2 and width 1,
  8. # and set the first such subplot as active.
  9. plt.subplot(2, 1, 1)
  10. # Make the first plot
  11. plt.plot(x, y_sin)
  12. plt.title('Sine')
  13. # Set the second subplot as active, and make the second plot.
  14. plt.subplot(2, 1, 2)
  15. plt.plot(x, y_cos)
  16. plt.title('Cosine')
  17. # Show the figure.
  18. plt.show()

Show image:

  1. import numpy as np
  2. from scipy.misc import imread, imresize
  3. import matplotlib.pyplot as plt
  4. img = imread('assets/cat.jpg')
  5. img_tinted = img * [1, 0.95, 0.9]
  6. # Show the original image
  7. plt.subplot(1, 2, 1)
  8. plt.imshow(img)
  9. # Show the tinted image
  10. plt.subplot(1, 2, 2)
  11. # A slight gotcha with imshow is that it might give strange results
  12. # if presented with data that is not uint8. To work around this, we
  13. # explicitly cast the image to uint8 before displaying it.
  14. plt.imshow(np.uint8(img_tinted))
  15. plt.show()

Show Gray-Scale Image:

  1. plt.imshow(img, cmap="Greys_r")

Change All sign or Negate all boolean

  1. np.logical_not(a)
  2. np.negative(b)

For Each Row / Column in Matrix

  1. # ufunc can be add / multiply
  2. np.ufunc.reduce(A, axis)

Generate Gaussian random

  1. g = np.random.normal(scale=0, size=(2,2))

Matrix max index

  1. (i, j) = np.unravel_index(x.argmax(), x.shape)

Swap dimension

  1. # I is a list of 8 1*28*28 images.
  2. # Show them in one image.
  3. imshow(I.transpose(1, 0, 2).reshape(28, 8*28), cmap='gray')
  4. # Or, diff is a 20 5*5 images list.
  5. imshow(diff.reshape(4, 5, 5, 5)
  6. .transpose(0, 2, 1, 3).reshape(4*5, 5*5), cmap='gray')

[W1, W2] * [x1; x2]

Not necessary to produce temporary array [ x1; x2 ], all you need is W1 * x1 + W2 * x2.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注