Professional Documents
Culture Documents
Machine Learning
Machine Learning
Using CNN
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_dim_ordering('th')
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape to be [samples][pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')
# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
def baseline_model():
# create model
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# build the model
model = baseline_model()
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200,
verbose=2)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("CNN Error: %.2f%%" % (100-scores[1]*100))
OUTPUT
2. Hand written digits classification using MLP and CNN using Tensorflow
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
# Model function for CNN
def cnn_model_fn(features, labels, mode):
# Input Layer
input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])
# Convolutional Layer #1
conv1 = tf.layers.conv2d(inputs=input_layer, filters=32, kernel_size=[5, 5],
padding="same", activation=tf.nn.relu)
# Pooling Layer #1
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
# Convolutional Layer #2 and Pooling Layer #2
conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size=[5, 5],
padding="same", activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)
# Dense Layer
pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
dropout = tf.layers.dropout(inputs=dense, rate=0.4, training=mode ==
tf.estimator.ModeKeys.TRAIN)
# Logits Layer
logits = tf.layers.dense(inputs=dropout, units=10)
predictions = {
# Generate predictions (for PREDICT and EVAL mode)
"classes": tf.argmax(input=logits, axis=1),
# Add `softmax_tensor` to the graph. It is used for PREDICT and by the
`logging_hook`
"probabilities": tf.nn.softmax(logits, name="softmax_tensor")
}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
import tensorflow as tf
TEXT_PATH = "tinytrain.txt"
DEV_PATH = "tinyvalid.txt"
BATCH_SIZE =20
NUM_TIMESTEPS =30
model = GeneratingLSTM(vocab_size=vocab.get_size(),
neurons_per_layer=100,
num_layers=2,
max_batch_size=BATCH_SIZE,
output_keep_prob= 0.8)
# Do the training
epoch =1
step = 1
arr1 = []
arr2 = []
for epoch in range(101):
for inputs, targets in dataset:
loss = model.train_step(session, inputs, targets)
step+=1
if epoch%10==0:
num_timesteps=NUM_TIMESTEPS)
arr1.append(loss)
arr2.append(dev_loss)
print("Epoch: %d, Step: %d, Train Loss: %f, Dev Loss: %f" % ( epoch, step,
loss, dev_loss))
OUTPUT
4. Predicting reviews using tensorflow
import pandas as pd
import numpy as np
import tensorflow as tf
train.head(5)
text = text.lower().split()
if remove_stopwords:
stops = set(stopwords.words("english"))
text = [w for w in text if not w in stops]
text = re.sub(r" ", " ", text) # Remove any extra spaces
return(text)
train_clean = train
test_clean = test
test_clean.head(5)
tokenizer = Tokenizer()
tokenizer.fit_on_texts(all_reviews)
print("Fitting is complete.")
train_seq = tokenizer.texts_to_sequences(list(train_clean['review']))
print("train_seq is complete.")
test_seq = tokenizer.texts_to_sequences(list(test_clean['review']))
print("test_seq is complete")
max_review_length = 200
print("train_pad is complete.")
print("test_pad is complete.")
n_batches = len(x)//batch_size
x, y = x[:n_batches*batch_size], y[:n_batches*batch_size]
n_batches = len(x)//batch_size
x = x[:n_batches*batch_size]
yield x[ii:ii+batch_size]
tf.reset_default_graph()
# Declare placeholders we'll feed into the graph
with tf.name_scope('inputs'):
with tf.name_scope('labels'):
with tf.name_scope("embeddings"):
with tf.name_scope("RNN_layers"):
lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
#print(lstm.output_size)
drop = tf.contrib.rnn.DropoutWrapper(lstm,output_keep_prob=keep_prob)
#print(drop.output_shape)
cell = drop
#print(cell.shape)
# Set the initial state
with tf.name_scope("RNN_init_state"):
with tf.name_scope("RNN_forward"):
with tf.name_scope("fully_connected"):
weights = tf.truncated_normal_initializer(stddev=0.1)
biases = tf.zeros_initializer()
if multiple_fc == True:
dense = tf.contrib.layers.fully_connected(dense,
num_outputs = fc_units,
activation_fn = tf.sigmoid,
weights_initializer = weights,
biases_initializer = biases)
with tf.name_scope('predictions'):
predictions = tf.contrib.layers.fully_connected(dense,
num_outputs = 1,
activation_fn=tf.sigmoid,
weights_initializer = weights,
biases_initializer = biases)
tf.summary.histogram('predictions', predictions)
with tf.name_scope('cost'):
tf.summary.scalar('cost', cost)
with tf.name_scope('train'):
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
with tf.name_scope("accuracy"):
tf.summary.scalar('accuracy', accuracy)
merged = tf.summary.merge_all()
return graph
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
valid_loss_summary = []
iteration = 0
print()
train_writer = tf.summary.FileWriter('./logs/3/train/{}'.format(log_string),
sess.graph)
valid_writer = tf.summary.FileWriter('./logs/3/valid/{}'.format(log_string))
for e in range(epochs):
state = sess.run(model.initial_state)
train_loss = []
train_acc = []
val_acc = []
val_loss = []
train_loss.append(loss)
train_acc.append(acc)
train_writer.add_summary(summary, iteration)
iteration += 1
pbar.update(batch_size)
avg_train_loss = np.mean(train_loss)
avg_train_acc = np.mean(train_acc)
val_state = sess.run(model.initial_state)
for x, y in get_batches(x_valid,y_valid,batch_size):
feed = {model.inputs: x,
model.keep_prob: 1,
model.initial_state: val_state}
summary, batch_loss, batch_acc, val_state = sess.run([model.merged,
model.cost, model.accuracy, model.final_state], feed_dict=feed)
val_loss.append(batch_loss)
val_acc.append(batch_acc)
pbar.update(batch_size)
avg_valid_loss = np.mean(val_loss)
avg_valid_acc = np.mean(val_acc)
valid_loss_summary.append(avg_valid_loss)
valid_writer.add_summary(summary, iteration)
# Stop training if the validation loss does not decrease after 3 epochs
print("No Improvement.")
stop_early += 1
if stop_early == 3:
break
# Reset stop_early if the validation loss finds a new low
else:
print("New Record!")
stop_early = 0
checkpoint ="./sentiment_{}.ckpt".format(log_string)
saver.save(sess, checkpoint)
n_words = len(tokenizer.word_index)
embed_size = 50
batch_size = 250
lstm_size = 64
num_layers = 2
dropout = 0.5
learning_rate = 0.001
epochs = 5
multiple_fc = False
fc_units = 250
log_string = 'ru={},fcl={},fcu={}'.format(lstm_size,multiple_fc,fc_units)
all_preds = []
embed_size = embed_size,
batch_size = batch_size,
lstm_size = lstm_size,
num_layers = num_layers,
dropout = dropout,
learning_rate = learning_rate,
multiple_fc = multiple_fc,
fc_units = fc_units)
saver = tf.train.Saver()
saver.restore(sess, checkpoint)
test_state = sess.run(model.initial_state)
for _, x in enumerate(get_test_batches(x_valid,
batch_size), 1):
feed = {model.inputs: x,
model.keep_prob: 1,
model.initial_state: test_state}
predictions = sess.run(model.predictions,feed_dict=feed)
all_preds.append(float(pred))
return all_preds
pred = make_predictions(64,True,128,"sentiment_ru=64,fcl=True,fcu=128.ckpt")
import numpy as np
import argparse
import os
# reparameterization trick
# z = z_mean + sqrt(var)*eps
def sampling(args):
# Arguments:
# Returns:
"""
batch = K.shape(z_mean)[0]
dim = K.int_shape(z_mean)[1]
def plot_results(models,
data,
batch_size=128,
model_name="vae_mnist"):
# Arguments:
"""
os.makedirs(model_name, exist_ok=True)
plt.figure(figsize=(12, 10))
plt.colorbar()
plt.xlabel("z[0]")
plt.ylabel("z[1]")
plt.savefig(filename)
plt.show()
filename = os.path.join(model_name, "digits_over_latent.png")
n = 30
digit_size = 28
grid_x = np.linspace(-4, 4, n)
for i, yi in enumerate(grid_y):
for j, xi in enumerate(grid_x):
x_decoded = decoder.predict(z_sample)
plt.figure(figsize=(10, 10))
start_range = digit_size // 2
sample_range_x = np.round(grid_x, 1)
sample_range_y = np.round(grid_y, 1)
plt.xticks(pixel_range, sample_range_x)
plt.yticks(pixel_range, sample_range_y)
plt.xlabel("z[0]")
plt.ylabel("z[1]")
plt.imshow(figure, cmap='Greys_r')
plt.savefig(filename)
plt.show()
# MNIST dataset
image_size = x_train.shape[1]
# network parameters
input_shape = (original_dim, )
intermediate_dim = 512
batch_size = 128
latent_dim = 2
epochs = 50
x = Dense(intermediate_dim, activation='relu')(inputs)
encoder.summary()
x = Dense(intermediate_dim, activation='relu')(latent_inputs)
decoder.summary()
if __name__ == '__main__':
reconstruction_loss *= original_dim
kl_loss *= -0.5
vae.add_loss(vae_loss)
vae.compile(optimizer='adam')
vae.summary()
vae.fit(x_train,epochs=epochs,batch_size=batch_size,validation_data=(x_test, None))
vae.save_weights('vae_mlp_mnist.h5')
# MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
image_size = x_train.shape[1]
original_dim = image_size * image_size
x_train = np.reshape(x_train, [-1, original_dim])
x_test = np.reshape(x_test, [-1, original_dim])
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# network parameters
input_shape = (original_dim, )
intermediate_dim = 512
batch_size = 128
latent_dim = 2
epochs = 50
if __name__ == '__main__':
parser = argparse.ArgumentParser()
help_ = "Load h5 model trained weights"
parser.add_argument("-w", "--weights", help=help_)
help_ = "Use mse loss instead of binary cross entropy (default)"
parser.add_argument("-m",
"--mse",
help=help_, action='store_true')
args = parser.parse_args()
models = (encoder, decoder)
data = (x_test, y_test)
import numpy as np
import tensorflow as tf
%matplotlib inline
np.random.seed(0)
tf.set_random_seed(0)
#
https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/examples/tut
orials/mnist/input_data.py
n_samples = mnist.train.num_examples
# https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-
tensorflow
minval=low, maxval=high,
dtype=tf.float32)
class VariationalAutoencoder(object):
end-to-end.
See "Auto-Encoding Variational Bayes" by Kingma and Welling for more details.
"""
learning_rate=0.001, batch_size=100):
self.network_architecture = network_architecture
self.transfer_fct = transfer_fct
self.learning_rate = learning_rate
self.batch_size = batch_size
# tf Graph input
self._create_network()
# corresponding optimizer
self._create_loss_optimizer()
init = tf.global_variables_initializer()
self.sess = tf.InteractiveSession()
self.sess.run(init)
def _create_network(self):
network_weights = self._initialize_weights(**self.network_architecture)
# space
self.z_mean, self.z_log_sigma_sq = \
self._recognition_network(network_weights["weights_recog"],
network_weights["biases_recog"])
n_z = self.network_architecture["n_z"]
self.x_reconstr_mean = \
self._generator_network(network_weights["weights_gener"],network_weights["biases_g
ener"])
n_hidden_gener_1, n_hidden_gener_2,
n_input, n_z):
all_weights = dict()
all_weights['weights_recog'] = {
all_weights['biases_recog'] = {
all_weights['biases_gener'] = {
return all_weights
biases['b1']))
biases['b2']))
biases['out_mean'])
z_log_sigma_sq = \
tf.add(tf.matmul(layer_2, weights['out_log_sigma']),
biases['out_log_sigma'])
biases['b1']))
biases['b2']))
x_reconstr_mean = \
tf.nn.sigmoid(tf.add(tf.matmul(layer_2, weights['out_mean']),
biases['out_mean']))
return x_reconstr_mean
def _create_loss_optimizer(self):
# is given.
reconstr_loss = \
1)
# 2.) The latent loss, which is defined as the Kullback Leibler divergence
# the prior.
- tf.square(self.z_mean)
- tf.exp(self.z_log_sigma_sq), 1)
self.optimizer = \
tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.cost)
"""
feed_dict={self.x: X})
return cost
space.
"""
if z_mu is None:
z_mu = np.random.normal(size=self.network_architecture["n_z"])
return self.sess.run(self.x_reconstr_mean,
feed_dict={self.z: z_mu})
return self.sess.run(self.x_reconstr_mean,
feed_dict={self.x: X})
vae = VariationalAutoencoder(network_architecture,
learning_rate=learning_rate,
batch_size=batch_size)
# Training cycle
avg_cost = 0.
for i in range(total_batch):
batch_xs, _ = mnist.train.next_batch(batch_size)
cost = vae.partial_fit(batch_xs)
# Compute average loss
if epoch % display_step == 0:
"cost=", "{:.9f}".format(avg_cost))
return vae
network_architecture = \
x_sample = mnist.test.next_batch(100)[0]
x_reconstruct = vae.reconstruct(x_sample)
plt.figure(figsize=(8, 12))
for i in range(5):
plt.subplot(5, 2, 2*i + 1)
plt.title("Test input")
plt.colorbar()
plt.subplot(5, 2, 2*i + 2)
plt.title("Reconstruction")
plt.colorbar()
plt.tight_layout()
plt.savefig('vae_tf_reconstruct.png')
network_architecture = \
z_mu = vae_2d.transform(x_sample)
plt.figure(figsize=(8, 6))
plt.colorbar()
plt.grid()
plt.savefig('vae_tf_mean.png')
nx = ny = 20
for i, yi in enumerate(x_values):
for j, xi in enumerate(y_values):
x_mean = vae_2d.generate(z_mu)
plt.figure(figsize=(8, 10))
plt.tight_layout()
plt.savefig('vae_tf_reconstruct.png')
OUTPUT
8. Gated recurrent unit implementation using tensorflow and keras for next character
prediction.