Friday, 24 May 2019

NN PY

#we create our feature set. It contains five records.
#Similarly, we created a labels set which contains corresponding labels for each record in the feature set.
#The labels are the answers we're trying to predict with the neural network.


import numpy as np 
feature_set = np.array([[0,1,0],[0,0,1],[1,0,0],[1,1,0],[1,1,1]]) 
labels = np.array([[1,0,0,1,1]]) 
labels = labels.reshape(5,1)

_________________________________________________

np.random.seed(42)  #random.seed function so that we can get the same random values whenever the script is executed.
weights = np.random.rand(3,1) 
bias = np.random.rand(1) 
lr = 0.05

_______________________________________________

def sigmoid(x):    #activation function is the sigmoid function
    return 1/(1+np.exp(-x))
_________________________________________________

def sigmoid_der(x):    #calculates the derivative of the sigmoid function
    return sigmoid(x)*(1-sigmoid(x))
_________________________________________________

#train our neural network that will be able to predict whether a person is obese or not.

# An epoch is basically the number of times we want to train the algorithm on our data.
#We will train the algorithm on our data 20,000 times. The ultimate goal is to minimize the error.

for epoch in range(20000): 
    inputs = feature_set

#Here we find the dot product of the input and the weight vector and add bias to it.

    # feedforward step1
    XW = np.dot(feature_set, weights) + bias
   
#We pass the dot product through the sigmoid activation function

    #feedforward step2
    z = sigmoid(XW)
   
#The variable z contains the predicted outputs. The first step of the backpropagation is to find the error.

    # backpropagation step 1
    error = z - labels

    print(error.sum())

    # backpropagation step 2
    dcost_dpred = error
    dpred_dz = sigmoid_der(z)
   
#Here we have the z_delta variable, which contains the product of dcost_dpred and dpred_dz.
#Instead of looping through each record and multiplying the input with corresponding z_delta,
#we take the transpose of the input feature matrix and multiply it with the z_delta.
#Finally, we multiply the learning rate variable lr with the derivative to increase the speed of convergence.

    z_delta = dcost_dpred * dpred_dz

    inputs = feature_set.T
    weights -= lr * np.dot(inputs, z_delta)

    for num in z_delta:
        bias -= lr * num
_______________________________________

#You can see that error is extremely small at the end of the training of our neural network.
#At this point of time our weights and bias will have values that can be used to detect whether a person is diabetic or not,
#based on his smoking habits, obesity, and exercise habits.

#TEST : suppose we have a record of a patient that comes in who smokes, is not obese, and doesn't exercise.
#Let's find if he is likely to be diabetic or not. The input feature will look like this: [1,0,0].

single_point = np.array([1,0,0]) 
result = sigmoid(np.dot(single_point, weights) + bias) 
print(result)
____________________________________________

#let's test another person who doesn't, smoke, is obese, and doesn't exercises. The input feature vector will be [0,1,0]

single_point = np.array([0,1,0]) 
result = sigmoid(np.dot(single_point, weights) + bias) 
print(result)
___________________________________________

#value is very close to 1, which is likely due to the person's obesity.
#Multiply the result by 100 percent to convert the accuracy to a percentage. For our thermometer example:
#Relative accuracy = Accuracy x 100 percent = 0.968 x 100 percent = 96.8 percent

A=0.00707584 * 100
B=0.99837029 * 100
print(A)
print(B)

Thursday, 23 May 2019

SVM R


# Importing the dataset

dataset = read.csv(‘social.csv')
dataset = dataset[3:5]

# Encoding the target feature as factor

dataset$Purchased = factor(dataset$Purchased, levels = c(0, 1))

###########################################

# Splitting the dataset into the Training set and Test set

install.packages('caTools')
library(caTools)

set.seed(123)
split = sample.split(dataset$Purchased, SplitRatio = 0.75)

training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
View(training_set)
View(test_set)

# Feature Scaling

training_set[-3] = scale(training_set[-3])
test_set[-3] = scale(test_set[-3])

View(training_set)
View(test_set)
##############################################

# Fitting SVM to the Training set
install.packages('e1071')
library(e1071)

classifier = svm(formula = Purchased ~ .,
                 data = training_set,
                 type = 'C-classification',
                 kernel = 'linear')

print(classifier)

# Predicting the Test set results

y_pred = predict(classifier, newdata = test_set[-3])


# Making the Confusion Matrix

cm = table(test_set[, 3], y_pred)
print(cm)
################################################

#Visualizing the Training set results

# installing library ElemStatLearn
library(ElemStatLearn)

# Plotting the training data set results
set = training_set
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)

grid_set = expand.grid(X1, X2)
colnames(grid_set) = c('Age', 'EstimatedSalary')
y_grid = predict(classifier, newdata = grid_set)

plot(set[, -3],
     main = 'SVM (Training set)',
     xlab = 'Age', ylab = 'Estimated Salary',
     xlim = range(X1), ylim = range(X2))

contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)
points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine'))
points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))

##################################################

#Visualizing the Test set results
set = test_set
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)

grid_set = expand.grid(X1, X2)
colnames(grid_set) = c('Age', 'EstimatedSalary')
y_grid = predict(classifier, newdata = grid_set)

plot(set[, -3], main = 'SVM (Test set)',
     xlab = 'Age', ylab = 'Estimated Salary',
     xlim = range(X1), ylim = range(X2))

contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)

points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine'))

points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))

#############################################

DT New

library("partykit")
airq <- subset(airquality, !is.na(Ozone))
ct <- ctree(Ozone ~ ., data = airq)
partykit:::.list.rules.party(ct)
________________________________________

detach("package:partykit", unload=TRUE)
library(party)
airct <- party::ctree(Ozone ~ ., data = airq)

t(sapply(unique(where(airct)), function(x) {
  n <- nodes(airct, x)[[1]]
  Ozone <- airq[as.logical(n$weights), "Ozone"]
  cbind.data.frame("Node" = as.integer(x),
                   "n" = length(Ozone),
                   "Avg."= mean(Ozone),
                   "Variance"= var(Ozone),
                   "SSE" = sum((Ozone - mean(Ozone))^2))
}))
___________________________________________

sum of squared errors of prediction (SSE)
_________________________________________

#print P values

terNodes <- unique(where(airct))
setdiff(1:max(terNodes), terNodes)

sapply(setdiff(1:max(terNodes), terNodes), function(x) {
          n <- nodes(airct, x)[[1]]
          pvalue <- 1 - nodes(airct, x)[[1]]$criterion$maxcriterion
          plab <- ifelse(pvalue < 10^(-3),
                         paste("p <", 10^(-3)),
                         paste("p =", round(pvalue, digits = 3)))
          c("Node" = x, "P-value" = plab)
})
________________________________________________
# print values from the node in ctree

a1=where(output)
table(a1)
print(a1)

input$x1=where(output)
View(input)

N4=subset(input,input$x1==4)
N5=subset(input,input$x1==5)
N6=subset(input,input$x1==6)
N7=subset(input,input$x1==7)

View(N1)


_________________________________________

RF

library(party)
library(randomForest)

# Create the forest.
output.forest <- randomForest(nativeSpeaker ~ age + shoeSize + score,
           data = readingSkills , importance =T)

# View the forest results.
print(output.forest)

fit=output.forest
print(importance(output.forest)) 

Wednesday, 22 May 2019

clustering


library(ggplot2)
df <- data.frame(age = c(18, 21, 22, 24, 26, 26, 27, 30, 31, 35, 39, 40, 41, 42, 44, 46, 47, 48, 49, 54),
    spend = c(10, 11, 22, 15, 12, 13, 14, 33, 39, 37, 44, 27, 29, 20, 28, 21, 30, 31, 23, 24))

ggplot(df, aes(x = age, y = spend)) + geom_point()



Clustering in R

library(tidyverse)  # data manipulation
library(cluster)    # clustering algorithms
library(factoextra)  # Visualization

################################3

View(USArrests)
df <- USArrests
df <- na.omit(df) #To remove any missing value
df <- scale(df)
head(df)

#################################

distance <- get_dist(df)

fviz_dist(distance, gradient = list(low = "#00AFBB", mid = "white", high = "#FC4E07"))

#################################


k2 <- kmeans(df, centers = 2, nstart = 2)
str(k2)

fviz_cluster(k2, data = df)

#################################


library(dplyr)
library(magrittr)
df %>%
  as_tibble() %>%
  mutate(cluster = k2$cluster,
         state = row.names(USArrests)) %>%
  ggplot(aes(UrbanPop, Murder, color = factor(cluster), label = state)) +
  geom_text()

###################################




k3 <- kmeans(df, centers = 3, nstart = 25)
k4 <- kmeans(df, centers = 4, nstart = 25)
k5 <- kmeans(df, centers = 5, nstart = 25)

# plots to compare
p1 <- fviz_cluster(k2, geom = "point", data = df) + ggtitle("k = 2")
p2 <- fviz_cluster(k3, geom = "point",  data = df) + ggtitle("k = 3")
p3 <- fviz_cluster(k4, geom = "point",  data = df) + ggtitle("k = 4")
p4 <- fviz_cluster(k5, geom = "point",  data = df) + ggtitle("k = 5")

library(gridExtra)
grid.arrange(p1, p2, p3, p4, nrow = 2)

######################################

Clustering optimization





set.seed(123)

gap_stat <- clusGap(df, FUN = kmeans, nstart = 25,
                    K.max = 10, B = 50)

# Print the result
print(gap_stat, method = "firstmax")

fviz_gap_stat(gap_stat)

final$cluster

View(df[final$cluster==1,])

#############################################

Hierarchical Cluster Analysis

# Dissimilarity matrix
d <- dist(df, method = "euclidean")

# Hierarchical clustering using Complete Linkage
hc1 <- hclust(d, method = "complete" )

# Plot the obtained dendrogram
plot(hc1, cex = 0.6, hang = -1)

##########################################

# Compute distance matrix
res.dist <- dist(df, method = "euclidean")

# Compute 2 hierarchical clusterings
hc1 <- hclust(res.dist, method = "complete")
hc2 <- hclust(res.dist, method = "ward.D2")

# Create two dendrograms
dend1 <- as.dendrogram (hc1)
dend2 <- as.dendrogram (hc2)

tanglegram(dend1, dend2)






KNN


prc <- read.csv("Prostate_Cancer.csv",stringsAsFactors = FALSE)   

stringsAsFactors = FALSE   #This command helps to convert every character vector to a factor wherever it makes sense.

str(prc)    #We use this command to see whether the data is structured or not.

prc <- prc[-1]  #removes the first variable(id) from the data set.

table(prc$diagnosis_result)  # it helps us to get the numbers of patients

prc$diagnosis <- factor(prc$diagnosis_result, levels = c("B", "M"), labels = c("Benign", "Malignant"))

round(prop.table(table(prc$diagnosis)) * 100, digits = 1)  # it gives the result in the percentage form rounded of to 1 decimal place( and so it’s digits = 1)

normalize <- function(x) {
  return ((x - min(x)) / (max(x) - min(x))) }

prc_n <- as.data.frame(lapply(prc[2:9], normalize))
summary(prc_n$radius)
prc_train <- prc_n[1:65,]
prc_test <- prc_n[66:100,]
prc_train_labels <- prc[1:65, 1]
prc_test_labels <- prc[66:100, 1]   #This code takes the diagnosis factor in column 1 of the prc data frame and on turn creates prc_train_labels and prc_test_labels data frame.

library(class)
prc_test_pred <- knn(train = prc_train, test = prc_test,cl = prc_train_labels, k=10)

#install.packages("gmodels")
library(gmodels)
CrossTable(x=prc_test_labels,y=prc_test_pred,prop.chisq = FALSE)

# Run for K value from 1 to 10, to find the best K value.

KVALUE <- seq(from=1,to=10,by=1)
for (K in 1:length(KVALUE)){
  prc_test_pred <- knn(train = prc_train, test = prc_test,cl = prc_train_labels, k=KVALUE[K])
  #prédiction check
  CrossTable(x=prc_test_labels,y=prc_test_pred,prop.chisq = FALSE)
}

Saturday, 18 May 2019

DL NN


!pip install tensorflow numpy scipy pillow matplotlib h5py keras
!pip install opencv-python




from imageai.Detection import ObjectDetection
import os

execution_path = os.getcwd()

detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.png"), output_image_path=os.path.join(execution_path , "image2new.jpg"), minimum_percentage_probability=30)

for eachObject in detections:
    print(eachObject["name"] , " : ", eachObject["percentage_probability"])
    print("--------------------------------")

E3


import cv2
import numpy as np
cap = cv2.VideoCapture(0)


while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()