Posts

Showing posts from November, 2022

Softmax Regession Exp-3

  import tensorflow as tf from tensorflow import keras import numpy as np (( train_data , train_labels ), ( mnist_data , mnist_labels ))= tf .keras.datasets.mnist.load_data() train_data = train_data / np .float32( 255 ) train_labels = train_labels .astype( np .int32) mnist_data = mnist_data / np .float32( 255 ) mnist_labels = mnist_labels .astype( np .int32) feature_columns =[ tf .feature_column.numeric_column( "x" , shape =[ 28 , 28 ])] classifier = tf .estimator.LinearClassifier(     feature_columns = feature_columns ,     n_classes = 10 ,     model_dir = "mnist_model/" ) train_input_fn = tf .compat.v1.estimator.inputs.numpy_input_fn(         x ={ "x" : train_data },         y = train_labels ,             batch_size = 100 ,             num_epochs = None ,             shuffle = True ) classifier .train( input_fn = train_input_fn , steps = 5 ) val_input_fn = tf .compat.v1.estimator.inputs.numpy_input_fn(         x ={ "x" : mnist_data },    

Single and Multi layer

  # -*- coding: utf-8 -*- """Single and Multi Layer Perceptron.ipynb Automatically generated by Colaboratory. Original file is located at     https://colab.research.google.com/drive/1sUwF-aPoUh-5eiqZRHDTrFQqz01k8xZs """ # importing modules import tensorflow as tf import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Dense from tensorflow.keras.layers import Activation import matplotlib.pyplot as plt import plotly.express as px (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # Cast the records into float values x_train = x_train.astype( 'float32' ) x_test = x_test.astype( 'float32' ) # normalize image pixel values by dividing # by 255 gray_scale = 255 x_train /= gray_scale x_test /= gray_scale print ( "Feature matrix:" , x_train.shape) print ( "Target matrix:" , x_test.shape) print ( "

Kernal implementaion Exp-7

import numpy as np import cv2 import matplotlib . pyplot as plt img = cv2 .imread( 'butterfly.jpg' ) gray = cv2 .cvtColor( img , cv2 .COLOR_BGR2GRAY) blur = cv2 .GaussianBlur( gray , ( 5 , 5 ), 0 ) # Robert Edge Detection kernelxx = np .array([[ 1 , 0 ], [ 0 , - 1 ]]) kernelyy = np .array([[ 0 , 1 ], [- 1 , 0 ]]) img_robertx = cv2 .filter2D( img , - 1 , kernelxx ) img_roberty = cv2 .filter2D( img , - 1 , kernelyy ) grad = cv2 .addWeighted( img_robertx , 0.5 , img_roberty , 0.5 , 0 ) plt . imshow ( grad , cmap = 'gray' ) plt . title ( "Robert Edge Detection" ) plt . axis ( 'off' ) # Laplacian laplacian = cv2 .Laplacian( img , cv2 .CV_64F) sobelx = cv2 .Sobel( src = blur , ddepth = cv2 .CV_64F, dx = 1 , dy = 0 , ksize = 3 ) sobely = cv2 .Sobel( src = blur , ddepth = cv2 .CV_64F, dx = 0 , dy = 1 , ksize = 3 ) fig , axs = plt . subplots ( 2 , 2 ) titles = [ 'Original' , 'Sobel along X-axis' , 'Sobel along Y-axis'

Edge Dedection Exp-6

import cv2 import matplotlib . pyplot as plt import numpy as np # Canny img = cv2 .imread( 'butterfly.jpg' ) # converting the image to grayscale gray = cv2 .cvtColor( img , cv2 .COLOR_BGR2GRAY) blur = cv2 .GaussianBlur( gray , ( 5 , 5 ), 0 ) # the second parm is the size of the kernel # wider the threshold range, more the edges canny = cv2 .Canny( img , threshold1 = 180 , threshold2 = 200 ) fig , axs = plt . subplots ( 2 , 2 ) titles = [ 'Original' , 'Grayscale' , 'Gaussian Blur' , 'Canny' ] axs [ 0 , 0 ].imshow( cv2 .cvtColor( img , cv2 .COLOR_BGR2RGB)) axs [ 0 , 0 ].set_title( titles [ 0 ]) axs [ 0 , 0 ].axis( 'off' ) axs [ 0 , 1 ].imshow( cv2 .cvtColor( gray , None )) axs [ 0 , 1 ].set_title( titles [ 1 ]) axs [ 0 , 1 ].axis( 'off' ) axs [ 1 , 0 ].imshow( cv2 .cvtColor( blur , None )) axs [ 1 , 0 ].set_title( titles [ 2 ]) axs [ 1 , 0 ].axis( 'off' ) axs [ 1 , 1 ].imshow( cv2 .cvtColor( canny , None )) axs

MLP Exp-5

 import tensorflow as tf import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Dense from tensorflow.keras.layers import Activation import matplotlib.pyplot as plt (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # Cast the records into float values x_train = x_train.astype('float32') x_test = x_test.astype('float32')    # normalize image pixel values by dividing  # by 255 gray_scale = 255 x_train /= gray_scale x_test /= gray_scale print("Feature matrix:", x_train.shape) print("Target matrix:", x_test.shape) print("Feature matrix:", y_train.shape) print("Target matrix:", y_test.shape) fig, ax = plt.subplots(10, 10) k = 0 for i in range(10):     for j in range(10):         ax[i][j].imshow(x_train[k].reshape(28, 28),                          aspect='auto')         k += 1 plt.show() model = Sequential([       

SLP EXP-4

from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.activations import hard_sigmoid import matplotlib.pyplot as plt from keras.callbacks import History import pandas as pd import numpy as np history=History() if _name_ == "_main_":     # Load the Pima diabetes dataset from CSV     # and convert into a NumPy matrix suitable for     # extraction into X, y format needed for TensorFlow     diabetes = pd.read_csv('/home/user/Downloads/diabetes.csv').values     # Extract the feature columns and outcome response     # into appropriate variables     X = diabetes[:, 0:8].astype(np.float32)     y = diabetes[:, 8].astype(np.float32)     # Create the 'Perceptron' using the Keras API     model = Sequential()     model.add(Dense(1, input_shape=(8,), activation=hard_sigmoid, kernel_initializer='glorot_uniform'))     model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accu

LINEAR RESGRESSION EXP-2

Ex2 import numpy as np import tensorflow.compat.v1 as tf import matplotlib.pyplot as plt tf.disable_v2_behavior() #fixing seeds np.random.seed(101) tf.set_random_seed(101) # Generating random linear data x = np.linspace(0, 50, 50) y = np.linspace(0, 50, 50) # Adding noise to the random linear data x += np.random.uniform(-4, 4, 50) y += np.random.uniform(-4, 4, 50) n = len(x) # Plot of Training Data plt.scatter(x, y) plt.xlabel('x') plt.ylabel('y') plt.title("Training Data") plt.show() X = tf.placeholder("float") Y = tf.placeholder("float") #defining weights and bias W = tf.Variable(np.random.randn(), name = "W") b = tf.Variable(np.random.randn(), name = "b") #hyperparameters lr = 0.01 epochs = 100 # Hypothesis y_pred = tf.add(tf.multiply(X, W), b) # Mean Squared Error Cost Function cost = tf.reduce_sum(tf.pow(y_pred-Y, 2)) / (2 * n) # Gradient Descent Optimizer optimizer = tf.train.GradientDescentOptimizer(lr).minimize(c