Tuesday, 30 July 2019

shiny2

library(shiny)
ui<-fluidPage(
  sidebarPanel(
    sliderInput("num","integer",1,200,5,step=1,animate = animationOptions(interval = 1000,loop = TRUE))),
  radioButtons("radio",label = h1("Choose one"),choices = list("Table"=1,"Even/Odd"=2,"Fact"=3),selected = 1),
  hr(),
  mainPanel(
    tableOutput("abc")
  )
)


server<-function(input,output)
{
 
    output$abc<-renderPrint({
      r<-input$radio
      x<-input$num
      if(r==1){
        for(i in 1:10)
        {
          cat(x,"X",i,"=",x*i,"<br>")
        }
      }else if(r==2)
      {
        if(x%%2==0)
        {
          print("Even")
        }else{
          print("Odd")
        }
      }
      else{
        print(factorial(x))
      }
    })
   
}   
   
shinyApp(ui=ui,server=server)

Shiny1

library(shiny)
ui <- fluidPage(
   titlePanel("TABLE"),
    sidebarLayout(
      sidebarPanel(
        sliderInput("num", "integer", 1, 20, 1,
                    step = 1, animate =
                      animationOptions(interval=400, loop=TRUE))),
      mainPanel(
        tableOutput("prod")
      )) )


server <- function(input, output) {
    output$prod <- renderPrint({ x<-input$num
    for(i in 1:10){
      a=x*i
      cat(x,"x",i,"=",a,"<br>")
       }})}

shinyApp(ui = ui, server = server)

Friday, 26 July 2019

Real time object detection


import cv2
import numpy as np
cam = cv2.VideoCapture(0)
cv2.namedWindow("test")
img_counter = 0
while True:
    ret, frame = cam.read()
    cv2.imshow("test", frame)
    if not ret:
        break
    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
print("Escape hit, closing...")
        break
elif k%256 == 32:
        # SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()

Wednesday, 24 July 2019

GUI with Python

# import openpyxl and tkinter modules
from openpyxl import *
from tkinter import *
 
# globally declare wb and sheet variable
 
# opening the existing excel file
wb = load_workbook('C:\\Users\\Manish\\Desktop\\excel.xlsx')
 
# create the sheet object
sheet = wb.active
 
 
def excel():
     
    # resize the width of columns in
    # excel spreadsheet
    sheet.column_dimensions['A'].width = 30
    sheet.column_dimensions['B'].width = 10
    sheet.column_dimensions['C'].width = 10
    sheet.column_dimensions['D'].width = 20
    sheet.column_dimensions['E'].width = 20
    sheet.column_dimensions['F'].width = 40
    sheet.column_dimensions['G'].width = 50
 
    # write given data to an excel spreadsheet
    # at particular location
    sheet.cell(row=1, column=1).value = "Name"
    sheet.cell(row=1, column=2).value = "Course"
    sheet.cell(row=1, column=3).value = "Semester"
    sheet.cell(row=1, column=4).value = "Form Number"
    sheet.cell(row=1, column=5).value = "Contact Number"
    sheet.cell(row=1, column=6).value = "Email id"
    sheet.cell(row=1, column=7).value = "Address"
 
 
# Function to set focus (cursor)
def focus1(event):
    # set focus on the course_field box
    course_field.focus_set()
 
 
# Function to set focus
def focus2(event):
    # set focus on the sem_field box
    sem_field.focus_set()
 
 
# Function to set focus
def focus3(event):
    # set focus on the form_no_field box
    form_no_field.focus_set()
 
 
# Function to set focus
def focus4(event):
    # set focus on the contact_no_field box
    contact_no_field.focus_set()
 
 
# Function to set focus
def focus5(event):
    # set focus on the email_id_field box
    email_id_field.focus_set()
 
 
# Function to set focus
def focus6(event):
    # set focus on the address_field box
    address_field.focus_set()
 
 
# Function for clearing the
# contents of text entry boxes
def clear():
     
    # clear the content of text entry box
    name_field.delete(0, END)
    course_field.delete(0, END)
    sem_field.delete(0, END)
    form_no_field.delete(0, END)
    contact_no_field.delete(0, END)
    email_id_field.delete(0, END)
    address_field.delete(0, END)
 
 
# Function to take data from GUI 
# window and write to an excel file
def insert():
     
    # if user not fill any entry
    # then print "empty input"
    if (name_field.get() == "" and
        course_field.get() == "" and
        sem_field.get() == "" and
        form_no_field.get() == "" and
        contact_no_field.get() == "" and
        email_id_field.get() == "" and
        address_field.get() == ""):
             
        print("empty input")
 
    else:
 
        # assigning the max row and max column
        # value upto which data is written
        # in an excel sheet to the variable
        current_row = sheet.max_row
        current_column = sheet.max_column
 
        # get method returns current text
        # as string which we write into
        # excel spreadsheet at particular location
        sheet.cell(row=current_row + 1, column=1).value = name_field.get()
        sheet.cell(row=current_row + 1, column=2).value = course_field.get()
        sheet.cell(row=current_row + 1, column=3).value = sem_field.get()
        sheet.cell(row=current_row + 1, column=4).value = form_no_field.get()
        sheet.cell(row=current_row + 1, column=5).value = contact_no_field.get()
        sheet.cell(row=current_row + 1, column=6).value = email_id_field.get()
        sheet.cell(row=current_row + 1, column=7).value = address_field.get()
 
        # save the file
        wb.save('C:\\Users\\Manish\\Desktop\\excel.xlsx')
 
        # set focus on the name_field box
        name_field.focus_set()
 
        # call the clear() function
        clear()
 
 
# Driver code
if __name__ == "__main__":
     
    # create a GUI window
    root = Tk()
 
    # set the background colour of GUI window
    root.configure(background='light green')
 
    # set the title of GUI window
    root.title("registration form")
 
    # set the configuration of GUI window
    root.geometry("500x300")
 
    excel()
 
    # create a Form label
    heading = Label(root, text="Form", bg="light green")
 
    # create a Name label
    name = Label(root, text="Name", bg="light green")
 
    # create a Course label
    course = Label(root, text="Course", bg="light green")
 
    # create a Semester label
    sem = Label(root, text="Semester", bg="light green")
 
    # create a Form No. lable
    form_no = Label(root, text="Form No.", bg="light green")
 
    # create a Contact No. label
    contact_no = Label(root, text="Contact No.", bg="light green")
 
    # create a Email id label
    email_id = Label(root, text="Email id", bg="light green")
 
    # create a address label
    address = Label(root, text="Address", bg="light green")
 
    # grid method is used for placing
    # the widgets at respective positions
    # in table like structure .
    heading.grid(row=0, column=1)
    name.grid(row=1, column=0)
    course.grid(row=2, column=0)
    sem.grid(row=3, column=0)
    form_no.grid(row=4, column=0)
    contact_no.grid(row=5, column=0)
    email_id.grid(row=6, column=0)
    address.grid(row=7, column=0)
 
    # create a text entry box
    # for typing the information
    name_field = Entry(root)
    course_field = Entry(root)
    sem_field = Entry(root)
    form_no_field = Entry(root)
    contact_no_field = Entry(root)
    email_id_field = Entry(root)
    address_field = Entry(root)
 
    # bind method of widget is used for
    # the binding the function with the events
 
    # whenever the enter key is pressed
    # then call the focus1 function
    name_field.bind("<Return>", focus1)
 
    # whenever the enter key is pressed
    # then call the focus2 function
    course_field.bind("<Return>", focus2)
 
    # whenever the enter key is pressed
    # then call the focus3 function
    sem_field.bind("<Return>", focus3)
 
    # whenever the enter key is pressed
    # then call the focus4 function
    form_no_field.bind("<Return>", focus4)
 
    # whenever the enter key is pressed
    # then call the focus5 function
    contact_no_field.bind("<Return>", focus5)
 
    # whenever the enter key is pressed
    # then call the focus6 function
    email_id_field.bind("<Return>", focus6)
 
    # grid method is used for placing
    # the widgets at respective positions
    # in table like structure .
    name_field.grid(row=1, column=1, ipadx="100")
    course_field.grid(row=2, column=1, ipadx="100")
    sem_field.grid(row=3, column=1, ipadx="100")
    form_no_field.grid(row=4, column=1, ipadx="100")
    contact_no_field.grid(row=5, column=1, ipadx="100")
    email_id_field.grid(row=6, column=1, ipadx="100")
    address_field.grid(row=7, column=1, ipadx="100")
 
    # call excel function
    excel()
 
    # create a Submit Button and place into the root window
    submit = Button(root, text="Submit", fg="Black",
                            bg="Red", command=insert)
    submit.grid(row=8, column=1)
 
    # start the GUI
    root.mainloop() 

ANN



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)


# In[3]:


labels


# In[8]:


#define hyper parameters for our neural network

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


# In[9]:


weights  #Return a sample (or samples) from the “standard normal” distribution( “normal” (Gaussian) distribution of mean 0 and variance 1)


# In[10]:


bias #Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1)


# In[11]:


lr # learning rate


# In[12]:


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


# In[13]:


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


# In[14]:


#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


# In[15]:


#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)


# In[ ]:


#You can see that the person is likely not diabetic since the value is much closer to 0 than 1.


# In[16]:


#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) 


# In[18]:


#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)

Reg2 GUI

from pandas import DataFrame
from sklearn import linear_model
import tkinter as tk
import statsmodels.api as sm

Stock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
                'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
                'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
                'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]       
                }


df = DataFrame(Stock_Market,columns=['Year','Month','Interest_Rate','Unemployment_Rate','Stock_Index_Price'])

X = df[['Interest_Rate','Unemployment_Rate']] # here we have 2 input variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example.Alternatively, you may add additional variables within the brackets
Y = df['Stock_Index_Price'] # output variable (what we are trying to predict)

# with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)


# with statsmodels
X = sm.add_constant(X) # adding a constant

model = sm.OLS(Y, X).fit()
predictions = model.predict(X)



# tkinter GUI
root= tk.Tk()

canvas1 = tk.Canvas(root, width = 1200, height = 450)
canvas1.pack()

# with sklearn
Intercept_result = ('Intercept: ', regr.intercept_)
label_Intercept = tk.Label(root, text=Intercept_result, justify = 'center')
canvas1.create_window(260, 220, window=label_Intercept)

# with sklearn
Coefficients_result  = ('Coefficients: ', regr.coef_)
label_Coefficients = tk.Label(root, text=Coefficients_result, justify = 'center')
canvas1.create_window(260, 240, window=label_Coefficients)

# with statsmodels
print_model = model.summary()
label_model = tk.Label(root, text=print_model, justify = 'center', relief = 'solid', bg='LightSkyBlue1')
canvas1.create_window(800, 220, window=label_model)


# New_Interest_Rate label and input box
label1 = tk.Label(root, text='Type Interest Rate: ')
canvas1.create_window(100, 100, window=label1)

entry1 = tk.Entry (root) # create 1st entry box
canvas1.create_window(270, 100, window=entry1)

# New_Unemployment_Rate label and input box
label2 = tk.Label(root, text=' Type Unemployment Rate: ')
canvas1.create_window(120, 120, window=label2)

entry2 = tk.Entry (root) # create 2nd entry box
canvas1.create_window(270, 120, window=entry2)


def values():
    global New_Interest_Rate #our 1st input variable
    New_Interest_Rate = float(entry1.get())
   
    global New_Unemployment_Rate #our 2nd input variable
    New_Unemployment_Rate = float(entry2.get())
   
    Prediction_result  = ('Predicted Stock Index Price: ', regr.predict([[New_Interest_Rate ,New_Unemployment_Rate]]))
    label_Prediction = tk.Label(root, text= Prediction_result, bg='orange')
    canvas1.create_window(260, 280, window=label_Prediction)
   
button1 = tk.Button (root, text='Predict Stock Index Price',command=values, bg='orange') # button to call the 'values' command above
canvas1.create_window(270, 150, window=button1)


root.mainloop()

GUI reg

from pandas import DataFrame
from sklearn import linear_model
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

Stock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
                'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
                'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
                'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]       
                }

df = DataFrame(Stock_Market,columns=['Year','Month','Interest_Rate','Unemployment_Rate','Stock_Index_Price'])

