k nearest neighbor python 3.10

k nearest neighbor python numpy language:

Welcome everyone in python crash course (Machine learning). This is first part of this section,if you want to learn SVM in python then click on it.
K Nearest Neighbors method also used for data prediction purpose, so in his section we will learn  K Nearest Neighbors predict method.

k nearest neighbor python numpy language
k nearest neighbor python numpy language

How do you use K nearest neighbor in Python language in smart way?

In this project following steps are used to performed operation:
  • Import knearest neighbor algorithm package.
  • Then Create feature and target variables using function.
  • Split data into x/y_training and x/y_test data.
  • Generate a kNN value model using neighbor method.
  • Train or fit the data into the different model methods.
  • finally Predict the future data

What is K nearest neighbor used for?

suppose you have been given a classified data set from a any popular company,they give you the data and the target classes and say predicts a class for a new data point based off of the features.
Let’s do it!

k nearest neighbor python 3.10

Import Libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

Get the Data
Set index_col=0

df = pd.read_csv(“Sample Classified Data”,index_col=0)

df.head()

WTS PTS EQS SBS LQS QWS FDS PJS HQS NXS TARGETC CLASSES
0.923917 1.172073 0.467946 0.655464 0.880862 0.252608 0.659697 0.343798 0.979422 1.231409 1
0.645632 1.033722 0.545342 0.865645 0.934109 0.658450 0.675334 1.213546 0.681552 1.492702 1
0.5521360 1.201493 0.921990 0.8775595 1.526629 0.720781 1.776351 1.154483 0.957877 1.285597 0
1.434204 1.386726 0.653046 0.425624 1.142504 0.875128 1.509708 1.380003 1.522692 1.253093 0
1.579491 0.949750 0.627280 0.768976 1.232537 0.703727 1.815596 0.646691 1.463812 1.519167 1

Standardize the Variables  K Nearest Neighbors method
In the next step we drop the TARGETC CLASSES from the data because this type of data affect on the prediction.

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(df.drop(‘TARGETC CLASSES’,axis=1))
StandardScaler(copy=True, with_mean=True, with_std=True)
scaled_features = scaler.transform(df.drop(‘TARGETC CLASSES’,axis=1))
df_feat = pd.DataFrame(scaled_features,columns=df.columns[:-1])

df_feat.head()

WTS  PTS EQS SBS LQS QWS FDS PJS HQS NXS
-0.045232 0.185907 -0.913431 0.3229629 -1.033637 -2.308375 -0.798951 -1.482368 -0.949719 -0.643314
-1.674836 -0.430348 -1.025313 0.625388 -0.444847 -1.152706 -1.129797 -0.202240 -1.828051 0.636759
-0.9988702 0.339318 0.301511 0.785873 2.031693 -0.870156 2.5109818 0.285707 -0.682494 -0.377850
0.992841 1.060193 -0.621399 0.635299 0.452820 -0.267220 1.770208 1.066491 1.241325 -1.026987
1.149275 -0.640392 -0.709819 -0.557175 0.822886 -0.936773 0.6996782 -1.472352 1.040772

Train Test Split method:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(scaled_features,df[‘TARGETC CLASSES’],
test_size=0.20)

Using KNN method
Remember we will start with k=1 value.

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train,y_train)
KNeighborsClassifier(algorithm=’auto’, leaf_size=20, metric=’minkowski’,
metric_params=None, n_jobs=1, n_neighbors=1, p=2,
weights=’uniform’)
pred = knn.predict(X_test)

Predictions and Evaluations using knn
Let’s start to evaluate our KNN model!

from sklearn.metrics import classification_report,confusion_matrix

print(confusions_matrix(y_test,pred))

[[124  19]
[ 12 145]]

print(classification_report(y_test,pred))

precisionx    recallx  f1-scorex   supportx
1       0.92      0.87      0.89       144
0       0.99      0.92      0.90       158
avg / total       0.94      0.90      0.89       300

Choosing a correct value for K for this
we use the elbow method to pick a correct K Value:

