In [4]:
# Numpy is our primary dependency
import numpy as np
# Import datasets from scikit-learn only to get the iris data set
from sklearn import datasets
# We will need some plotting too
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib notebook
#假設你要讓每一個 chart inline 獨立顯示
%matplotlib inline
In [5]:
from sklearn import datasets
from sklearn import decomposition
import matplotlib.pyplot as plt
import numpy as np
mnist = datasets.load_digits()
X = mnist.data
y = mnist.target
In [6]:
# 他是一個 8*8 影像矩陣
X.shape
Out[6]:
In [7]:
print("這個數字 #{}#".format(y[33]))
plt.imshow(X[33].reshape(8,8), interpolation='nearest')
plt.show()
In [8]:
# 計算 varience 前,先計算各 feature 的 mean
mean = np.mean(X,axis=0)
# 計算每個一點和 mean 之間的差,及為各資料點的varience
x_x = X-mean
In [9]:
# 計算 covarience matrix
cov = np.matmul(x_x.transpose(),x_x)/mean.shape[0]
In [10]:
# 用 np 的 function 算出 eigenvalue 及 eigevecto
value,vec = np.linalg.eig(cov)
In [11]:
# 確認一下 shape 是否為 8*8 ,因為是計算 feature 間的 covairence
value.shape
Out[11]:
In [12]:
# 再來看 eigen_value 遞減佔比,由此可以看出大約前 8 個 componet 就佔了大部份
y_eigen_value = []
for i in range(8*8):
y_eigen_value.append(value[i]/np.sum(value))
plt.scatter(range(0,8*8), y_eigen_value , cmap=plt.cm.spectral)
plt.show()
In [13]:
# 因為 PCA 產出的值為負到正的浮點數,故需先作平移,才能視覺化成現
new_vec = ((vec+1)*128).astype(int)
In [14]:
# 來看一下 componet
In [15]:
plt.imshow(new_vec[:,0].reshape(8,8), interpolation='nearest')
Out[15]:
In [16]:
plt.imshow(new_vec[:,1].reshape(8,8), interpolation='nearest')
Out[16]:
In [17]:
plt.imshow(new_vec[:,2].reshape(8,8), interpolation='nearest')
Out[17]:
In [18]:
# new_X 為降為過後,降成三維
new_X = np.matmul(X,vec[:,:3])
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(new_X[:, 0], new_X[:, 1], new_X[:, 2], c=y, cmap=plt.cm.spectral)
plt.show()
In [19]:
# 將投影的結果,進行 Normalize ,以便好計算兩兩間的 similarity
from sklearn.preprocessing import normalize
new_X_normlized = normalize(new_X)
In [20]:
# 因為進行 normalize 了,故成現球形的分佈
fig2 = plt.figure()
ax2 = fig2.gca(projection='3d')
ax2.scatter(new_X_normlized[:, 0], new_X_normlized[:, 1], new_X_normlized[:, 2], c=y, cmap=plt.cm.spectral)
plt.show()
In [21]:
# 計算看看 similarity
test_index = 333
new_X_normlized
sims = np.matmul(new_X_normlized,new_X_normlized[test_index])
for i in sims.argsort()[-30:][::-1]:
print("這個數字 #{}#".format(y[i]))
plt.imshow(X[i].reshape(8,8), interpolation='nearest')
plt.show()
In [22]:
pca = decomposition.PCA(n_components=3)
new_X = pca.fit_transform(X)
fig3 = plt.figure()
ax = fig3.gca(projection='3d')
ax.scatter(new_X[:, 0], new_X[:, 1], new_X[:, 2], c=y, cmap=plt.cm.spectral)
plt.show()
In [23]:
from keras.layers import Input, Dense
from keras.models import Model
from keras import regularizers
In [24]:
# 為何要 load 另外一組 dataset 呢,原因是因為要 sklearn 的 data 量太少,經過實驗後無法學到好的 encode 效果
from keras.datasets import mnist
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()
In [25]:
h1_size = 32
h2_size = 32
input_img = Input(shape=(28*28,))
encoder = Dense(h1_size,activation='relu')(input_img)
hidden = Dense(h2_size,activation='relu')(encoder)
# 最後一層的輸出改用 sigmoid ,因為 relu 的出輸結果無法 bound 在 0~1 之間
decoder = Dense(28*28,activation='sigmoid')(hidden)
autoencoder = Model(input_img, decoder)
autoencoder.compile(loss='binary_crossentropy',optimizer='adadelta')
In [26]:
# 由於必需要計算 cross entropy 作 lose function ,x 的值必需要 normalize 到介於 0 到 1 之間
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
# 由於沒有要做 2D Convolution 故 reshape 成一維
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
print(x_train.shape)
print(x_test.shape)
In [27]:
encoder_model = Model(input_img,encoder)
decoder_model = Model(input_img,decoder)
In [28]:
autoencoder.fit(x_train, x_train,
epochs=500,
verbose=2,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
In [29]:
# encode and decode some digits
# note that we take them from the *test* set
# encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder_model.predict(x_test[:100].reshape(100,28*28))
In [ ]:
In [30]:
# use Matplotlib (don't ask)
import matplotlib.pyplot as plt
n = 10 # how many digits we will display
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28,28))
# plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow((decoded_imgs[i]).reshape(28, 28))
# plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
In [31]:
new_X = encoder_model.predict(x_test.reshape(x_test.shape[0],28*28))
In [32]:
new_X = (new_X*255).astype('int32')
In [33]:
import numpy as np
from sklearn.manifold import TSNE
X = new_X[:1000]
X_embedded = TSNE(n_components=3).fit_transform(X)
X_embedded.shape
Out[33]:
In [34]:
fig3 = plt.figure()
ax = fig3.gca(projection='3d')
ax.scatter(X_embedded[:, 0], X_embedded[:, 1], X_embedded[:, 2], c=y_test[:1000], cmap=plt.cm.spectral)
plt.show()
In [35]:
input_img = Input(shape=(784,))
encoded = Dense(128, activation='relu')(input_img)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(32, activation='relu')(encoded)
decoded = Dense(64, activation='relu')(encoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(784, activation='sigmoid')(decoded)
In [36]:
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
autoencoder.fit(x_train, x_train,
epochs=100,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
Out[36]:
In [37]:
decoded_imgs = autoencoder.predict(x_test[:100].reshape(100,28*28))
In [38]:
# use Matplotlib (don't ask)
import matplotlib.pyplot as plt
n = 10 # how many digits we will display
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28,28))
# plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow((decoded_imgs[i]).reshape(28, 28))
# plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
In [39]:
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Reshape
from keras.models import Model
from keras import backend as K
In [40]:
input_img = Input([28*28])
reshape_img = Reshape([28,28,1])(input_img)
conv1 = Conv2D(16,[3,3],padding='same')(reshape_img)
maxpool1 = MaxPooling2D([2,2])(conv1)
conv2 = Conv2D(8,[3,3],padding='same')(maxpool1)
maxpool2 = MaxPooling2D((2, 2), padding='same')(conv2)
conv3 = Conv2D(8, (3, 3), activation='relu', padding='same')(maxpool2)
maxpool3 = MaxPooling2D((2, 2), padding='same')(conv3)
encoder = Model(input_img,maxpool3)
# encoder.compile(optimizer='adadelta', loss='binary_crossentropy')
encoder.summary()
In [41]:
re_conv1 = Conv2D(8, (3, 3), activation='relu', padding='same')(maxpool3)
up1 = UpSampling2D((2, 2))(re_conv1)
re_conv2 = Conv2D(8, (3, 3), activation='relu', padding='same')(up1)
up2 = UpSampling2D((2, 2))(re_conv2)
re_conv3 = Conv2D(16, (3, 3), activation='relu')(up2)
up3 = UpSampling2D((2, 2))(re_conv3)
re_conv4 = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(up3)
reshape_img2 = Reshape([28*28])(re_conv4)
decoder = Model(input_img,reshape_img2)
decoder.summary()
In [42]:
from keras.callbacks import TensorBoard
autoencoder.fit(x_train, x_train,
epochs=50,
batch_size=128,
shuffle=True,
validation_data=(x_test, x_test),
callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])
Out[42]:
In [43]:
decoded_imgs = autoencoder.predict(x_test[:100].reshape(100,28*28))
# use Matplotlib (don't ask)
import matplotlib.pyplot as plt
n = 10 # how many digits we will display
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28,28))
# plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow((decoded_imgs[i]).reshape(28, 28))
# plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
In [44]:
#看一下 encode 分佈的結果
In [45]:
ymaping = [[],[],[],[],[],[],[],[],[],[],]
for idx, val in enumerate(y_test):
ymaping[val].append(idx)
In [46]:
test_image = x_test[ymaping[0]]
test_images_encode = encoder.predict(test_image.reshape((test_image.shape[0],28*28)))
In [47]:
test_images_encode.shape
Out[47]:
In [ ]:
In [48]:
X_embedded = TSNE(n_components=1).fit_transform(test_images_encode.reshape((980,4*4*8)))
In [49]:
sorted_index = np.argsort(X_embedded.reshape(980)).tolist()
In [50]:
plt.figure(figsize=(20, 20))
n = len(sorted_index)
for index,value in enumerate(sorted_index):
if index >= 100 : break
ax = plt.subplot(10,10, index+1)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.imshow( x_test[ymaping[0][index]].reshape(28,28) , interpolation='nearest')
plt.show()
In [51]:
'''This script demonstrates how to build a variational autoencoder with Keras.
Reference: "Auto-Encoding Variational Bayes" https://arxiv.org/abs/1312.6114
'''
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from keras.layers import Input, Dense, Lambda, Layer
from keras.models import Model
from keras import backend as K
from keras import metrics
from keras.datasets import mnist
batch_size = 100
original_dim = 784
latent_dim = 2
intermediate_dim = 256
epochs = 50
epsilon_std = 1.0
In [52]:
x = Input(shape=(original_dim,))
h = Dense(intermediate_dim, activation='relu')(x)
z_mean = Dense(latent_dim)(h)
z_log_var = Dense(latent_dim)(h)
def sampling(args):
z_mean, z_log_var = args
epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim), mean=0.,
stddev=epsilon_std)
return z_mean + K.exp(z_log_var / 2) * epsilon
# note that "output_shape" isn't necessary with the TensorFlow backend
z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])
# we instantiate these layers separately so as to reuse them later
decoder_h = Dense(intermediate_dim, activation='relu')
decoder_mean = Dense(original_dim, activation='sigmoid')
h_decoded = decoder_h(z)
x_decoded_mean = decoder_mean(h_decoded)
In [53]:
# Custom loss layer
class CustomVariationalLayer(Layer):
def __init__(self, **kwargs):
self.is_placeholder = True
super(CustomVariationalLayer, self).__init__(**kwargs)
def vae_loss(self, x, x_decoded_mean):
xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)
kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
return K.mean(xent_loss + kl_loss)
def call(self, inputs):
x = inputs[0]
x_decoded_mean = inputs[1]
loss = self.vae_loss(x, x_decoded_mean)
self.add_loss(loss, inputs=inputs)
# We won't actually use the output.
return x
y = CustomVariationalLayer()([x, x_decoded_mean])
vae = Model(x, y)
vae.compile(optimizer='rmsprop', loss=None)
In [54]:
# train the VAE on MNIST digits
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
vae.fit(x_train,
shuffle=True,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_test, None))
# build a model to project inputs on the latent space
encoder = Model(x, z_mean)
In [55]:
# display a 2D plot of the digit classes in the latent space
x_test_encoded = encoder.predict(x_test, batch_size=batch_size)
plt.figure(figsize=(6, 6))
plt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test)
plt.colorbar()
plt.show()
In [56]:
# build a digit generator that can sample from the learned distribution
decoder_input = Input(shape=(latent_dim,))
_h_decoded = decoder_h(decoder_input)
_x_decoded_mean = decoder_mean(_h_decoded)
generator = Model(decoder_input, _x_decoded_mean)
In [57]:
decoded_imgs = vae.predict(x_train[:100])
In [58]:
# use Matplotlib (don't ask)
import matplotlib.pyplot as plt
n = 10 # how many digits we will display
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_train[i].reshape(28,28))
# plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow((decoded_imgs[i]).reshape(28, 28))
# plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
In [59]:
# display a 2D manifold of the digits
n = 15 # figure with 15x15 digits
digit_size = 28
figure = np.zeros((digit_size * n, digit_size * n))
# linearly spaced coordinates on the unit square were transformed through the inverse CDF (ppf) of the Gaussian
# to produce values of the latent variables z, since the prior of the latent space is Gaussian
grid_x = norm.ppf(np.linspace(0.05, 0.95, n))
grid_y = norm.ppf(np.linspace(0.05, 0.95, n))
for i, yi in enumerate(grid_x):
for j, xi in enumerate(grid_y):
z_sample = np.array([[xi, yi]])
x_decoded = generator.predict(z_sample)
digit = x_decoded[0].reshape(digit_size, digit_size)
figure[i * digit_size: (i + 1) * digit_size,
j * digit_size: (j + 1) * digit_size] = digit
plt.figure(figsize=(10, 10))
plt.imshow(figure, cmap='Greys_r')
plt.show()
In [ ]:
In [ ]: