CNN and RNN code
CNN and RNN code
import numpy as np
import tensorflow as tf
plt.rc('figure', autolayout=True)
plt.rc('image', cmap='magma')
[-1, 8, -1],
])
image = tf.io.read_file('Ganesh.jpg')
img = tf.squeeze(image).numpy()
plt.figure(figsize=(5, 5))
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.title('Original Gray Scale image')
plt.show();
# Reformat
# convolution layer
conv_fn = tf.nn.conv2d
image_filter = conv_fn(
input=image,
filters=kernel,
strides=1, # or (1, 1)
padding='SAME',
plt.figure(figsize=(15, 5))
plt.subplot(1, 3, 1)
plt.imshow(
tf.squeeze(image_filter)
)
plt.axis('off')
plt.title('Convolution')
# activation layer
relu_fn = tf.nn.relu
# Image detection
image_detect = relu_fn(image_filter)
plt.subplot(1, 3, 2)
plt.imshow(
tf.squeeze(image_detect)
plt.axis('off')
plt.title('Activation')
# Pooling layer
pool = tf.nn.pool
image_condense = pool(input=image_detect,
window_shape=(2, 2),
pooling_type='MAX',
strides=(2, 2),
padding='SAME',
)
plt.subplot(1, 3, 3)
plt.imshow(tf.squeeze(image_condense))
plt.axis('off')
plt.title('Pooling')
plt.show()
import numpy as np
2
import tensorflow as tf
3
chars = sorted(list(set(text)))
3
char_to_index = {char: i for i, char in enumerate(chars)}
4
seq_length = 3
2
sequences = []
3
labels = []
4
labels.append(char_to_index[label])
10
11
X = np.array(sequences)
12
y = np.array(labels)
Step 4: Convert Sequences and Labels to One-Hot Encoding
For training, we convert X and y into one-hot encoded tensors.
Python
1
X_one_hot = tf.one_hot(X, len(chars))
2
model = Sequential()
2
model.add(Dense(len(chars), activation='softmax'))
Step 6: Compile and Train the Model
We compile the model using the categorical_crossentropy loss and
train it for 100 epochs.
Python
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
2
generated_text = start_seq
3
for i in range(50):
5
prediction = model.predict(x_one_hot)
8
next_index = np.argmax(prediction)
9
next_char = index_to_char[next_index]
10
generated_text += next_char
11
12
print("Generated Text:")
13
print(generated_text)
Output:
Generated Text: This is Geeks a software training instituteais
is is is is
Complete Code
# Step 1: Import necessary libraries
import numpy as np
import tensorflow as tf
chars = sorted(list(set(text)))
seq_length = 3
sequences = []
labels = []
labels.append(char_to_index[label])
X = np.array(sequences)
y = np.array(labels)
model = Sequential()
model.add(Dense(len(chars), activation='softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
generated_text = start_seq
for i in range(50):
prediction = model.predict(x_one_hot)
next_index = np.argmax(prediction)
next_char = index_to_char[next_index]
generated_text += next_char
print("Generated Text:")
print(generated_text)