Introduction to Machine Learning in Python
Machine learning is the act of giving computers the ability to learn without explicitly programming them. This is done by giving data to computers and having them transform the data into decision models which are then used for future predictions.
In this tutorial, we will talk about machine learning and some of the fundamental concepts required to get started with machine learning. We will also devise a few Python examples to predict certain elements or events.
Introduction to Machine Learning
Machine learning is a type of technology that aims to learn from experience. For example, as a human, you can learn how to play chess simply by observing other people playing chess. In the same way, computers are programmed by providing them with data from which they learn and are then able to predict future elements or conditions.
Let's say, for instance, that you want to write a program that can tell whether a certain type of fruit is an orange or a lemon. You might find it easy to write such a program and it will give the required results, but you might also find that the program doesn't work effectively for large datasets. This is where machine learning comes into play.
There are various steps involved in machine learning:
- collection of data
- filtering of data
- analysis of data
- algorithm training
- testing of the algorithm
- using the algorithm for future predictions
Machine learning uses different kinds of algorithms to find patterns, and these algorithms are classified into two groups:
- supervised learning
- unsupervised learning
Supervised Learning
Supervised learning is the science of training a computer to recognize elements by giving it sample data. The computer then learns from it and can predict future datasets based on the learned data.
For example, you can train a computer to filter out spam messages based on past information.
Supervised learning has been used in many applications, e.g. Facebook, to search images based on a certain description. You can now search images on Facebook with words that describe the contents of the photo. Since the social networking site already has a database of captioned images, it can search and match the description to features from photos with some degree of accuracy.
There are only two steps involved in supervised learning:
- training
- testing
Some of the supervised learning algorithms include:
- decision trees
- support vector machines
- naive Bayes
- k-nearest neighbor
- linear regression
Machine Learning With the Sklearn Library
Sklearn is a machine learning library for the Python programming language with a range of features such as multiple analysis, regression, and clustering algorithms. We are going to write a simple program to demonstrate how supervised learning works using the Sklearn library and the Python language.
Sklearn also interoperates well with the NumPy and SciPy libraries.
Install Sklearn
The Sklearn installation guide offers a very simple way of installing it for multiple platforms. It requires several dependencies:
- Python (>= 3.6),
- NumPy (min version 1.17.3)
- SciPy (Min version 1.3.2)
If you already have these dependencies, you can install Sklearn as simply as:
pip install -U scikit-learn<br>
An easier way is to simply install Anaconda. This takes care of all the dependencies, so you don't have to worry about installing them one by one.
To test if Sklearn is running properly, simply import it from a Python interpreter as follows:
Python 3.9.12 (main, Apr 5 2022, 06:56:58) <br>[GCC 7.5.0] :: Anaconda, Inc. on linux<br>Type "help", "copyright", "credits" or "license" for more information.<br>>>> import sklearn<br>>>> <br>
If no error occurs, then you are good to go.
Now that we are done with the installation, let's get back to our problem. We want to be able to differentiate between different animals. So we will design an algorithm that can tell specifically whether a given animal is either a horse or a chicken.
We first need to collect some sample data from each type of animal. Some sample data is shown in the table below.
from sklearn import tree<br>
Define the features you want to use to classify the animals.
features = [[7, 0.6, 40], [7, 0.6, 41], [37, 600, 37], [37, 600, 38]]<br>
Define the output each classifier will give. A chicken will be represented by 0, while a horse will be represented by 1.
#labels = [chicken, chicken, horse, horse]<br><br># we use 0 to represent a chicken and 1 to represent a horse<br><br>labels = [0, 0, 1, 1]<br>
We then define the classifier which will be based on a decision tree.
classifier = tree.DecisionTreeClassifier()<br>
Feed or fit your data to the classifier.
classifier.fit(features, labels)<br>
The complete code for the algorithm is shown below.
from sklearn import tree<br>features = [[7, 0.6, 40], [7, 0.6, 41], [37, 600, 37], [37, 600, 38]]<br>#labels = [chicken, chicken, horse, horse]
labels = [0, 0, 1, 1]
classif = tree.DecisionTreeClassifier()
classif.fit(features, labels)
We can now predict a given set of data. Here's how to predict an animal with a height of 7 inches, a weight of 0.6 kg, and a temperature of 41:
from sklearn import tree<br>features = [[7, 0.6, 40], [7, 0.6, 41], [37, 600, 37], [37, 600, 38]]<br>
#labels = [chicken, chicken, horse, horse]
labels = [0, 0, 1, 1]
classif = tree.DecisionTreeClassifier()
classif.fit(features, labels)
print(classif.predict([[7, 0.6, 41]]))
Here's how to predict an animal with a height of 38 inches, a weight of 600 kg, and a temperature of 37.5:
from sklearn import tree<br>features = [[7, 0.6, 40], [7, 0.6, 41], [37, 600, 37], [37, 600, 38]]<br>#labels = [chicken, chicken, horse, horse]
labels = [0, 0, 1, 1]
classif = tree.DecisionTreeClassifier()
classif.fit(features, labels)
print(classif.predict([[38, 600, 37.5]]))
# output
# [1] or a Horse
As you can see above, you have trained the algorithm to learn all the features and names of the animals, and the knowledge of this data is used for testing new animals.
Linear Regression on Large Datasets
In the second example, we will use a much larger dataset to perform Linear regression.
According to Wikipedia:
In statistics, linear regression is a linear approach for modelling the relationship between a scalar response and one or more explanatory variables (also known as dependent and independent variables).
The dataset can be found here. Download the csv file into your working directory
Let's start by importing the necessary dependencies.
pip install -U scikit-learn<br>
Next, load the csv data in to a pandas dataframe.
Python 3.9.12 (main, Apr 5 2022, 06:56:58) <br>[GCC 7.5.0] :: Anaconda, Inc. on linux<br>Type "help", "copyright", "credits" or "license" for more information.<br>>>> import sklearn<br>>>> <br>
To see the data's appearance, you can use the DataFrame's describe () function.
from sklearn import tree<br>
Here is the output:
features = [[7, 0.6, 40], [7, 0.6, 41], [37, 600, 37], [37, 600, 38]]<br>
As you can see above, the data contains the GDP of different countries from 1960 to 2016. The next step is to create the x and y-dimensional arrays.
#labels = [chicken, chicken, horse, horse]<br><br># we use 0 to represent a chicken and 1 to represent a horse<br><br>labels = [0, 0, 1, 1]<br>
Next, create a regression model and a prediction using the X (year) as the input.
classifier = tree.DecisionTreeClassifier()<br>
Finally, plot the data and a line representing the prediction model.
classifier.fit(features, labels)<br>
Here is the plot:

Unsupervised Learning
Unsupervised learning is when you train your machine with only a set of inputs. The machine will then be able to find a relationship between the input data and any other you might want to predict. Unlike in supervised learning, where you present a machine with some data to train on, unsupervised learning is meant to make the computer find patterns or relationships between different datasets.
Unsupervised learning can be further subdivided into:
- clustering
- association
Clustering
Clustering means grouping data inherently. For example, you can classify the shopping habits of consumers and use the data for advertising by targeting consumers based on their purchases and shopping habits.
Association
Association is where you identify rules that describe large sets of data. This type of learning can be applicable in associating books based on author or category, whether motivational, fictional, or educational books.
Some of the popular unsupervised learning algorithms include:
- k-means clustering
- hierarchical clustering
Conclusion
I hope this tutorial has helped you get started with machine learning. This is just an introduction—machine learning has a lot to cover, and this is just a fraction of what machine learning can do. Sklearn is just one of the libraries used in machine learning. Other libraries include tensorflow and keras.
Additionally, don’t hesitate to see what we have available for sale and for study on Envato Market.
Your decision to use either a supervised or unsupervised machine learning algorithm will depend on various factors, such as the structure and size of the data.
Machine learning can be applied in almost all areas of our lives, e.g. in fraud prevention, personalizing news feeds on social media sites to fit users' preferences, email and malware filtering, weather predictions, and even in the e-commerce sector to predict consumer shopping habits.
The above is the detailed content of Introduction to Machine Learning in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.
