Advertisement
mikolajmki

si_lab08

Dec 1st, 2022
782
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.99 KB | None | 0 0
  1. from keras.datasets import fashion_mnist
  2. from sklearn.model_selection import train_test_split
  3. import pandas as pd
  4. import numpy as np
  5. data = fashion_mnist.load_data()
  6. X_train, y_train = data[0][0], data[0][1]
  7. X_test, y_test = data[1][0], data[1][1]
  8. X_train = np.expand_dims(X_train, axis = -1)
  9. X_test = np.expand_dims(X_test, axis = -1)
  10. y_train = pd.get_dummies(pd.Categorical(y_train)).values
  11. y_test = pd.get_dummies(pd.Categorical(y_test)).values
  12. from matplotlib import pyplot as plt
  13. from matplotlib import rcParams
  14. rcParams['font.size'] = 48
  15. def show_pictures(arrs):
  16.  arr_cnt = arrs.shape[0]
  17.  fig, axes = plt.subplots(1, arr_cnt, figsize=(5*arr_cnt, arr_cnt))
  18.  for axis, pic in zip(axes, arrs):
  19.      axis.imshow(pic.squeeze(), cmap = 'gray')
  20.      axis.axis('off')
  21.  fig.tight_layout()
  22. demo_images = X_train[:10,...,0]
  23. # show_pictures (demo_images).suptitle("Zdjęcia pierwotne")
  24. # odbicia_poziome = demo_images[...,::-1]
  25. # show_pictures(odbicia_poziome).suptitle("Odbicia poziome")
  26. # odbicia_pionowe = demo_images[...,::-1,:]
  27. # show_pictures(odbicia_pionowe).suptitle("Odbicia pionowe")
  28. from PIL import Image
  29. rotated_images = demo_images.copy()
  30. img_size = demo_images.shape[1:]
  31. angles = np.random.randint(-30,30, len(rotated_images))
  32. for i, img in enumerate(rotated_images):
  33.     angle = np.random.randint(-30,30)
  34.     img = Image.fromarray(img).rotate(angle,
  35.     expand = 1).resize(img_size)
  36.     rotated_images[i] = np.array(img)
  37. # show_pictures(rotated_images)
  38.  
  39. from PIL import Image
  40. rotated_images = demo_images.copy()
  41. img_size = demo_images.shape[1:]
  42. for i, img in enumerate(rotated_images):
  43.  angle = np.random.randint(-30,30)
  44.  left, upper = np.random.randint(0, 5, 2)
  45.  right, lower = np.random.randint(23, 28, 2)
  46.  img = Image.fromarray(img).crop((left, upper, right, lower)).resize(img_size)
  47.  rotated_images[i] = np.array(img)
  48. show_pictures(rotated_images)
  49.  
  50. from keras.models import Model
  51. from keras.layers import Input, Dense, Dropout, Reshape, BatchNormalization, Lambda
  52. from keras.optimizers import Adam
  53. act_func = 'selu'
  54. hidden_dims = 64
  55.  
  56. encoder_layers = [
  57.  Reshape((28*28,)),
  58.  BatchNormalization(),
  59.  Dense(512,activation=act_func),
  60.  Dense(128,activation=act_func),
  61.  Dense(64, activation=act_func),
  62.  Dense(hidden_dims, activation=act_func)]
  63. tensor = encoder_input = Input(shape = (28,28))
  64. for layer in encoder_layers:
  65.  tensor = layer(tensor)
  66. encoder_output = tensor
  67. encoder = Model(inputs=encoder_input,
  68.  outputs=encoder_output)
  69.  
  70. decoder_layers = [
  71.  Dense(128,activation=act_func),
  72.  Dense(512,activation=act_func),
  73.  Dense(784,activation='sigmoid'),
  74.  Reshape((28,28)),
  75.  Lambda(lambda x: x*255)]
  76. decoder_input = tensor = Input(encoder_output.shape)
  77. for layer in decoder_layers:
  78.  tensor = layer(tensor)
  79. decoder_output = tensor
  80. decoder = Model(inputs = decoder_input, outputs = decoder_output)
  81.  
  82. learning_rate = 0.0001;
  83. aec_output = decoder(encoder(encoder_input))
  84. gen_autoencoder = Model(inputs = encoder_input, outputs = aec_output)
  85. gen_autoencoder.compile(optimizer = Adam(learning_rate), loss = 'MeanSquaredError')
  86. gen_autoencoder.fit(x=X_train,y=X_train,
  87.  validation_data=(X_test, X_test),
  88.  batch_size=256, epochs=10)
  89.  
  90. from keras import backend as K
  91. def adding_noise(tensor):
  92.  noise = K.random_normal(shape=(K.shape(tensor)),
  93.  mean=0, stddev=1.5)
  94.  return tensor + noise
  95. noised_encoder_output = Lambda(adding_noise)(encoder_output)
  96. augmenter_output = decoder(noised_encoder_output)
  97. augmenter = Model(inputs = encoder_input, outputs = augmenter_output)
  98.  
  99. def filter_data(data, iteration_num):
  100.  augmented_data = data.copy()
  101.  for i in range(iteration_num):
  102.     augmented_data = gen_autoencoder.predict(augmented_data)
  103.  return augmented_data
  104. start = 50
  105. end = start + 10
  106. for i in range(10):
  107.  test_for_augm = X_train[i*10:i*10+10,...]
  108.  augmented_data = test_for_augm.copy()
  109.  show_pictures(test_for_augm)
  110.  augmented_data = augmenter.predict(augmented_data)
  111.  show_pictures(augmented_data)
  112.  augmented_data = filter_data(augmented_data, 5)
  113.  show_pictures(augmented_data)
  114.  
  115.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement