Runoob Tutorial ArchiveEnglish

AI Ethics and Safety

AI Ethics and Safety

You might think ethics is a very abstract word, far removed from daily life.

But consider these scenarios:

These are not science fiction; they are things that have happened or are happening.

AI is not a neutral tool; it reflects biases in the training data, it can be used for malicious purposes, and its output may contain serious errors. While enjoying the convenience of AI, you need to be aware of its risks.

With great power comes great responsibility; understanding the risks of AI is necessary to use AI responsibly.


AI Bias Issues

AI does not inherently have biases, but it inherits biases from the training data.

If the training data has few samples of female engineers, the AI might assume that the term "engineer" defaults to male.

If a certain group of people has been treated unfairly in loan approvals historically, the patterns learned by the AI may perpetuate or even amplify this unfairness.

Where Does Bias Come From

There are three main sources of AI bias:

Source Description Example
Training data bias The data itself contains unfair historical patterns If a certain position has a high proportion of men, the AI will assume that the position is suitable for men
Annotation bias Subjective tendencies of the annotator are introduced during manual annotation Different people have different standards for judging offensive content
Deviation in use scenarios Mismatch between training scenarios and actual use scenarios Facial recognition trained mainly on light-skinned individuals has a low recognition rate for dark-skinned individuals

Real-world bias cases

In 2018, Amazon discovered that its AI recruiting system was biased against women. This system analyzed ten years of resume data, most of which came from men. As a result, resumes containing the words "female" or "woman" were penalized, and graduates from women's colleges were also given lower scores. Amazon eventually abandoned this system.

Similar examples include: some facial recognition systems have a much higher error rate in recognizing dark-skinned individuals compared to light-skinned individuals.

Some medical AI models have lower diagnostic accuracy for specific races.

Bias is not a question of "XX correctness," but of real harm—it can cause someone to lose a job, a loan, or even the chance to receive a correct medical diagnosis.

How to detect AI bias

We can create a simple bias detection example using code:

Example

============================================

AI Bias Detection Example

Detect whether there is a tendency towards bias in the text regarding gender, race, etc.

============================================

class

BiasDetector:

   

"""A simple bias detector to demonstrate the basic idea of bias detection"""

   

def

init

(

self

)

:

       

"""Initialize keywords and patterns related to bias"""

       

Gender-related occupational stereotypes

       

self

.

gendered_occupations

=

{

           

"nurse"

:

"Female"

,

           

"Engineer"

:

"Male"

,

           

"Programmer"

:

"Male"

,

           

"Teacher"

:

"Female"

,

           

"Chef"

:

"Male"

,

           

"Nanny"

:

"Female"

,

           

"Scientist"

:

"Male"

,

           

"Secretary"

:

"Female"

,

       

}

       

Words considered "positive"

       

self

.

positive_words

=

[

           

"Excellent"

,

"Intelligent"

,

"Capable"

,

"Successful"

,

"Excellent"

,

"Professional"

,

"Reliable"

,

"Responsible"

       

]

       

Words considered "negative"

       

self

.

negative_words

=

[

           

"Emotional"

,

"Weak"

,

"Irrational"

,

"Sensitive"

,

"Impulsive"

,

"Careless"

,

"Unreliable"

       

]

       

Sentence templates for testing

       

self

.

test_templates

=

[

           

"{occupation} should be a {gender} job"

,

           

"{gender} is more suitable for {occupation}"

,

           

"This {occupation} is very {adjective}"

,

       

]

   

def

analyze_gender_bias

(

self

,

text:

str

)

dict

:

       

"Analyze gender bias indicators in the text"

result

=

{

           

"text"

: text

,

           

"has_gendered_occupation"

:

False

,

           

"has_gender_mention"

:

False

,

           

"bias_warning"

:

""

,

       

}

       

Check for gendered occupational descriptions

       

for

occupation

,

gender

in

self

.

gendered_occupations

.

items

(

)

:

           

if

occupation

in

text:

result

[

"has_gendered_occupation"

]

=

True

result

[

"occupation"

]

=

occupation

result

[

"stereotyped_gender"

]

=

gender

       

Check for gender mentions

       

if

"Male"

in

text

or

"female"

in

text

or

"male"

in

text

or

"female"

in

text:

            result

[

"has_gender_mention"

]

=

True

       

Generate warning (if any)

       

if

result

[

"has_gendered_occupation"

]

and

result

[

"has_gender_mention"

]

:

result

[

"bias_warning"

]

=

(

                f

"⚠️ Warning: The text will associate the profession '{result['occupation']}' with a specific gender,"

                f

"This may carry the risk of stereotypes"

           

)

       

return

result

   

def

detect_bias_in_sentences

(

self

,

sentences:

list

)

list

:

       

"""Batch check bias for a set of sentences"""

results

=

[

]

       

for

sentence

in

sentences:

analysis

=

self

.

analyze_gender_bias

(

sentence

)

results.

append

(

analysis

)

       

return

results

   

def

runoob_demo_test

(

self

)

:

       

"""runoob demo: testing some common biased statements"""

test_sentences

=

[

           

"Engineering is a man's job"

,

           

"Women are more suited to be nurses"

,

           

"This programmer is excellent"

,

           

"She is excellent at being a doctor"

,

           

"Men are not suitable to be kindergarten teachers"

,

       

]

       

print

(

"="

60

)

       

print

(

"RUNOOB AI Bias Detection Demo"

)

       

print

(

"="

60

)

results

=

self

.

detect_bias_in_sentences

(

test_sentences

)

       

for

i

,

result

in

enumerate

(

results

,

1

)

:

           

print

(

f

"\nTest {i}: {result['text']}"

)

           

if

result

[

"bias_warning"

]

:

               

print

(

f

" {result['bias_warning']}"

)

           

else

:

               

print

(

✓ No obvious gender stereotypes detected

)

       

return

results

============================================

Advanced Bias Detection: Statistical Analysis

============================================

def

analyze_representation_distribution

(

data:

list

)

dict

:

   

"""
Analyze the representative distribution of different groups in the data
For example: whether the pass rate of male and female resumes is consistent in recruitment data
"""

   

Example data: group label + result (passed/failed)

   

In actual applications, this should be real business data

   

from

collections

import

defaultdict

counts

=

defaultdict

(

lambda

:

{

"total"

:

0

,

"positive"

:

0

}

)

   

for

group

,

outcome

in

data:

        counts

[

group

]

[

"total"

]

=

1

       

if

outcome

==

"positive"

:

counts

[

group

]

[

"positive"

]

=

1

   

Calculate the pass rate of each group

rates

=

{

}

   

for

group

,

stats

in

counts.

items

(

)

:

       

if

stats

[

"total"

]

0

:

rates

[

group

]

=

{

               

"total"

: stats

[

"total"

]

,

               

"positive"

: stats

[

"positive"

]

,

               

"rate"

: stats

[

"positive"

]

/ stats

[

"total"

]

,

           

}

   

Check if the pass rate difference is too large (simplified version)

   

In practical applications, statistical significance tests should be used

   

if

len

(

rates

)

=

2

:

all_rates

=

[

r

[

"rate"

]

for

r

in

rates.

values

(

)

]

max_rate

=

max

(

all_rates

)

min_rate

=

min

(

all_rates

)

       

if

max_rate - min_rate

0.2

:

Differences exceeding 20% are noteworthy

rates

[

"_warning"

]

=

(

                f

"Detected large differences between groups: highest pass rate {max_rate:.1%},"

                f

"lowest pass rate {min_rate:.1%}, further investigation is recommended"

           

)

   

return

rates

============================================

Run Demo

============================================

if

name

==

"main"

:

   

Demo 1: Simple Bias Detection

detector

=

BiasDetector

(

)

detector.

runoob_demo_test

(

)

   

print

(

"\n"

"="

60

)

   

print

(

"RUNOOB Representative Distribution Analysis Demo"

)

   

print

(

"="

60

)

   

Demo 2: Pass Rate Distribution Analysis

   

Simulated data: (group, result), "positive" indicates pass

hiring_data

=

[

       

(

"male"

,

"positive"

)

,

(

"Male"

,

"positive"

)

,

(

"male"

,

"positive"

)

,

       

(

"male"

,

"positive"

)

,

(

"Male"

,

"negative"

)

,

       

(

"female"

,

"positive"

)

,

(

"female"

,

"negative"

)

,

(

"female"

,

"negative"

)

,

       

(

"female"

,

"negative"

)

,

(

"female"

,

"negative"

)

,

   

]

distribution

=

analyze_representation_distribution

(

hiring_data

)

   

for

group

,

stats

in

distribution.

items

(

)

:

       

if

group.

startswith

(

"_"

)

:

           

continue

 

Skip warning field

       

print

(

f

"\nGroup: {group}"

)

       

print

(

f

"Total count: {stats['total']}"

)

       

print

(

f

" Passed: {stats['positive']}"

)

       

print

(

f

" Pass rate: {stats['rate']:.1%}"

)

   

if

"_warning"

in

distribution:

       

print

(

f

"\n⚠️ Warning: {distribution['_warning']}"

)

Running the code above, you will see:

Original prompt (Chinese, left untranslated)



============================================================

RUNOOB AI 偏见检测演示

============================================================



测试 1: 工程师应该是男性的工作

   ⚠️ 注意:文本将职业'工程师'与特定性别关联,这可能存在刻板印象风险



测试 2: 女性更适合做护士

   ⚠️ 注意:文本将职业'护士'与特定性别关联,这可能存在刻板印象风险



测试 3: 这个程序员很优秀

   ✓ 未检测到明显的性别刻板印象



测试 4: 她当医生很出色

   ✓ 未检测到明显的性别刻板印象



测试 5: 男性不适合做幼儿园老师

   ✓ 未检测到明显的性别刻板印象



============================================================

RUNOOB 代表性分布分析演示

============================================================



群体: 男性

  总数: 5

  通过: 4

  通过率: 80.0%



群体: 女性

  总数: 5

  通过: 1

  通过率: 20.0%

警告: 检测到群体间差异较大:最高通过率 80.0%,最低通过率 20.0%,建议进一步调查

This example demonstrates the basic idea of bias detection: checking if different groups are treated fairly.

How to deal with AI bias

There is no perfect solution, but there are some best practices to reduce the impact of bias:

Method Description Who to do
Data review Check the representativeness of training data, ensuring sufficient samples for all groups Data scientist
Bias audit Regularly test the performance differences of the model across different groups AI Team
Manual Review High-risk decisions (such as hiring, loans) retain a manual review step Business side
Diverse team Having people from different backgrounds participate in AI development can uncover more blind spots Company management

Remember:AI is not objective; it only amplifies existing patterns in the data. If you train AI with biased data, you will get a biased AI.


Privacy and Data Security

Where does the content you input into AI go? Will it be saved? What will it be used for?

These questions are more important than you think.

The content you input into AI may be saved

Most AI tools' terms of service state that your input may be collected to improve the service.

If you input this information into AI, it may be saved or used for training:

Company trade secrets, personal ID numbers, customer private information, unreleased product plans, financial data

This happened in 2023: an employee of a company entered the company's confidential code into an AI tool, and as a result, this code appeared in suggestions given by that AI tool to other users.

What not to tell AI

A simple principle: if you don't want a stranger to know about it, don't tell the AI.

Specifically:

Information Type Risk Level Description
Personally Identifiable Information (ID card number, bank card number) Extremely high Absolutely do not input
Company trade secrets, non-public information Extremely high Unless using AI deployed internally by the company
Customer privacy data Extremely high May violate data protection regulations
Personal sensitive experiences High Consider carefully
General work documents Low Generally no problem

Best practices for protecting privacy

If you must use AI to process sensitive information:

Important reminder:Do not assume AI will keep your information confidential. Unless the contract explicitly states that data will not be saved or used for training, assume your input may be used to improve the product.


AI hallucination problem

AI will talk nonsense seriously; this is called hallucination.

It may fabricate non-existent papers, cite non-existent legal articles, or generate completely non-existent codebases. The most dangerous thing is that it says these things with a very confident tone.

What is AI hallucination

Typical manifestations of hallucination:

The problem is: AI does not know it is fabricating; it is just generating a sequence of text that looks reasonable.

Real hallucination cases

In 2023, a lawyer used AI to write a legal document, and the AI cited 6 non-existent cases.

The judge found that these cases could not be found at all and asked the lawyer what was going on, only then did the lawyer realize that the AI had fabricated them.

Another common scenario is code generation: AI gives you a piece of code that looks perfect, but it calls a library function that doesn't exist.

There is also academic writing: AI invents non-existent references that look particularly formal.

How to identify and deal with hallucinations

There is no way to completely avoid hallucinations, but you can reduce the risk:

Scenario Countermeasures Verification methods
Fact checking Require AI to provide source links Self-search to verify key facts
Code generation Require AI to use common, stable libraries Run tests to check if functions actually exist
Legal/medical advice For reference only, not for final decision-making Consult a professional
Academic citations Do not use citations provided directly by AI Every citation must be verified through searching

A practical tip is: for important information, ask the AI to answer in at least two different ways to check for consistency.

If the first response says "this study was published in 2020" and the second says "this work was first proposed in 2021," you should be wary—at least one is wrong, and both might be wrong.

Golden rule for high-risk scenarios:Do not trust, verifyAI output is always for reference, not the final answer. For important decisions involving law, medicine, investment, security, etc., manual verification is mandatory.


Deepfake Risks

The phrase "pictures tell the truth" is no longer valid in the age of AI.

AI can generate extremely realistic photos, videos, and audio, making it difficult to distinguish truth from falsehood. This is called deepfake.

What is deepfake

Deepfake technology can:

In 2023, scammers used AI to imitate a company CEO's voice and tricked the company out of $240,000.

How to identify AI-generated content

Although deepfakes are becoming increasingly realistic, there are still some clues to identify them:

Type Common flaws Checking methods
AI images Abnormal fingers, strange teeth, inconsistent lighting and shadows Look closely at the details, especially the hands
AI video Unnatural blinking, stiff facial expressions Check if the movements are smooth and natural
AI audio Abnormal background noise, strange speaking pace and rhythm Pay attention to whether the tone and pauses are natural

Additionally, there are now specialized tools to detect whether content is AI-generated.

However, in the long run, detection will become increasingly difficult—AI-generated content will become more realistic.

Legal and Ethical Boundaries

Legitimate use cases for deepfakes:

Film special effects, historical documentary restoration, language learning (having AI speak in your native language)

Misuse cases for deepfakes:

Spreading rumors and defamation, fraud, creating pornographic content, forging evidence

Many countries are formulating relevant laws. In China, using deepfakes to commit fraud, defamation, and other acts is explicitly illegal.

New guidelines when facing video/audio evidence:Do not trust single audiovisual evidence unless verified by multiple independent sources. In the age of AI, what you see may not be the truth.


Intellectual property issues

Who owns the copyright of AI-generated content?

This is a developing legal field, and there is no globally unified answer yet.

Copyright ownership of AI-generated content

Current general principles:

Region Can AI-generated content obtain copyright? Explanation
USA Generally no The Copyright Office requires a "human author"
EU Under development Tends to protect human creators

Key point: Purely AI-generated content is usually not protected by copyright. If you just input "draw a cat," you cannot claim copyright to the generated image.

But if you put a lot of creative design into the prompt, the situation might be different—this is a legal gray area.

Copyright disputes over training data

Another bigger controversy: Is it infringement for AI to be trained on copyrighted works?

For example, if AI reads ten thousand copyrighted novels and can then generate a new novel in a similar style, does this infringe on the original author's rights?

This issue is currently in litigation, and different countries may have different rulings.

As a user, you need to know:

The content you generate with AI may contain elements from the training data. If the AI "references" too much of a copyrighted work, you may be at risk.

The safest approach: before commercial use, confirm that the training data source of the AI tool you are using is legal.

Precautions when using AI for creation

If you use AI for creation:


Guidelines for Responsible AI Use

After discussing so many risks, this is not to make you fear AI, but to help you use it more safely.

Here is a set of simple guidelines to help you use AI responsibly.

Three core principles

Principle Description Specific actions
Verify important information AI output is for reference, not the truth Important facts must be searched and cross-verified
Do not rely on AI for major decisions AI has no sense of responsibility; you bear the consequences Decisions in medicine, law, investment, etc., require human judgment
Transparently declare AI usage Let others know that the content involves AI Consider stating the role of AI when publishing publicly

Checklists for different scenarios

Before using AI to write emails/documents, ask yourself:

Before using AI to write code, ask yourself:

Before generating public content with AI, ask yourself:

When the AI's suggestions conflict with your judgment,

whose should you listen to?

This question has no standard answer, but you can consider it in this order:

Remember:You are the decision-maker, AI is the consultant. The final responsibility lies with you, not the AI.


AI Regulatory Trends in Various Countries

AI is developing too fast, and laws are struggling to keep up. Understanding the regulatory direction of major countries can help you determine what is compliant.

Major Global Regulatory Frameworks

Region Key Regulations/Initiatives Core Philosophy Key Focus Areas
European Union AI Act Risk-based regulation High-risk scenarios must comply
United States Regulation by various departments Industry self-regulation + control in key areas Safety, discrimination, transparency
China Interim Measures for the Management of Generative Artificial Intelligence Services Content safety + algorithmic transparency Content compliance, data security
United Kingdom AI Safety and Innovation Framework Encouraging innovation + prudent regulation Safety testing, ethics

Common regulatory trends for high-risk AI applications

Regardless of the country, the following scenarios are considered high-risk and will be subject to stricter regulation:

Medical diagnosis, financial decision-making, judicial sentencing, recruitment screening, educational scoring, public service resource allocation

The common characteristic of these scenarios is that they directly affect people's fundamental rights.

If you are developing AI applications in these fields, you need to pay special attention to compliance issues.

Impact on individual users

Regulations mainly target enterprises, but they also affect individual users:

The AI tools you use must comply with local content review requirements;

Some high-risk AI services may require real-name registration for use;

You have the right to know whether you are conversing with an AI or a human (transparency requirement).