官术网_书友最值得收藏!

How to do it...

The strategy defined above is coded as follows (please refer to Issue_with_image translation.ipynb file in GitHub while implementing the code)

  1. Download the dataset and extract the train and test MNIST datasets:
from keras.datasets import mnist
from keras.layers import Flatten, Dense
from keras.models import Sequential
import matplotlib.pyplot as plt
%matplotlib inline
(X_train, y_train), (X_test, y_test) = mnist.load_data()
  1. Fetch the training set corresponding to label 1 only:
X_train1 = X_train[y_train==1]
  1. Reshape and normalize the original training dataset:
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0],num_pixels).astype('float32')
X_test = X_test.reshape(X_test.shape[0],num_pixels).astype('float32')
X_train = X_train / 255
X_test = X_test / 255
  1. One-hot-encode the output labels:
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_train.shape[1]
  1. Build a model and fit it:
model = Sequential()
model.add(Dense(1000, input_dim=num_pixels, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
model.fit(X_train, y_train, validation_data=(X_test, y_test),epochs=5, batch_size=1024, verbose=1)
  1. Let's plot the average 1 image that we obtained in step 2:
pic=np.zeros((28,28))
pic2=np.copy(pic)
for i in range(X_train1.shape[0]):
pic2=X_train1[i,:,:]
pic=pic+pic2
pic=(pic/X_train1.shape[0])
plt.imshow(pic)

In the preceding code, we initialized an empty picture that is 28 x 28 in dimension and took an average pixel value at the various pixel locations of images that have a label of 1 (the X_train1 object) by looping through all the values in the X_train1 object.

The plot of the average 1 image appears as follows:

It is to be noted that the more yellow (thick) the pixel is, the more often people have written on top of the pixel, and the less yellow (more blue/less thick) the pixel, the less often people have written on top of the pixel. Also, it is to be noted that the pixel in the middle is the yellowest/thickest (this is because most people would be writing over the middle pixels, irrespective of whether the whole digit is written in a vertical line or is slanted toward the left or right).

主站蜘蛛池模板: 梨树县| 化州市| 米林县| 开封市| 公安县| 桐梓县| 铁岭县| 大新县| 名山县| 洛南县| 阿拉善左旗| 岑巩县| 象山县| 巴东县| 加查县| 富源县| 綦江县| 樟树市| 内黄县| 丁青县| 金乡县| 昌邑市| 连城县| 诸暨市| 宁波市| 吴桥县| 佛坪县| 泌阳县| 鸡东县| 丰镇市| 策勒县| 桐梓县| 玛曲县| 南郑县| 太康县| 阿拉尔市| 大冶市| 洛南县| 新干县| 平安县| 柘荣县|