error_rate = []

(more…)

I am Mr. Sachin pagar Embedded system engineer, the founder of Pythonslearning, a Passionate Educational Blogger and Author, who love to share the informative content on educational resources.

Continue Readingk nearest neighbor python 3.10

python 3 get user input-raw_input ( ) function input ( prompt ) function

 python 3 get user input

Hello everyone, In this article we will see What is difference between raw_input ( ) function,input ( prompt ) function?, How to get different input from keyboard in python language ?
So let’s start:
python 3 get user input-raw_input ( ) function input ( prompt ) function
 python 3 get user input-raw_input ( ) function input ( prompt ) function

Python 3 version has a built-in function input() to accept user input from keyboard.
Python  language provides  two inbuilt function to read the input or data  from the keyboard.
  • raw_input ( prompt ) function
  • input ( prompt ) function

What is difference between raw_input ( ) function input ( prompt ) function?

raw_input ( ) function:
 This function takes exact input from the keyboard and convert it to string, then return it to the variable form in which we want to store it. raw_input ( ) function works in only older version python 2.0. 
For example –

# Python example for a use of raw_input() 
s = raw_input("Enter your good name : ") 
print s
Output :

Enter your good name :  sachin
sachin

Here, s is a variable which give the string value, type by user . 
input ( prompt ) function :
we use input(prompt) to accept input from a user and print() function used  to display output on the console.
input ( prompt ) function takes the input from the user or external source and then evaluates the value.If the input provided is wrong then it gives syntax error or exception 
For example –

# Python program showing  input ( prompt ) function
sach = input("please enter your smart value: ") 
print(sach) 
Output:

please enter your smart value: 55
55

What is the input in python?

we are provide some value to system or machine this known as input. 
For example, if you want to perform an multiplication of two numbers on the calculator or on scientific calculator  then you need to first provide two number to the calculator, those two number is known as input provided by the user.

How to get different input from keyboard in python language?

Continue Readingpython 3 get user input-raw_input ( ) function input ( prompt ) function

How to remove duplicates from list in python 3

How to remove duplicates from list in python 3 :

Hello friends, In this article, we will see How to remove duplicates items or elements from the list in python so Let’s start :
How to remove duplicates from list in python 3
How to remove duplicates from list in python 3
 
There are different way to remove duplicates from list :
  1. Method 1 : Using list comprehension method
  2. Method 2 : Using list comprehension + enumerate() method
  3. Method 3 : Using set() method
  4. Method 4 : Naive method
  5. Method 5 : Using collections.OrderedDict.fromkeys() method

Method 1 : Using list comprehension method

This method has working similar to the Naive method , but small difference is it just a liner shorthand of longer methods done with the help of lists comprehension method.

For example :

# Demonstrate Python 3 code 
# remove duplicated from list using list comprehension
#  first we initializing list 
use_list = [4, 3, 7, 6, 3, 5, 7, 1] 
print (“The main/original list is : ” +  str(use_list)) 
# then we use using list comprehension method  
# to remove from list  
rest = [] 
[rest.append(x) for x in use_list if x not in rest] 
  
# printing list output after removal  
print (“The unique list after removing dupli is follow: ” + str(rest)) 
Output :
The main/original list is : [4, 3, 7, 6, 3, 5, 7, 1] 
The unique list after removing dupli is follow : [4, 3, 7, 6, 5, 1]
This time to learn different python terminologies in python.

Method 2 : Using list comprehension + enumerate()

list comprehension coupled with enumerate function can also achieve this task. It basically looks for already occurred elements and skips adding them. It preserves the list ordering.
# removing duplicated from list using list comprehension + enumerate() 
# first initializing list 
use_list = [4, 3, 7, 6, 3, 5, 7, 1] 
print (“The main/original list is : ” +  str(use_list)) 
# using list comprehension + enumerate() method to remove duplicated  
# from  the list  
rest = [i for n, i in enumerate(use_list) if i not in test_list[:n]]  
print (“TThe unique list after removing dupli is follow : ” + str(rest)) 
Output :
The main/original list is : [4, 3, 7, 6, 3, 5, 7, 1] 
The unique list after removing dupli is follow: [4, 3, 7, 6, 5, 1]

Method 3 : Naive method

In this method (naive method), we simply append the first occurrence of the element in new existing list and ignore all the other occurrences of the list.
# Demonstrate Python program 
# remove duplicated element from list using list Naive method
#  first we initializing list 
use_list = [4, 3, 7, 6, 3, 5, 7, 1] 
print (“The main/original list is : ” +  str(use_list)) 
# then we use using list Naive method  
rest = [] 
for i in test_list: 
    if i not in rest: 
        rest.append(i) 
  
# printing output after removal  
print (“The unique list after removing dupli is follow: ” + str(rest)) 
Output :
The main/original list is : [4, 3, 7, 6, 3, 5, 7, 1] 
The unique list after removing dupli is follow: [4, 3, 7, 6, 5, 1]

(more…)

Continue ReadingHow to remove duplicates from list in python 3

modulo operator in python 3.9

modulo operator in python 3.9

Welcome everyone, Today we will see Modulo Operator python,Modulo Operator python for negative number,How does a modulo operator work?,What is the use of modulo operator?,How do you find modulo?,What is the symbol of modulus operator?
so let’s start:

Modulo Operator python
Modulo Operator python

Modulo operator is show by the percent sign (%).
The syntax for Modulo Operator python is :

numx % numy
output:
For example
11 % 2
output:
1

If any case the divisor result is equal to zero then output show ZeroDivisionError:

11 % 0
output:
ZeroDivisionError: modulo by zero.

The modulo operator also work on floating numbers as arguments:
for example:

4.8 % 1.2
Copy
0.0

Remember % character represents the interpolation operator.(formatting strings)
Examples
modulo operator is used for different purpose like One of the most common use is to check whether a number is even or odd.
If a given number divided by 2 and has no remainder, then this number is even number. Otherwise it is odd.
EXAMPLE 01) Check for even or odd number:

numx = 15
 
if (numx % 5) == 0:
 
   print(num, “is even no.”)
 
else:
 
   print(num, “is odd no.”)
 
output:
 
15 is even no.

If you run the code above, 15 % 5 leaves a remainder of 0 and the code inside the else statement is executed:
15 is even no.
EXAMPLE 02) Check for prime number:

def is PrimeNumber(numb):
 
  if numb < 1:
 
    return False
 
  for i in range(2, numb):
 
    if (numb % i) == 0:
 
      return False
 
  else:
 
    return True

In this example first, we have to checking if the number, num is a positive number or negative(it’s required positive number). Next step is checking whether the number is divisible by another number in the range from 2 to number without any reminder. If none of the conditions are satisfy, the result is prime number.

Modulo Operator python for negative number:

Most complex mathematics task is taking modulo of a negative number, which is done behind the program of Python.
(x+y)mod z = [(x mod z)+(y mod z)]mod z
To apply this math to given statement as –

-3 % 7 = ( -1*7 + 4 ) % 7 = 4 

This was done so that the (-1*7)%7 will give the answer as 4
Let’s see more examples for better understanding.
Example #1 :
By using this mathematics, we can see able to perform and understand the negative modulo.

11 % 0
 
output:
 
ZeroDivisionError: modulo by zero.

filter_none
edit
play_arrow
brightness_4
# Using negative modulo in python

res1 = -35% 5
 
res2 = – 17 % 5
 
print(result1) 
 
print(result2)
 
Output :
 
0
 
2

(more…)

Continue Readingmodulo operator in python 3.9

explain advantages and disadvantages in machine learning

Advantages and disadvantages of Machine Learning :

Welcome everyone, In this article we will learn which is advantages and disadvantages of Machine Learning ? First, we will talk about the Advantages of Machine Learning. so Let’s start:
explain advantages and disadvantages in machine learning
advantages and disadvantages in machine learning


Advantages of Machine Learning

  • Efficient Handling of Data
  • Best for Education and Online Shopping
  • Continuous Improvement
  • Automation for everything
  • Automation of Everything
  • Wide Range of Applications
  • Trends and patterns identification
  • Scope of Improvement
There is a number of advantages of Machine Learning. So, let’s have a see at the some advantages of Machine Learning :
1. Efficient Handling of Data
Machine Learning has so many things that make it special. One of them is handling the data. Machine Learning plays the important role when it comes to data. 
Machine Learning can handle any type of data. Machine Learning can be support different types of data. These special handling data that normal systems can’t do.
2. Best for Online Shopping and Education
Machine Learning has a best scope in the future for education. It provides very super tech. to help student in study. Recently in China, a school mostly focus on machine Learning to improve student focus.In online shopping, the machine Learning would provide advertisements. 
3.Continuous Updated
Machine Learning algorithms are depend on which data that we provide. If we provided the new data, the model is make decisions improve with subsequent training. 
4. Automation of Everything
Machine Learning is one of the biggest source to responsible for cutting the workload and time.
Due to machine Learning, we are now designing more advanced computers system. These computers can handle various kind of smart work using machine Learning models and algorithms 
5. Different wide Range of Applications
Machine Learning has a different variety of applications.Machine Learning  has its role everywhere in world from banking to science,medical, business and tech.
It’s also play a major role in customer interaction. Machine Learning can help in the medical for detection of diseases like cancer more quickly.That is why investing in machine Learning technology is worth it.
6.Trends and patterns identification in machine learning :
Various Supervised, Unsupervised and Reinforced learning algorithms can be used for various classification and regression problems in machine learning.
7.Use in wide range of applications
Machine Learning is used in almost in every industry, for example from Online shopping to Education. With the help of past data companies generate profits, automate, predict the future, cut costs,analyze trend, predict the future,  and patterns from the past data, and many more. for example Applications like GPS Tracking for traffic
8. Scope of Improvement
Machine Learning is become the most popular technology in future. There is a lot of scope in machine Learning to become the top technology in the future world. 
Machine Learning help us to improve both software and hardware component. In hardware component, we have various laptops and GPU system. These help in the faster processing power of the computer system.we have to use various UI and libraries software. These software help in designing more efficient algorithms.

Disadvantages of Machine Learning :

  1. Data Acquisition
  2. Time and Space
  3. Time-consuming
  4. Possibility of High Error
  5. Algorithm Selection

Continue Readingexplain advantages and disadvantages in machine learning

which is valid identifier in python 3.10

what are python identifiers with example : 

An identifier is a simple concept which is used to identify entities. ( i.e. class, variables,  functions,module or other object ) Identifier used to differentiate one entity from another entityAn identifier starts with an underscore (_), letter A to Z or small letter a to z or  simply follow by zero or more letter and digits (0 to 9).

Python identifier simple example :

what are python identifiers
what are python identifiers
 
In the following example we have to used three variables.
The name of the variables
  •  rollno.,
  •  _sachin
  • and sachin_samprada are the identifiers.
# Basic examples on identifiers

rollno = 1
print(rollno)

_sachin = 5
print(_x)

sachin_samprada = 143
print(sachin_samprada)

OUTPUT :

>> 1
>> 5
>>  143

which is valid identifier in python 3.10

There are different no. of rules that must need to be followed to create a python identifier.

  • An identifier starts with an underscore (_), letter A to Z or small letter a to z or  simply follow by zero or more letter and digits (0 to 9)
  • sachin_SAMPRADA : contains all the valid character
  • _: underscore is also valid identifier
  • _sachin: it is valid to identifier can start with an underscore symbol

Some python Invalid Identifiers Example :

  • 143: identifier cannot be only digit
  • 143samprada: identifier cannot start with number
  • sachin+samprada: the only special character is valid an underscore
  • from: it is a reserved keyword

