Learn Python

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Introduction

Setup

ANN

Working process ANN

Propagation

Bias parameter

Activation function

Loss function

Overfitting and Underfitting

Optimization function

Chain rule

Minima

Gradient problem

Weight initialization

Dropout

ANN Regression Exercise

ANN Classification Exercise

Hyper parameter tuning

CNN

CNN basics

Convolution

Padding

Pooling

Data argumentation

Flattening

Create Custom Dataset

Binary Classification Exercise

Multiclass Classification Exercise

Transfer learning

Transfer model Basic template

RNN

How RNN works

LSTM

Bidirectional RNN

Sequence to sequence

Attention model

Transformer model

Bag of words

Tokenization & Stop words

Stemming & Lemmatization

TF-IDF

N-Gram

Word embedding

Normalization

Pos tagging

Parser

semantic analysis

Regular expression

Learn MySQL

Learn MongoDB

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Machine learning exercise 1

Dataset Link

Install keras

#!pip install keras-tuner
#!pip install keras

Importing Libraries

#Basic libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras import layers
from kerastuner.tuners import RandomSearch
from sklearn import metrics
from sklearn.metrics import confusion_matrix

Getting the data

df = pd.read_csv("D:/car data.csv")
df.head()

Let's gather some information

df.info()

df.isnull().sum()

Label encoding

df.replace({"Fuel_Type":{"Petrol":2,"Diesel":1,"CNG":0}},inplace=True)
df.replace({"Seller_Type":{"Dealer":1,"Individual":0}},inplace=True)
df.replace({"Transmission":{"Manual":1,"Automatic":0}},inplace=True)
df.drop(columns=["Car_Name"], axis=1, inplace=True) df.head()

Scaling the data

independent_features=df.drop(columns=["Selling_Price"], axis=1)
scaler= StandardScaler()
transform_scale_data=scaler.fit_transform(independent_features)
transform_scale_data

Separating the data and label

X=transform_scale_data
Y=df["Selling_Price"]

Splitting data into train and test data

X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2, random_state=1)

Creating ANN model

Initializing the model

'''
#Step 1:
Sequential is used to initializing our ANN model In this step we will create ann object by using a class of Keras named Sequential.
'''
ann=Sequential()

Adding the input layer and first hidden layer

'''
Step 2:
To adding different layers of ANN dense is used. In this code example we will create a neural netwrok where we will have one input layer, two hidden layer and one output layer
Let's create first input and hidden layer
'''
ann.add(Dense(units=4, input_dim=7, kernel_initializer='glorot_uniform',activation="relu", ))
ann.add(Dropout(rate = 0.1))
'''
Parameters:
1. units= Here we define the number of neurons of the hidden layer. Without parameter tuning, the number of hidden neurons should be half the size of the input layer. Here we have 7 features so we use 7 neurons in the input layer. So for hidden layer use half means 4 neurons. But again you can use any but it is better to use parameter tuning for selection.
2. input_dim= here we write the number of neurons of the input layer. The number of the neuron of the input layer is equal to the number of independent features or variables are present in the X_train or we can say the number of independent features which you want pass to the model.
3. kernel_initializer= Here we pass the name of weight initialization technique which we want to use.
4. activation= here we write the activation function name which we will use.
'''

Adding the Second Hidden layer

ann.add(Dense(units=6, kernel_initializer='he_normal', activation="relu"))
ann.add(Dropout(rate = 0.1))
'''
If you want to add more layers then do the same thing agin. You can change the value of the parameters if you want like change the number of neurons etc.
'''

Adding the third Hidden layer

ann.add(Dense(units=8, kernel_initializer='glorot_normal', activation="relu"))
ann.add(Dropout(rate = 0.1))

Adding the output layer

ann.add(Dense(units=1,kernel_initializer = 'uniform', activation="linear"))
'''
Here output_dim = 1 means in the output layer we want only one node or neuron.
'''

Compiling ANN

ann.compile(optimizer="adam",loss="mean_absolute_error",metrics=['mean_absolute_error'])
'''
Parameters: 1. optimizer= pass the name of the optimizer which you want to use
2. loss= pass the name of the loss function which you want to use
3. metrics= pass the name of the metrics which you want to use
'''

Fitting the the model

ann.fit(X_train,Y_train,validation_split=0.33,batch_size=12,epochs = 100)

R squared error training data

training_data_prediction=ann.predict(X_train)
score_using_r2_score=metrics.r2_score(Y_train,training_data_prediction)
score_using_r2_score

Visualization of the actual value and training data predicted value

plt.scatter(Y_train,training_data_prediction)
plt.xlabel("actual value")
plt.ylabel("Predicted value")
plt.show()

R squared error testing data

testing_data_prediction=ann.predict(X_test)
score_using_r2_score=metrics.r2_score(Y_test,testing_data_prediction)
score_using_r2_score

Visualization of the actual value and testing data predicted value

plt.scatter(Y_test,testing_data_prediction)
plt.xlabel("actual value")
plt.ylabel("Predicted value")
plt.show()

Make Prediction

test_predictions = ann.predict(X_test).flatten()
results_df = pd.DataFrame({'Predicted Price': test_predictions,'Actual Price':Y_test.values.flatten()})
results_df.head(10)

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.