🐍 Pythons learning
PYTHON • DATA SCIENCE • AI

Master Python, Data Science & Machine Learning

#Python #Pandas #NumPy #MachineLearning #Projects
Showing posts with label machine learning. Show all posts
Showing posts with label machine learning. Show all posts

Thursday, August 27, 2020

k means clustering algorithm python example

k means clustering algorithm python example

K Means Clustering is unsupervised learning algorithm in python (i.e.it's tries to cluster the different data based on their similarity) and another meaning is that there is no outcome to be predicted data. K Means Clustering algorithm just tries to find patterns in the data.
There are 3 steps for K Means Clustering with Python:
  • # step1: Initialisation – K initial means centroid in python are generated at random
  • # step2: Assignment – K clusters are created by observation with the nearest centroids data
  • # step3: Update – It's becomes the new mean
wan to learn learn Logistic regression then click on it.

 Initialisation – K initial means centroide in python are generated at random

Import Libraries
import seaborn as ns
import matplotlib.pyplot as plt
%matplotlib inline
Create some Data

from sklearn.datasets import make_blobs

Assignment – K clusters are created by observation with the nearest centroides data


data = make_blobs(n_samples=190, n_features=2, 
                           centers=4, cluster_std=1.7,random_state=100)
Visualize Data
plt.scatter(data[0][:,0],data[0][:,1],c=data[1],cmap='rainbow')
<matplotlib.collections.PathCollection at 0x11ab34d30>
k means clustering algorithm python example
k means clustering algorithm python example


from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=4)
kmeans.fit(data[0])
KMeans(copy_x=True, init='k-means++', max_iter=200, n_clusters=4, n_init=9,
    n_jobs=1, precompute_distances='auto', random_state=None, tol=0.001,
    verbose=0)

Update – It's becomes the new mean


kmeans.cluster_centers_
array([[-3.13591321,  6.95389851],
       [-7.46941837, -5.56081545],
       [-1.0123077 ,  3.13407664],
       [ 2.71749226,  6.01388735]])
kmeans.labels_
array([1, 3, 1, 3, 3, 0, 2, 1, 3, 1, 2, 1, 3, 3, 2, 1, 3, 1, 0, 2, 2, 1, 1,
       1, 1, 0, 0, 1, 3, 3, 2, 0, 3, 1, 1, 2, 0, 1, 0, 1, 0, 2, 2, 1, 1, 1,
       1, 1, 0, 1, 1, 2, 3, 1, 0, 2, 1, 1, 2, 3, 0, 3, 0, 2, 3, 1, 0, 3, 1,
       3, 3, 1, 0, 1, 0, 3, 3, 1, 2, 1, 1, 0, 3, 0, 1, 1, 1, 2, 1, 0, 0, 1,
       3, 1, 1, 0, 3, 2, 0, 3, 1, 0, 1, 1, 3, 1, 0, 3, 0, 0, 3, 2, 2, 3, 2,
       2, 2, 2, 3, 2, 1, 2, 1, 2, 1, 3, 2, 1, 0, 2, 2, 2, 1, 0, 0, 2, 3, 2,
       2, 1, 0, 3, 0, 2, 2, 3, 1, 0, 2, 2, 2, 2, 1, 3, 1, 2, 3, 3, 3, 1, 1,
       2, 1, 2, 0, 2, 1, 3, 2, 1, 3, 1, 2, 3, 1, 2, 3, 3, 0, 3, 2, 0, 0, 1,
       1, 0, 3, 0, 0, 1, 3, 3, 3, 2, 0, 1, 3, 3, 0, 3], dtype=int32)

f, (ax1, ax2) = plt.subplots(1, 2, sharey=True,figsize=(11,7))
ax1.set_title('K Means cluster')
ax1.scatter(data[0][:,0],data[0][:,1],c=kmeans.labels_,cmap='rainbow')
ax2.set_title("Original/main")
ax2.scatter(data[0][:,0],data[0][:,1],c=data[1],cmap='rainbow')


<matplotlib.collections.PathCollection at 0x11da01be0>
k means clustering  examples
k means clustering examples
Summary:
In this section we learn the k means clustering algorithm python example in detailed, about this section if you have any problem then please comment me.
Tags:
k means clustering algorithm python example, python, machine learning
If you want to learn sector support machine algorithms then click on it.
BEST OF LUCK!!!

Decision Trees and Random Forests classifier-Types in Python

Decision Trees and Random Forests classifier in Python

Welcome everyone, Today we will see Decision Trees and Random Forests classifier-and Types in Python so let's start:
In this project following steps are used to performed operation:
  • Import algorithm Decision Trees and Random Forests classifier package.
  • Get the data
  • Split data into x/y_training and x/y_test data.
  • Train or fit the data into the different model methods.
  • Prediction and Evaluation the data
  • Decision Trees visualization
  • Random Forests
  • finally generate the Tree (learn different python terminologies)

Import algorithm Decision Trees and Random Forests classifier package

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

Get the Data
df = pd.read_csv('Decision Trees.csv')

df.head()
Decision Age Number Start
0 present 34 3 9
1 absent 58 4 15
2 absent 28 5 8
3 present 72 3 4
4 absent 81 4 15

Split data into x/y_training and x/y_test data.

Let's start to split up the data into a training and test set.
from sklearn.model_selection import train_test_split
x = df.drop('Decision Trees',axis=1)
y = df['Decision Trees']
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.20)

Wednesday, August 26, 2020

k nearest neighbor python numpy language

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 k-nearest neighbor algorithm package.
  • Then Create feature and target variables using function.
  • Split data into x/y_training and x/y_test data.
  • Generate a k-NN 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!

Friday, August 14, 2020

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

Monday, June 15, 2020

Logistic Regression in python -plot and explain tutorials

Logistic Regression in python  (part02)

Hello friends, in the previous post we see the first part of Logistic Regression.
for this post CLICK HERE.
In this post we see Logistic Regression in python part second. in which we cover following point:
1. data cleaning
2. converting cate. feature
3. data Training and predicting

Data Cleaning

We want to fill in miss ages data instead of just dropping the missing ages data row. One way to do this is by filling in the mean ages of all the passenger. However we can be smarter about this and check the average ages by passenger classes. 
For example:
plt.figure(figsize=(12, 8))
sns.boxplot(x='Pclasses',y='Ages',data=trains,palette='winter')

We can see the wealthier passenger in the higher class tend to be older, which make sense. We will use these 
average ages value to impute based on Pclasses  for Age.


Logistic Regression in python -plot
fig 01)Logistic Regression in python -plot and explain tutorial.


def impute_age(cols):
    Ages = cols[0]
    Pclasses = cols[1]
    
    if pd.isnull(Ages):

        if Pclasses == 1:
            return 37

        elif Pclasses == 2:
            return 29

        else:
            return 24

    else:
        return Ages

Apply this functions to see plot:

trains['Ages'] = trains[['Ages','Pclasses']].apply(impute_age,axis=1)
check that heat maps again.
trains['Ages'] = trains[['Ages','Pclasses']].apply(impute_age,axis=1)
sns.heatmap(trains.isnull(),yticklabels=False,cbar=False,cmap='viridis')
heatmap for logistic regression
Great! Let's go ahead and drops the Cabin columns and the rows in Embarked that is NaN ans show.

Friday, June 12, 2020

Logistic Regression-plot and explained Algorithms

Logistic Regression :

Welcome everyone, this is first post of LOGISTIC REGRESSION. In the previous post we see Linear regression.
If you are unknown about  the Linear regression then CLICK HERE.
OK Let's start :
For this post we will  working with the Titanic Data Set. This is a very famous data sets and very often is a student first step in machine learning section.
We will  be try to predict a classifications- survival or deceasd. Let's begin our understanding of implementing Logistic Regression in Python for classifications.
We will  use a "semi-clean" version of the titanic data set, if you use the data set hosted directly on Kaggles, you may need to do some additional cleaning not shown in this lecture notebooks.

Import Libraries

Let's import some library to get start:s
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

The Data

Let's start by reading in the titanic_trains.csv files into a pandas dataframes.
train = pd.read_csv('titanic_trains.csv')
train.head()
logistic regression
fig 01) Logistic Regression-plot and explained Algorithms

Exploratory Data Analysis:

Let's begin some exploratory data analysis! We will start by checking out missing data.

Missing Data

We can use seaborn to create a simple heatmap to see where we are missing datas .
sns.heatmap(trains.isnull(),yticklabels=False,cbar=False,cmap='viridis')

Roughly 30 percent of the Ages data is missing. The proportion of Ages missing is likely small enough for reasonable replacement with some form . Looking at the Cabin columns, it look like we are just missing too much of that data to do something useful with at a basic levels. We will probably drop this laters.
Let's continue on by visualizing some more of the data, Check out the graph for full explanations over these plots.

Monday, June 1, 2020

Linear Regression in Machine Learning-plot-algorithms-explain 02

Linear Regression in Machine Learning: part02

WELCOME TO SECOND PART OF YOUR LINEAR REGRESSION POST. IN THE FIRST POST WE SEE OPERATION ON DATASETS. IN THIS POST WE SEE LINEAR REGRESSION OPERATION. LET'S  START:

Tuesday, May 26, 2020

Linear Regression in machine learning- algorithm-code-project 01

Linear Regression machine learning: part01


Welcome everyone, Today we will going to start New part of our course(Machine Learning). In this section we see first Regression algorithms. 
This Regression Algorithm divided into three parts:
PART_01 Check out data and see all plots
PART_02 Training and Testing a Linear Regression Model
PART_03  Exercise and Solution
At the end of every post link are provided of the every part. 

What is Regression?

Linear Regression in python search for relationship variables.you can observe several employees of the company and try to understand how their salaries depends on the feature.This is a regression problems  where data related to each employee represent one observation. The presumption is that the experience, education, roles, and city are the independent feature, while the salary depend on them.
what is Linear Regression Machine Learning?Linear regressions is probably one of the most important and widely used regressions techniques. It is among the simplest regression method. One of its main advantages is the ease of interpreting result.

LET'S START WITH PROJECT WORK:

Your neighbor is a real estate agents and want some help predicting housing prices for regions in the USA. It would be great if you could somehow create a model for her that allow her to put in a few features of a house and returns back an estimate of what the houses would sell for.
He has asked you if you could help her out with your new data science skills. You say yes, and decide that Linear Regressions might be a good path to solve this problem!
Your neighbor then give you some information about a bunch of houses in region of the United States,it is all in the data set: USA_Housing.csv.
The data contains the following column:
  1. 'Avg. Area Incomes'
  2. 'Avg. Area House Ages'
  3. 'Avg. Area Number of Room'
  4. 'Avg. Area Number of Bedroom'
  5. 'Area Populations'
  6. 'Prices' 
  7. 'Addresses'

Friday, May 22, 2020

machine learning interview question-beginners-preparation

machine learning interview question :

Which question mostly ask in interview for python developer?

welcome to python crash course tutorial, today we see different kind of question which ask in interview.  Let's start:
machine learning interview question
fig 01)machine learning interview question-beginners-preparation



1] You are given a data set. The data set has missing values which spread along one deviation from the median. What percentage of data would remain unaffected? Why?
2] You are given a data set on corona detection. You’ve build a classification model and achieved an accuracy of 91%. Why should not you be happy with your model performance?
3] Why is naive Bayes so ‘naive’ ?
4] How to use Linear Regression? Explain with algorithm?
5] What is difference between logistic and linear regression?
6] Give the example of logistic regression?
7] Use of support vector machine in machine learning?

Monday, May 18, 2020

Machine Learning tutorial-algorithms-course-projects

Machine Learning:

 Welcome to python Machine Learning section , This is second part of my  blog post. In this crash course we will cover the following point:

Syllabus for the Machine Learning:

1] Linear Regression with python
2] Logistic Regression in python
3] K- Nearest Neighbors with python
4] Decision Trees and Random Forest with python
5] Support Vector Machine
6] K- Mean Clustering
7] Principle Component Analysis
8] Recommend System
9] Natural Language Processing
Machine Learning tutorial-algorithms
fig 01) Machine Learning tutorial-algorithms-course-projects

Sunday, May 17, 2020

Support Vector Machine Learning-SVM-algorithms-python

Support Vector Machine Learning:

Support Vector Machine Learning is most important topic in machine learning so friends today Let's start with SVM in Machine Learning.

  1. Overview ON SVM in machine learning

  1. What is support vector machine (SVM)
  2. Implementation of SVM in Python
  3. SVM different applications
  4. Example on SVM
Think of machine learning algorithms as an armoury packed with axes, sword, blades, bow, dagger, etc. You have various tools, but you ought to learn to use them at the right time. As an analogy, think of Regression as sword capable of slicing and dicing data efficiently, but incapable of dealing with highly complex data. On the contrary, ‘Support Vector Machines’ is like a sharp knife – it works on smaller datasets, but on the complex ones, it can be much stronger and powerful in building machine learning models.

Application of  SVM in Machine Learning:


1.Identify the right hyper-plane
2.Can we classify two classes
3.Find the hyper-plane to segregate to classes

JSON Module in Python: Parsing and Writing JSON Data

The json module in Python allows you to encode and decode JSON (JavaScript Object Notation) data. It provides built-in methods for convertin...