How to check if a String is a Valid Identifier in python? :

  • Identifier name cannot begin with a digit or number.
  • Python identifier cannot contain only digits or number.
  •  Identifier name can start with an underscore is valid.
  • There is no any limit on the length of the identifier.
  • Identifier name are case sensitive in nature.
  • sachin143samprada: Identifier contain only letters and numbers

We can use python string identifier() Functions to check identifier name is valid or not. But, this method doesn’t take reserved keywords into consideration. So, we can use this function with keyword.iskeyword() to check if the name is valid or not.
print(“_”.fallinlove()) # True
print(“for”.inlove()) # True – wrong output(error)
print(“sahin”.inlove())  # True
print(“143sach”.isidentifier())  # False

list of the Python keywords :

...
help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not                 
class               from                or                  
continue            global              pass

(more…)

Continue Readingwhich is valid identifier in python 3.10

comparison python vs r vs sas vs spss

python  vs r vs sas vs spss :

Welcome everyone, Today we will see comparison between  r vs python vs sas vs spss . So Let’s start :
what is Python ?
python  vs r vs sas vs spss
  python  vs r vs sas vs spss

1. python is best languages when learning to code :
If you are beginner to learn coding then mostly Python is your language of choice because It is one of the easy programming language to learn (it read and write like to plain English)

2. Python is heavily used in the IOT sector :
Most popular company use python algorithms platform for there services.

Like
  • Google
  • Youtube
  • Quora 
  • amazon etc. 
Advantages :
Powerful, fully-functional programming language
  1.  Latest availability of library Data science Learning and Machine Learning method
  2. Very easy to automate through scripts
  3. Extremely smart community support 
  4. Visualizations algorithms are easy to create
  5. Professional IDE environments are available
  6. object-oriented, functional and structured concepts
  7. A large number of stable package available
  8. Readable and clean syntax 
Disadvantages :
  1. Due to being a “full” programming language high bar of entry
  2. More licensing cost
  3. Only few statistical method are available
There are no user fees for the use of Python. However, in some special areas (e.g. text mining) not all packages are released for commercial use.
Conclusion
For Learning Python language we requires to learn a complete programming language
 Many good tutorials and trainings are available on the python tutorials point due to the language’s popularity. 

What is R?

R is a so popular and open-source language, it was developed in 1995 by Ross Robert Gentleman and Ihaka. R is used by statisticians and data miners for performing statistical computations and modeling hence it is most widely used. it is commonly used with RStudio
Advantages :
  1.  It is provide Very well community support, as also fee-based support via third-party provider.
  2. Easy free help resources also available like tutorials, exercise/solution.
  3. R is Very powerful and flexible  language e.g. support oop and Windows, Linux, MacOS
  4. R include very large range of functions 
  5. New statistical function are quickly implemented
  6. R is easy to automate and integrate 
Disadvantages :
  1. when we working with very large data sets then it’s required powerful hardware
  2. very costly Licensing mode
  3. R stores it object files in a physical memory so it’s produce problem.
Conclusion :
 R is a basically vey good choice for different user that plan to deal more extensively with statistics and not restricted by their statistical program.

SAS (Statistical Analysis System) :

SAS is one of the best Institute they offers a professional statistics software.
This software commonly used in banking sector,biometrics and in the clinical research.SAS is popular for data management, multivariate analysis,predictive analytics and business intelligence etc.
Advantage :
  1. In SAS numerous module and interface are available for free.
  2. It’s ability to handling large data sets
  3. very stable and reliable routines and fast integration of new statistical methods
  4. It’s provide very professional support and good documentation
  5. SAS offers good security to its users.
  6. It provides to load large volume of data for scalable and stable software that allow the companies
Disadvantage :
  1. SAS is a not open source software (i.e.you have to buy a licence for using it)
  2. SAS not contained most features in graphical visualisations. 
  3. but mostly some of the features in SAS are very limited. 
  4. It’s supported different, partly complicated program languages
  5. costly licensing model
Conclusion :
SAS offers good security to its users.It provides to load large volume of data for scalable and stable software that allow the companies

(more…)

Continue Readingcomparison python vs r vs sas vs spss