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

Machine learning applications

Machine learning applications

Machine learning applications can be divided into several major fields, each with its own unique application scenarios and challenges:

  1. Computer vision: let machines "see" the world
  2. Natural Language Processing: let machines "understand" human language
  3. Recommendation systems: personalized content recommendation
  4. Predictive Analytics: predict future trends and outcomes
  5. Anomaly detection: discover unusual patterns

Why do these applications need machine learning?

Imagine if we tried to solve these problems with traditional programming methods:

Machine learning enables computers to automatically learn these complex patterns from large amounts of data, greatly simplifying the problem-solving process.


Computer Vision Applications

Face Recognition

Application scenarios: phone unlocking, access control systems, identity verification

How It Works:

  1. Detect face locations in an image
  2. Extract facial features (eye spacing, nose shape, etc.)
  3. Compare with facial features in a database

Autonomous driving

Application scenarios: Tesla Autopilot, Baidu Apollo, Google Waymo

Core Tasks:

Example

Object Detection Example in Autonomous Driving (Conceptual Code)

import

cv2

import

numpy

as

np

def

detect_objects

(

image

)

:

   

"""
    Detect objects in an image (vehicles, pedestrians, traffic signs, etc.)
    """

   

1. Preprocess the image

    processed_image

=

preprocess_image

(

image

)

   

2. Use a trained deep learning model to detect objects

   

Here a pretrained YOLO model is used as an example

    boxes

,

classes

,

scores

=

yolo_model.

detect

(

processed_image

)

   

3. Filter out low-confidence detection results

    valid_detections

=

filter_detections

(

boxes

,

classes

,

scores

)

   

4. Draw detection results on the image

    result_image

=

draw_detections

(

image

,

valid_detections

)

   

return

result_image

,

valid_detections

In practical applications, this is only one component of the entire autonomous driving system

It also needs to be combined with multiple modules such as sensor fusion and path planning

Medical Image Diagnosis

Application scenarios: X-ray analysis, CT scans, pathology slide analysis

Advantage:


Natural Language Processing Applications

Intelligent Assistants

Application scenarios: Siri, XiaoAI, Tmall Genie

Core Features:

Example

Intelligent Assistant Workflow (Simplified Example)

import

speech_recognition

as

sr

from

textblob

import

TextBlob

class

SmartAssistant:

   

def

init

(

self

)

:

       

self

.

recognizer

=

sr.

Recognizer

(

)

   

def

listen_and_respond

(

self

)

:

       

"""Listen to the user's voice and respond"""

       

with

sr.

Microphone

(

)

as

source:

           

print

(

"Listening..."

)

            audio

=

self

.

recognizer

.

listen

(

source

)

       

try

:

           

1. Speech recognition

            text

=

self

.

recognizer

.

recognize_google

(

audio

,

language

=

'zh-CN'

)

           

print

(

f

"User said: {text}"

)

           

2. Intent understanding

            intent

=

self

.

understand_intent

(

text

)

           

3. Generate a response

            response

=

self

.

generate_response

(

intent

,

text

)

           

print

(

f

"Assistant response: {response}"

)

           

return

response

       

except

sr.

UnknownValueError

:

           

return

"Sorry, I didn't catch that, please say it again"

   

def

understand_intent

(

self

,

text

)

:

       

"""Understand user intent"""

       

Simplified intent recognition

       

if

"weather"

in

text:

           

return

"weather"

       

elif

"time"

in

text:

           

return

"time"

       

elif

"joke"

in

text:

           

return

"joke"

       

else

:

           

return

"unknown"

   

def

generate_response

(

self

,

intent

,

text

)

:

       

"""Generate a response based on intent"""

       

if

intent

==

"weather"

:

           

return

"It's sunny today, temperature 25 degrees"

       

elif

intent

==

"time"

:

           

from

datetime

import

datetime

           

return

f

"The current time is {datetime.now().strftime('%H:%M')}"

       

elif

intent

==

"joke"

:

           

return

"Why do programmers like the dark? Because there are no bugs!"

       

else

:

           

return

"Sorry, I'm still learning and can't understand this question"

Usage examples

assistant

=

SmartAssistant

(

)

assistant.listen_and_respond() # Uncomment when actually running

Machine translation

Application scenarios: Google Translate, Baidu Translate, Youdao Translate

How It Works:

  1. Encode source-language text into a numeric representation
  2. Learn the mapping relationship between languages through a neural network
  3. Decode into target-language text

Sentiment analysis

Application scenarios: product review analysis, social media monitoring, customer feedback processing

Example

Sentiment Analysis Example

from

textblob

import

TextBlob

import

jieba

def

analyze_sentiment_chinese

(

text

)

:

   

"""
    Chinese Sentiment Analysis Example
    """

   

Use jieba for word segmentation

    words

=

jieba.

cut

(

text

)

    word_list

=

" "

.

join

(

words

)

   

This is simplified here; practical applications need a dedicated Chinese sentiment analysis model

   

You can use libraries such as SnowNLP and BERT-Chinese

   

Simulate sentiment analysis results

    positive_words

=

[

"good"

,

"great"

,

"like"

,

"satisfied"

,

"Referral"

]

    negative_words

=

[

"bad"

,

"poor"

,

"dislike"

,

"disappointed"

,

"not recommended"

]

    pos_count

=

sum

(

1

for

word

in

positive_words

if

word

in

text

)

    neg_count

=

sum

(

1

for

word

in

negative_words

if

word

in

text

)

   

if

pos_count

neg_count:

       

return

"positive sentiment"

   

elif

neg_count

pos_count:

       

return

"negative sentiment"

   

else

:

       

return

"neutral sentiment"

Test example

reviews

=

[

   

"This product is really great, I like it a lot!"

,

   

"The quality is too poor, not worth buying at all."

,

   

"It's okay, nothing special."

]

for

review

in

reviews:

    sentiment

=

analyze_sentiment_chinese

(

review

)

   

print

(

f

"Review: {review}"

)

   

print

(

f

"Sentiment: {sentiment}"

)

   

print

(

"---"

)


Recommendation System Applications

E-commerce Recommendation

Application scenarios: Taobao product recommendations, Amazon recommendations

Recommended strategy:

  1. Collaborative Filtering: recommend based on similarity of user behavior
  2. Content Recommendation: recommend based on similarity of product features
  3. Hybrid Recommendation: combine multiple strategies

Example

Simple Collaborative Filtering Recommendation Example

import

numpy

as

np

User-item rating matrix (rows are users, columns are items)

ratings

=

np.

array

(

[

   

[

5

,

3

,

0

,

1

]

,

 

User 1's ratings for items 1, 2, and 4

   

[

4

,

0

,

0

,

1

]

,

 

User 2's ratings for items 1 and 4

   

[

1

,

1

,

0

,

5

]

,

 

User 3's ratings for items 1, 2, and 4

   

[

1

,

0

,

0

,

4

]

,

 

User 4's ratings for items 1 and 4

   

[

0

,

1

,

5

,

4

]

,

 

User 5's ratings for items 2, 3, and 4

]

)

def

user_similarity

(

user1

,

user2

)

:

   

"""Compute the similarity between two users (cosine similarity)"""

   

Find items rated by both users

    common_items

=

np.

where

(

(

user1

0

)

&

(

user2

0

)

)

[

0

]

   

if

len

(

common_items

)

==

0

:

       

return

0

   

Compute cosine similarity

    user1_ratings

=

user1

[

common_items

]

    user2_ratings

=

user2

[

common_items

]

    dot_product

=

np.

dot

(

user1_ratings

,

user2_ratings

)

    norm1

=

np.

linalg

.

norm

(

user1_ratings

)

    norm2

=

np.

linalg

.

norm

(

user2_ratings

)

   

if

norm1

==

0

or

norm2

==

0

:

       

return

0

   

return

dot_product /

(

norm1 * norm2

)

def

recommend_items

(

user_id

,

ratings_matrix

,

k

=

2

)

:

   

"""Recommend items for a given user"""

    user_ratings

=

ratings_matrix

[

user_id

]

   

Compute the similarity between this user and other users

    similarities

=

[

]

   

for

i

,

other_user

in

enumerate

(

ratings_matrix

)

:

       

if

i

!=

user_id:

            sim

=

user_similarity

(

user_ratings

,

other_user

)

            similarities.

append

(

(

i

,

sim

)

)

   

Sort by similarity

    similarities.

sort

(

key

=

lambda

x: x

[

1

]

,

reverse

=

True

)

   

Find items the user has not rated

    unrated_items

=

np.

where

(

user_ratings

==

0

)

[

0

]

   

Predict the user's ratings for unrated items

    predictions

=

[

]

   

for

item_id

in

unrated_items:

        weighted_sum

=

0

        similarity_sum

=

0

       

for

similar_user_id

,

similarity

in

similarities

[

:k

]

:

           

if

similarity

0

and

ratings_matrix

[

similar_user_id

]

[

item_id

]

0

:

                weighted_sum +

=

similarity * ratings_matrix

[

similar_user_id

]

[

item_id

]

                similarity_sum +

=

similarity

       

if

similarity_sum

0

:

            predicted_rating

=

weighted_sum / similarity_sum

            predictions.

append

(

(

item_id

,

predicted_rating

)

)

   

Sort by predicted rating

    predictions.

sort

(

key

=

lambda

x: x

[

1

]

,

reverse

=

True

)

   

return

predictions

[

:

3

]

 

Return the top 3 recommendations

Recommend items for user 0

user_id

=

0

recommendations

=

recommend_items

(

user_id

,

ratings

)

print

(

f

"Items recommended for user {user_id}:"

)

for

item_id

,

predicted_rating

in

recommendations:

   

print

(

f

"Item {item_id + 1}, predicted rating: {predicted_rating:.2f}"

)

Video Recommendation

Application scenarios: Douyin, YouTube, Netflix

Feature:


Predictive Analytics Applications

Financial Risk Control

Application scenarios: credit card fraud detection, loan approval

Example

Simple Fraud Detection Example

import

numpy

as

np

from

sklearn.

ensemble

import

RandomForestClassifier

from

sklearn.

model_selection

import

train_test_split

Simulate transaction data

Features: transaction amount, transaction time, merchant type, location, etc.

Labels: 0 = normal, 1 = fraud

np.

random

.

seed

(

42

)

Generate simulated data

n_samples

=

1000

n_features

=

4

Normal transactions

normal_transactions

=

np.

random

.

normal

(

loc

=

[

100

,

14

,

2

,

3

]

,

scale

=

[

50

,

4

,

1

,

1

]

,

                                     size

=

(

int

(

n_samples *

0.95

)

,

n_features

)

)

Fraudulent transactions (usually with abnormal amounts, abnormal times, etc.)

fraud_transactions

=

np.

random

.

normal

(

loc

=

[

500

,

3

,

4

,

1

]

,

scale

=

[

200

,

2

,

1

,

0.5

]

,

                                    size

=

(

int

(

n_samples *

0.05

)

,

n_features

)

)

Merge the data and add labels

X

=

np.

vstack

(

[

normal_transactions

,

fraud_transactions

]

)

y

=

np.

hstack

(

[

np.

zeros

(

len

(

normal_transactions

)

)

,

np.

ones

(

len

(

fraud_transactions

)

)

]

)

Split into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Train a random forest model

model

=

RandomForestClassifier

(

n_estimators

=

100

,

random_state

=

42

)

model.

fit

(

X_train

,

y_train

)

Evaluate the model

accuracy

=

model.

score

(

X_test

,

y_test

)

print

(

f

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

)

Predict a new transaction

new_transaction

=

np.

array

(

[

[

450

,

2

,

4

,

1

]

]

)

 

Abnormal transaction

fraud_probability

=

model.

predict_proba

(

new_transaction

)

[

0

]

[

1

]

print

(

f

"Probability that the new transaction is fraud: {fraud_probability:.2f}"

)

if

fraud_probability

0.5

:

   

print

(

"Warning: suspicious transaction detected!"

)

else

:

   

print

(

"Transaction is normal."

)

Stock Price Prediction

Application scenarios: quantitative trading, investment decisions

Challenges:


Anomaly Detection Applications

Network Security

Application scenarios: intrusion detection, malware identification

How It Works:

  1. Learn normal network traffic patterns
  2. Detect behavior that deviates from normal patterns
  3. Trigger an alert or block

Industrial Quality Inspection

Application scenarios: product defect detection, equipment failure prediction

Example

Simple Anomaly Detection Example

import

numpy

as

np

from

sklearn.

ensemble

import

IsolationForest

import

matplotlib.

pyplot

as

plt

Simulate sensor data (normal data + a few anomalies)

np.

random

.

seed

(

42

)

Normal data: sensor readings when the equipment is running normally

normal_data

=

np.

random

.

normal

(

loc

=

10

,

scale

=

1

,

size

=

(

200

,

2

)

)

Abnormal data: sensor readings when the equipment fails

anomaly_data

=

np.

random

.

normal

(

loc

=

[

15

,

5

]

,

scale

=

[

1

,

1

]

,

size

=

(

10

,

2

)

)

Merge data

all_data

=

np.

vstack

(

[

normal_data

,

anomaly_data

]

)

Use Isolation Forest for anomaly detection

model

=

IsolationForest

(

contamination

=

0.05

,

random_state

=

42

)

predictions

=

model.

fit_predict

(

all_data

)

Visualize the result

plt.

figure

(

figsize

=

(

10

,

6

)

)

normal_points

=

all_data

[

predictions

==

1

]

anomaly_points

=

all_data

[

predictions

==

1

]

plt.

scatter

(

normal_points

[

:

,

0

]

,

normal_points

[

:

,

1

]

,

           c

=

'blue'

,

label

=

'Normal Data'

)

plt.

scatter

(

anomaly_points

[

:

,

0

]

,

anomaly_points

[

:

,

1

]

,

           c

=

'red'

,

label

=

'Abnormal Data'

)

plt.

xlabel

(

'Sensor 1 Reading'

)

plt.

ylabel

(

'Sensor 2 Reading'

)

plt.

title

(

'Equipment Operating Status Anomaly Detection'

)

plt.

legend

(

)

plt.

grid

(

True

)

plt.

show

(

)

print

(

f

"Detected {len(anomaly_points)} anomaly points"

)