X = df[['Interest_Rate','Unemployment_Rate']].astype(float) # here we have 2 input variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example.Alternatively, you may add additional variables within the brackets
Y = df['Stock_Index_Price'].astype(float) # output variable (what we are trying to predict)

# with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)


# tkinter GUI
root= tk.Tk()

canvas1 = tk.Canvas(root, width = 500, height = 300)
canvas1.pack()

# with sklearn
Intercept_result = ('Intercept: ', regr.intercept_)
label_Intercept = tk.Label(root, text=Intercept_result, justify = 'center')
canvas1.create_window(260, 220, window=label_Intercept)

# with sklearn
Coefficients_result  = ('Coefficients: ', regr.coef_)
label_Coefficients = tk.Label(root, text=Coefficients_result, justify = 'center')
canvas1.create_window(260, 240, window=label_Coefficients)


# New_Interest_Rate label and input box
label1 = tk.Label(root, text='Type Interest Rate: ')
canvas1.create_window(100, 100, window=label1)

entry1 = tk.Entry (root) # create 1st entry box
canvas1.create_window(270, 100, window=entry1)

# New_Unemployment_Rate label and input box
label2 = tk.Label(root, text=' Type Unemployment Rate: ')
canvas1.create_window(120, 120, window=label2)

entry2 = tk.Entry (root) # create 2nd entry box
canvas1.create_window(270, 120, window=entry2)


def values():
    global New_Interest_Rate #our 1st input variable
    New_Interest_Rate = float(entry1.get())
   
    global New_Unemployment_Rate #our 2nd input variable
    New_Unemployment_Rate = float(entry2.get())
   
    Prediction_result  = ('Predicted Stock Index Price: ', regr.predict([[New_Interest_Rate ,New_Unemployment_Rate]]))
    label_Prediction = tk.Label(root, text= Prediction_result, bg='orange')
    canvas1.create_window(260, 280, window=label_Prediction)
   
button1 = tk.Button (root, text='Predict Stock Index Price',command=values, bg='orange') # button to call the 'values' command above
canvas1.create_window(270, 150, window=button1)


#plot 1st scatter
figure3 = plt.Figure(figsize=(5,4), dpi=100)
ax3 = figure3.add_subplot(111)
ax3.scatter(df['Interest_Rate'].astype(float),df['Stock_Index_Price'].astype(float), color = 'r')
scatter3 = FigureCanvasTkAgg(figure3, root)
scatter3.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
ax3.legend()
ax3.set_xlabel('Interest Rate')
ax3.set_title('Interest Rate Vs. Stock Index Price')

#plot 2nd scatter
figure4 = plt.Figure(figsize=(5,4), dpi=100)
ax4 = figure4.add_subplot(111)
ax4.scatter(df['Unemployment_Rate'].astype(float),df['Stock_Index_Price'].astype(float), color = 'g')
scatter4 = FigureCanvasTkAgg(figure4, root)
scatter4.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
ax4.legend()
ax4.set_xlabel('Unemployment_Rate')
ax4.set_title('Unemployment_Rate Vs. Stock Index Price')

root.mainloop()

Tuesday, 23 July 2019

smile det

import cv2

faceCascade = cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml')
smileCascade= cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_smile.xml')

# grab the reference to the webcam
vs = cv2.VideoCapture(0)

# keep looping
while True:
# grab the current frame
ret, frame = vs.read()
 
# if we are viewing a video and we did not grab a frame,
# then we have reached the end of the video
if frame is None:
break

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)

faces = faceCascade.detectMultiScale(frame, scaleFactor=1.05, minNeighbors=5, minSize=(45, 45))

for (x,y,w,h) in faces:
#cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
face_gray = gray[y:y+h, x:x+w]
face_color = frame[y:y+h, x:x+w]
smiles = smileCascade.detectMultiScale(face_gray, scaleFactor=1.7, minNeighbors=3, minSize=(15, 15))
for (ex,ey,ew,eh) in smiles:
cv2.rectangle(face_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),1)

# show the frame to our screen
cv2.imshow("Video", frame)
key = cv2.waitKey(1) & 0xFF

# if the 'q' key is pressed, stop the loop
if key == ord("q"):
break

# close all windows
cv2.destroyAllWindows()