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

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).

主站蜘蛛池模板: 冷水江市| 中江县| 巴彦淖尔市| 五大连池市| 南丰县| 团风县| 临高县| 莱西市| 无为县| 阿拉善右旗| 晋中市| 遵义市| 岗巴县| 遂川县| 黔西| 台江县| 濮阳市| 通道| 韶关市| 乌鲁木齐县| 隆昌县| 辽阳市| 合川市| 连云港市| 青海省| 池州市| 泰顺县| 老河口市| 山阴县| 北宁市| 衢州市| 安义县| 茂名市| 沧州市| 盘山县| 崇礼县| 来安县| 青州市| 东山县| 项城市| 古田县|