Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Getting Started with Machine Learning in Python

Getting Started with Machine Learning in Python

Python is one of the most commonly used programming languages in machine learning, thanks to its ease of learning, powerful library support, and community ecosystem.

Next, I will explain step by step how to get started with machine learning through Python and introduce some commonly needed libraries.

Installing Python and Necessary Libraries

Method 1: Official Installer

First, make sure you have installed Python. You can visit the Python official website https://www.python.org/ to download and install the latest version.

Windows:

# 1. 下载安装程序后运行
# 2. Check "Add Python to PATH"
# 3. Select "Install for all users"
# 4. Click "Install" to start installation

macOS:

# 方法1:使用官网安装包
# Download the .pkg file and double-click to install
# Method 2: Using Homebrew
brew install python3

Linux:

# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip
# CentOS/RHEL
sudo yum install python3 python3-pip

Method 2: Anaconda Distribution

Anaconda is a Python distribution designed for data science, like a "machine learning toolbox" preinstalled with all the tools.

Advantages of Anaconda

  1. Pre-installed common libraries: NumPy, Pandas, Scikit-learn, etc.
  2. Environment Management: conda commands for managing virtual environments
  3. Graphical interface: Anaconda Navigator provides visual operations
  4. Cross-platform: supports all major operating systems

Installing Anaconda

  1. Access the https://www.anaconda.com/products/distribution
  2. Download the installation package for your system
  3. Run the installer and follow the prompts to complete the installation

Verify installation:

conda --version
python --version

If you are not yet familiar with Python, you can first study our Python Tutorial。

If you are not yet familiar with Conda, you can first study our Anaconda Tutorial。

It is recommended to install Anaconda for creating virtual environments.

Why do we need virtual environments?

A virtual environment is like a separate kitchen prepared for each project, preventing the "seasonings" (library versions) of different projects from interfering with each other.

Benefits of Virtual Environments

  1. Dependency isolation: different projects use different versions of libraries
  2. Environment reproducibility: makes it easy to recreate the same environment on other machines
  3. Permission management: avoids polluting the system Python environment
  4. Project cleanup: delete the associated environment when deleting a project

Managing Environments with conda

# 创建环境
conda create -n ml_env python=3.8
# Activate environment
conda activate ml_env
# 安装包
conda install numpy pandas scikit-learn
# List environment
conda env list
# Delete environment
conda env remove -n ml_env

Development tool configuration

Jupyter Notebook

Jupyter Notebook is a data scientist's digital laboratory, supporting interactive programming and visual presentation.

Installing and Launching Jupyter


# Install Jupyter
pip install jupyter
# Start Jupyter Notebook
jupyter notebook
# Start Jupyter Lab (a more modern interface)
jupyter lab

Basic Jupyter Usage

Example

Jupyter Notebook Usage Example

Run the following code in Jupyter

1. Data import and exploration

import

pandas

as

pd

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

Create sample data

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

]

,

   

'Age'

:

[

25

,

30

,

35

,

28

]

,

   

'City'

:

[

'Beijing'

,

'Shanghai'

,

'Guangzhou'

,

'Shenzhen'

]

,

   

'Salary'

:

[

15000

,

20000

,

18000

,

22000

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Data preview:"

)

print

(

df.

head

(

)

)

2. Data Visualization

plt.

figure

(

figsize

=

(

10

,

4

)

)

plt.

subplot

(

1

,

2

,

1

)

plt.

bar

(

df

[

'Name'

]

,

df

[

'Age'

]

)

plt.

title

(

'Age distribution'

)

plt.

xlabel

(

'Name'

)

plt.

ylabel

(

'Age'

)

plt.

subplot

(

1

,

2

,

2

)

plt.

bar

(

df

[

'Name'

]

,

df

[

'Salary'

]

)

plt.

title

(

'Salary Distribution'

)

plt.

xlabel

(

'Name'

)

plt.

ylabel

(

'Salary'

)

plt.

tight_layout

(

)

plt.

show

(

)

3. Simple statistical analysis

print

(

"\nBasic statistical information:"

)

print

(

df.

describe

(

)

)

print

(

"\nCity distribution:"

)

print

(

df

[

'City'

]

.

value_counts

(

)

)

VS Code Configuration

VS Code is a lightweight yet powerful code editor, which can be turned into a professional machine learning development environment through extensions.

Recommended Extensions

  1. Python: Microsoft's official Python extension
  2. Jupyter: supports Jupyter Notebook
  3. Python Docstring Generator: automatically generates docstrings
  4. Bracket Pair Colorizer: bracket pair colorization
  5. GitLens: enhanced Git features

VS Code Configuration Example

// .vscode/settings.json
{
    "python.defaultInterpreterPath": "./envs/ml_env/bin/python",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.formatting.provider": "black",
    "python.testing.pytestEnabled": true,
    "jupyter.askForKernelRestart": false,
    "editor.fontSize": 14,
    "editor.tabSize": 4,
    "editor.insertSpaces": true
}

Machine Learning Library Installation

Common machine learning libraries:


pip install numpy pandas matplotlib seaborn scikit-learn

If you plan to use a deep learning framework, install as follows:

pip install torch  # 或者
pip install tensorflow

Related courses:

When doing machine learning with Python, the whole process generally follows these steps:

  1. Import the necessary libraries - For example, NumPy, Pandas, and Scikit-learn.

  2. Loading and preparing data - Data is the core of machine learning. You need to load the data and perform necessary preprocessing (such as data cleaning, filling missing values, etc.).

  3. Selecting a model and algorithm - Choose a suitable machine learning algorithm based on the task (such as linear regression, decision trees, etc.).

  4. Train the model - Use the training set to train the model.

  5. Evaluate the model - Use the test set to evaluate the model's accuracy and optimize the model based on the results.

  6. Tuning the model and hyperparameters - Adjust the model's hyperparameters based on the evaluation results to further improve performance.


A Simple Machine Learning Example: Classification with Scikit-learn

Scikit-learn (short for Sklearn) is an open-source machine learning library built on top of the scientific computing libraries NumPy, SciPy, and matplotlib, providing simple and efficient tools for data mining and data analysis.

Scikit-learn includes many common machine learning algorithms, including:

Next, we demonstrate the machine learning workflow through a simple classification task——using the Iris Dataset, a classic dataset containing 150 samples that describe the length and width of petals and sepals for three different types of iris flowers.

Step 1: Import Libraries

Import the required Python libraries:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

Step 2: Load Data

Load the Iris dataset:

Example

Load the Iris dataset

iris

=

load_iris

(

)

Convert the data into a pandas DataFrame

X

=

pd.

DataFrame

(

iris.

data

,

columns

=

iris.

feature_names

)

 

Feature data

y

=

pd.

Series

(

iris.

target

)

 

Label data

Display the first five rows

print

(

X.

head

(

)

)

The printed output is shown below:

   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.1               3.5                1.4               0.2
1                4.9               3.0                1.4               0.2
2                4.7               3.2                1.3               0.2
3                4.6               3.1                1.5               0.2
4                5.0               3.6                1.4               0.2

Step 3: Split the Dataset

Split the dataset into a training set and a test set, typically using a 70% training and 30% test ratio:

Example

Split into training and test sets (80% training, 20% test)

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Step 4: Feature Scaling (Standardization)

Many machine learning algorithms depend on the scale of features, especially algorithms like K-Nearest Neighbors. To ensure each feature has a mean of 0 and a standard deviation of 1, we use standardization to process the data:

Example

Standardize features

scaler

=

StandardScaler

(

)

X_train

=

scaler.

fit_transform

(

X_train

)

X_test

=

scaler.

transform

(

X_test

)

Step 5: Select and Train a Model

In this example, we choose the K-Nearest Neighbors (KNN) algorithm for classification:

Example

Create a KNN classifier

knn

=

KNeighborsClassifier

(

n_neighbors

=

3

)

Train the model

knn.

fit

(

X_train

,

y_train

)

Step 6: Evaluate the Model

After training, we use the test set to evaluate the model's accuracy:

Example

Predict on the test set

y_pred

=

knn.

predict

(

X_test

)

Compute accuracy

accuracy

=

accuracy_score

(

y_test

,

y_pred

)

print

(

f

'Model accuracy: {accuracy:.2f}'

)

After running the code above, the output is:


模型准确率: 1.00

Step 7: Visualize the Results (Optional)

You can use visualization to gain a deeper understanding of the model's performance, especially with multidimensional datasets. For example, you can use a 2D plot to show the KNN classification results (though this requires reducing the data to two dimensions).

Example

import

numpy

as

np

import

pandas

as

pd

import

matplotlib.

pyplot

as

plt

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

preprocessing

import

StandardScaler

from

sklearn.

neighbors

import

KNeighborsClassifier

from

sklearn.

metrics

import

accuracy_score

Load the Iris dataset

iris

=

load_iris

(

)

Convert the data into a pandas DataFrame

X

=

pd.

DataFrame

(

iris.

data

,

columns

=

iris.

feature_names

)

 

Feature data

y

=

pd.

Series

(

iris.

target

)

 

Label data

Split into training and test sets (80% training, 20% test)

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Standardize features

scaler

=

StandardScaler

(

)

X_train

=

scaler.

fit_transform

(

X_train

)

X_test

=

scaler.

transform

(

X_test

)

Create a KNN classifier

knn

=

KNeighborsClassifier

(

n_neighbors

=

3

)

Train the model

knn.

fit

(

X_train

,

y_train

)

Predict on the test set

y_pred

=

knn.

predict

(

X_test

)

Compute accuracy

accuracy

=

accuracy_score

(

y_test

,

y_pred

)

Visualization - this is just a simple example; choose the plotting method according to your actual situation

plt.

scatter

(

X_test

[

:

,

0

]

,

X_test

[

:

,

1

]

,

c

=

y_pred

,

cmap

=

'viridis'

,

marker

=

'o'

)

plt.

title

(

"KNN Classification Results"

)

plt.

xlabel

(

"Feature 1"

)

plt.

ylabel

(

"Feature 2"

)

plt.

show

(

)

The output image is shown below: