1 回答

TA貢獻1966條經驗 獲得超4個贊
3 個嵌套for循環,帶有if條件,同時整形和追加顯然不是一個好主意;numpy.roll以矢量方式完美地完成了這項工作:
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train.shape
# (60000, 28, 28)
# plot an original image
plt.gray()
plt.matshow(x_train[0])
plt.show()
我們先演示一下操作:
# one pixel down:
x_down = np.roll(x_train[0], 1, axis=0)
plt.gray()
plt.matshow(x_down)
plt.show()
# one pixel up:
x_up = np.roll(x_train[0], -1, axis=0)
plt.gray()
plt.matshow(x_up)
plt.show()
# one pixel left:
x_left = np.roll(x_train[0], -1, axis=1)
plt.gray()
plt.matshow(x_left)
plt.show()
# one pixel right:
x_right = np.roll(x_train[0], 1, axis=1)
plt.gray()
plt.matshow(x_right)
plt.show()
確定了這一點后,我們可以簡單地生成所有訓練圖像的“正確”版本
x_all_right = [np.roll(x, 1, axis=1) for x in x_train]
對于其他 3 個方向也是如此。
讓我們確認第一張圖片x_all_right確實是我們想要的:
plt.gray()
plt.matshow(x_all_right[0])
plt.show()
您甚至可以避免最后一個列表理解,而使用純 Numpy 代碼,如
x_all_right = np.roll(x_train, 1, axis=2)
這更有效,雖然稍微不那么直觀(只需采用相應的單圖像命令版本并增加axis
1)。
添加回答
舉報