dl1 = """
1. DEEP NEURAL NETWORK MODEL
pip install tensorflow
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow import keras
X=np.array([6,7,8,9,10], dtype= float)
y=3*X+2
model=keras.Sequential([keras.layers.Dense(1,input_shape=[1])])
model.compile(
optimizer='adam',
loss='mse')
print("Training the model...")
history=model.fit(X,y,epochs=500,verbose=0)
weights=model.layers[0].get_weights()
print("\\nLearned Weight(slope):", weights[0][0][0])
print("Learned Bias:", weights[1][0])
test_value=np.array([10], dtype=float)
prediction=model.predict(test_value)[0][0]
print(f"\\n prediction for x=10:{prediction}")
plt.plot(history.history['loss'])
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.title("Training Loss Curve")
plt.show()
"""

dl2 = """
2. SPEECH TO TEXT
pip install SpeechRecognition pyaudio
import speech_recognition as sr
recognizer=sr.Recognizer()
AUDIO_FILE="audio.wav"
try:
with sr.AudioFile(AUDIO_FILE) as source:
print("Processing audio file: (AUDIO_FILE)")
audio=recognizer.listen(source)
text=recognizer.recognize_google(audio)
print("Transcribed text:",text)
except sr.UnknownValueError:
print("sorry, I could not understand the audio.")
except sr.RequestError as e:
print("could not request results; {e}")
except FileNotFoundError:
print(f"Error: the audio file '{AUDIO_FILE}' was not found. pls check the path.")
except Exception as e:
print(f" An unexpected error occured :{e}")
"""

dl3 = """
3. TEXT TO SPEECH
pip install pyttsx3
import pyttsx3
engine=pyttsx3.init()
engine.setProperty('rate',170)
engine.setProperty('volume',0.9)
voices=engine.getProperty('voices')
engine.setProperty('voive', voices[1].id)
text=input("enter the text to convert to speech:")
engine.say(text)
engine.runAndWait()
"""

dl4 = """
4. TIME SERIES FORECASTING WITH LSTM MODEL
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
time = np.arange(0, 100, 0.1)
data = np.sin(time)
df = pd.DataFrame(data, columns=['value'])
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df)
def create_sequences(data, time_step=10):
x, y = [], []
for i in range(len(data) - time_step):
x.append(data[i:(i + time_step), 0])
y.append(data[i + time_step, 0])
return np.array(x), np.array(y)
time_step = 10
x, y = create_sequences(scaled_data, time_step)
x = x.reshape(x.shape[0], x.shape[1], 1)
train_size = int(len(x) * 0.8)
x_train = x[:train_size]
x_test = x[train_size:]
y_train = y[:train_size]
y_test = y[train_size:]
model = Sequential()
model.add(LSTM(50, input_shape=(time_step, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=10, batch_size=32, verbose=1)
train_predict = model.predict(x_train)
test_predict = model.predict(x_test)
train_predict = scaler.inverse_transform(train_predict)
y_train_actual = scaler.inverse_transform([y_train])
test_predict = scaler.inverse_transform(test_predict)
y_test_actual = scaler.inverse_transform([y_test])
train_score = np.sqrt(mean_squared_error(y_train_actual[0], train_predict[:,0]))
test_score = np.sqrt(mean_squared_error(y_test_actual[0], test_predict[:,0]))
print(f'Train Score: {train_score:.2f} RMSE')
print(f'Test Score: {test_score:.2f} RMSE')
plt.figure(figsize=(10,5))
plt.plot(df.values,label="actual data")
train_plot = np.empty_like(scaled_data)
train_plot[:] = np.nan
train_plot[time_step:train_size+time_step, :] = train_predict
test_plot = np.empty_like(scaled_data)
test_plot[:] = np.nan
test_plot[train_size+time_step:] = test_predict
plt.title('LSTM Sine Wave Prediction')
plt.plot(scaler.inverse_transform(scaled_data), label='Actual Data')
plt.plot(train_plot, label='Training Prediction')
plt.plot(test_plot, label='Testing Prediction')
plt.legend()
plt.show()
"""

dl5a = """
5A. FEED FORWARD NEURAL NETWORK FOR PREDICTION OF INDIVIDUAL LOGIC GATE
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
inputs=np.array([[0,0],[0,1],[1,0],[1,1]])
#AND GATE
outputs=np.array([[0],[0],[0],[1]])
#OR GATE
outputs=np.array([[0],[1],[1],[1]])
#XOR GATE
outputs=np.array([[0],[1],[1],[0]])
model=Sequential()
model.add(Dense(4,input_dim=2,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
model.fit(inputs,outputs,epochs=3000,verbose=0)
predictions=model.predict(inputs)
print("\\n Predictions")
for i, p in enumerate(predictions):
print(f"{inputs[i]} => {round(float(p))} (raw:{float(p):.4f})")
"""

dl5b = """
5B. FEED FORWARD NEURAL NETWORK FOR PREDICTION OF MULTIPLE LOGIC GATES
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
inputs = np.array([[0,0],[0,1],[1,0],[1,1]])
outputs = np.array([
[0,0,0],
[0,1,1],
[0,1,1],
[1,1,0]
])
model = Sequential()
model.add(Dense(6, input_dim=2, activation='relu'))
model.add(Dense(3, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(inputs, outputs, epochs=4000, verbose=0)
predictions = model.predict(inputs)
print("\\nPredictions:")
for i, p in enumerate(predictions):
print(f"{inputs[i]} => AND:{round(p[0])} (raw:{p[0]:.4f}), "
f"OR:{round(p[1])} (raw:{p[1]:.4f}), "
f"XOR:{round(p[2])} (raw:{p[2]:.4f})")
"""

dl6a = """
6A. RGB TO GRAYSCALE
pip install scikit-image
from skimage import data
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
plt.figure(figsize=(15,15))
coffee=data.coffee()
plt.subplot(1,2,1)
plt.imshow(coffee)
gray_coffee=rgb2gray(coffee)
plt.subplot(1,2,2)
plt.imshow(gray_coffee,cmap="gray")
plt.show()
"""

dl6b = """
6B. RGB TO HSV
from skimage import data
from skimage.color import rgb2hsv
import matplotlib.pyplot as plt
plt.figure(figsize=(15,15))
coffee=data.coffee()
plt.subplot(1,2,1)
plt.imshow(coffee)
hsv_coffee=rgb2hsv(coffee)
plt.subplot(1,2,2)
hsv_coffee_colorbar=plt.imshow(hsv_coffee)
plt.colorbar(hsv_coffee_colorbar,fraction=0.046,pad=0.04)
plt.show()
"""

dl6c = """
6C. SUPERVISED SEGMENTATION
from skimage import data
from skimage import filters
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
coffee=data.coffee()
gray_coffee=rgb2gray(coffee)
plt.figure(figsize=(15,15))
for i in range(10):
binarized_gray=(gray_coffee>i*0.1)*1
plt.subplot(5,2,i+1)
plt.title("threshold:>"+str(round(i*0.1,1)))
plt.imshow(binarized_gray,cmap='gray')
plt.tight_layout()
plt.show()
"""

dl7 = """
7. OBJECT DETECTION USING IMAGE
pip install ultralytics opencv-python
from ultralytics import YOLO
import cv2
model=YOLO("yolov8n.pt")
results=model("nun.jpg")
for r in results:
img=r.plot()
cv2.imshow("Detection Result", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
"""

dl8 = """
8. CHARACTER RECOGNITION USING CNN
pip install opencv-python
import tensorflow as tf
from tensorflow.keras import layers, models
import cv2
import numpy as np
import matplotlib.pyplot as plt
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
x_train = x_train.reshape((len(x_train), 28, 28, 1))
x_test = x_test.reshape((len(x_test), 28, 28, 1))
model = models.Sequential([
layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D((2,2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
img = cv2.imread("number.png", cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img,(28,28))
img = img.astype('float32') / 255.0
img = img.reshape(1, 28, 28, 1)
prediction = model.predict(img)
predicted_digit = np.argmax(prediction)
print("Predicted Digit:", predicted_digit)
plt.imshow(img.reshape(28,28), cmap='gray')
plt.title(f"Predicted: {predicted_digit}")
plt.show()
"""

dl9 = """
9. AUTOENCODER USING MNIST HANDWRITTEN DIGITS
PROGRAM
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
(x_train, _), (x_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), 784))
x_test = x_test.reshape((len(x_test), 784))
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)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
autoencoder.fit(x_train, x_train, epochs=20, batch_size=256, shuffle=True, validation_data=(x_test, x_test))
decoded_imgs = autoencoder.predict(x_test)
n = 10
plt.figure(figsize=(20, 4))
for i in range(n):
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)
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()
"""