第100+27步 ChatGPT学习:概率校准 Temperature Scaling

news2024/10/8 9:16:17

基于Python 3.9版本演示

一、写在前面

最近看了一篇在Lancet子刊《eClinicalMedicine》上发表的机器学习分类的文章:《Development of a novel dementia risk prediction model in the general population: A large, longitudinal, population-based machine-learning study》。

学到一种叫做“概率校准”的骚操作,顺手利用GPT系统学习学习。

文章中用的技术是:保序回归(Isotonic regression)。

为了体现举一反三,顺便问了GPT还有哪些方法也可以实现概率校准。它给我列举了很多,那么就一个一个学习吧。

这一期,介绍一个叫做 Temperature Scaling 的方法。

二、Temperature Scaling

Temperature Scaling的核心思想是通过引入一个温度参数(temperature parameter, T)来调整模型的logits(未归一化的输出值),从而校准输出的概率分布。具体来说,它是一种后处理方法,即在训练完模型后进行校准,而不改变模型的结构或训练过程。

(1)主要步骤

1)训练模型:首先,训练你的分类模型,获得logits和初步的概率预测。

2)验证集校准:使用验证集来找到最优的温度参数T。通过最小化负对数似然(negative log-likelihood, NLL)或者期望校准误差(expected calibration error, ECE)等校准指标来找到最佳的T。

3)校准:使用找到的最优温度参数T对测试集或实际应用中的预测概率进行校准。

三、Temperature Scaling代码实现

下面,我编一个1比3的不太平衡的数据进行测试,对照组使用不进行校准的SVM模型,实验组就是加入校准的SVM模型,看看性能能够提高多少?

(1)不进行校准的SVM模型(默认参数)

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve

# 加载数据
dataset = pd.read_csv('8PSMjianmo.csv')
X = dataset.iloc[:, 1:20].values
Y = dataset.iloc[:, 0].values

# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=666)

# 标准化数据
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

# 使用SVM分类器
classifier = SVC(kernel='linear', probability=True)
classifier.fit(X_train, y_train)

# 预测结果
y_pred = classifier.predict(X_test)
y_testprba = classifier.decision_function(X_test)

y_trainpred = classifier.predict(X_train)
y_trainprba = classifier.decision_function(X_train)

# 混淆矩阵
cm_test = confusion_matrix(y_test, y_pred)
cm_train = confusion_matrix(y_train, y_trainpred)
print(cm_train)
print(cm_test)

# 绘制测试集混淆矩阵
classes = list(set(y_test))
classes.sort()
plt.imshow(cm_test, cmap=plt.cm.Blues)
indices = range(len(cm_test))
plt.xticks(indices, classes)
plt.yticks(indices, classes)
plt.colorbar()
plt.xlabel('Predicted')
plt.ylabel('Actual')
for first_index in range(len(cm_test)):
    for second_index in range(len(cm_test[first_index])):
        plt.text(first_index, second_index, cm_test[first_index][second_index])

plt.show()

# 绘制训练集混淆矩阵
classes = list(set(y_train))
classes.sort()
plt.imshow(cm_train, cmap=plt.cm.Blues)
indices = range(len(cm_train))
plt.xticks(indices, classes)
plt.yticks(indices, classes)
plt.colorbar()
plt.xlabel('Predicted')
plt.ylabel('Actual')
for first_index in range(len(cm_train)):
    for second_index in range(len(cm_train[first_index])):
        plt.text(first_index, second_index, cm_train[first_index][second_index])

plt.show()

# 计算并打印性能参数
def calculate_metrics(cm, y_true, y_pred_prob):
    a = cm[0, 0]
    b = cm[0, 1]
    c = cm[1, 0]
    d = cm[1, 1]
    acc = (a + d) / (a + b + c + d)
    error_rate = 1 - acc
    sen = d / (d + c)
    sep = a / (a + b)
    precision = d / (b + d)
    F1 = (2 * precision * sen) / (precision + sen)
    MCC = (d * a - b * c) / (np.sqrt((d + b) * (d + c) * (a + b) * (a + c)))
    auc_score = roc_auc_score(y_true, y_pred_prob)
    
    metrics = {
        "Accuracy": acc,
        "Error Rate": error_rate,
        "Sensitivity": sen,
        "Specificity": sep,
        "Precision": precision,
        "F1 Score": F1,
        "MCC": MCC,
        "AUC": auc_score
    }
    return metrics

metrics_test = calculate_metrics(cm_test, y_test, y_testprba)
metrics_train = calculate_metrics(cm_train, y_train, y_trainprba)

print("Performance Metrics (Test):")
for key, value in metrics_test.items():
    print(f"{key}: {value:.4f}")

print("\nPerformance Metrics (Train):")
for key, value in metrics_train.items():
print(f"{key}: {value:.4f}")

结果输出:

记住这些个数字。

这个参数的SVM还没有LR好。

(2)进行校准的SVM模型(默认参数)

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, roc_auc_score, brier_score_loss
from sklearn.calibration import calibration_curve

# 加载数据
dataset = pd.read_csv('8PSMjianmo.csv')
X = dataset.iloc[:, 1:20].values
Y = dataset.iloc[:, 0].values

# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=666)

# 标准化数据
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

# 使用SVM分类器
classifier = SVC(kernel='rbf', C=0.1, probability=True)
classifier.fit(X_train, y_train)

# 获取未校准的概率预测
y_train_probs = classifier.predict_proba(X_train)[:, 1]
y_test_probs = classifier.predict_proba(X_test)[:, 1]

# Temperature Scaling
class TemperatureScaling:
    def __init__(self):
        self.temperature = 1.0

    def fit(self, logits, true_labels):
        from scipy.optimize import minimize

        def nll_loss(T):
            scaled_logits = logits / T
            probs = np.exp(scaled_logits) / np.sum(np.exp(scaled_logits), axis=1, keepdims=True)
            log_probs = np.log(probs[np.arange(len(true_labels)), true_labels])
            return -np.mean(log_probs)

        logits = np.log(np.column_stack([1 - logits, logits]))  # 转换成logits
        result = minimize(nll_loss, [1.0], bounds=[(0.1, 10.0)])
        self.temperature = result.x[0]

    def predict_proba(self, probs):
        logits = np.log(np.column_stack([1 - probs, probs]))  # 转换成logits
        scaled_logits = logits / self.temperature
        exp_scaled_logits = np.exp(scaled_logits)
        probs = exp_scaled_logits[:, 1] / np.sum(exp_scaled_logits, axis=1, keepdims=True)[:, 0]
        return probs

# 训练Temperature Scaling模型
temp_scaling = TemperatureScaling()
temp_scaling.fit(y_train_probs, y_train)

# 进行校准
calibrated_train_probs = temp_scaling.predict_proba(y_train_probs)
calibrated_test_probs = temp_scaling.predict_proba(y_test_probs)

# 预测结果
y_train_pred = (calibrated_train_probs >= 0.5).astype(int)
y_test_pred = (calibrated_test_probs >= 0.5).astype(int)

# 混淆矩阵
cm_test = confusion_matrix(y_test, y_test_pred)
cm_train = confusion_matrix(y_train, y_train_pred)
print(cm_train)
print(cm_test)

# 绘制混淆矩阵函数
def plot_confusion_matrix(cm, classes, title='Confusion Matrix'):
    plt.imshow(cm, cmap=plt.cm.Blues)
    indices = range(len(cm))
    plt.xticks(indices, classes)
    plt.yticks(indices, classes)
    plt.colorbar()
    plt.xlabel('Predicted')
    plt.ylabel('Actual')
    for first_index in range(len(cm)):
        for second_index in range(len(cm[first_index])):
            plt.text(second_index, first_index, cm[first_index][second_index])
    plt.title(title)
    plt.show()

# 绘制测试集混淆矩阵
plot_confusion_matrix(cm_test, list(set(y_test)), 'Confusion Matrix (Test)')

# 绘制训练集混淆矩阵
plot_confusion_matrix(cm_train, list(set(y_train)), 'Confusion Matrix (Train)')

# 计算并打印性能参数
def calculate_metrics(cm, y_true, y_pred_prob):
    a = cm[0, 0]
    b = cm[0, 1]
    c = cm[1, 0]
    d = cm[1, 1]
    acc = (a + d) / (a + b + c + d)
    error_rate = 1 - acc
    sen = d / (d + c)
    sep = a / (a + b)
    precision = d / (b + d)
    F1 = (2 * precision * sen) / (precision + sen)
    MCC = (d * a - b * c) / (np.sqrt((d + b) * (d + c) * (a + b) * (a + c)))
    auc_score = roc_auc_score(y_true, y_pred_prob)
    brier_score = brier_score_loss(y_true, y_pred_prob)
    
    metrics = {
        "Accuracy": acc,
        "Error Rate": error_rate,
        "Sensitivity": sen,
        "Specificity": sep,
        "Precision": precision,
        "F1 Score": F1,
        "MCC": MCC,
        "AUC": auc_score,
        "Brier Score": brier_score
    }
    return metrics

metrics_test = calculate_metrics(cm_test, y_test, calibrated_test_probs)
metrics_train = calculate_metrics(cm_train, y_train, calibrated_train_probs)

print("Performance Metrics (Test):")
for key, value in metrics_test.items():
    print(f"{key}: {value:.4f}")

print("\nPerformance Metrics (Train):")
for key, value in metrics_train.items():
    print(f"{key}: {value:.4f}")

看看结果:

大同小异吧。

四、换个策略

参考那篇文章的策略:采用五折交叉验证来建立和评估模型,其中四折用于训练,一折用于评估,在训练集中,其中三折用于建立SVM模型,另一折采用Temperature Scaling概率校正,在训练集内部采用交叉验证对超参数进行调参。

代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV, KFold
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, roc_auc_score, brier_score_loss
from sklearn.calibration import calibration_curve

# 加载数据
dataset = pd.read_csv('8PSMjianmo.csv')
X = dataset.iloc[:, 1:20].values
Y = dataset.iloc[:, 0].values

# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=666)

# 标准化数据
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

# 定义五折交叉验证
kf = KFold(n_splits=5, shuffle=True, random_state=666)
calibrated_probs = []
true_labels = []

# Temperature Scaling
class TemperatureScaling:
    def __init__(self):
        self.temperature = 1.0

    def fit(self, logits, true_labels):
        from scipy.optimize import minimize

        def nll_loss(T):
            scaled_logits = logits / T
            probs = np.exp(scaled_logits) / np.sum(np.exp(scaled_logits), axis=1, keepdims=True)
            log_probs = np.log(probs[np.arange(len(true_labels)), true_labels])
            return -np.mean(log_probs)

        logits = np.log(np.column_stack([1 - logits, logits]))  # 转换成logits
        result = minimize(nll_loss, [1.0], bounds=[(0.1, 10.0)])
        self.temperature = result.x[0]

    def predict_proba(self, probs):
        logits = np.log(np.column_stack([1 - probs, probs]))  # 转换成logits
        scaled_logits = logits / self.temperature
        exp_scaled_logits = np.exp(scaled_logits)
        probs = exp_scaled_logits[:, 1] / np.sum(exp_scaled_logits, axis=1, keepdims=True)[:, 0]
        return probs

best_params = None  # 用于存储最优参数

for train_index, val_index in kf.split(X_train):
    X_train_fold, X_val_fold = X_train[train_index], X_train[val_index]
    y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]
    
    # 内部三折交叉验证用于超参数调优
    inner_kf = KFold(n_splits=3, shuffle=True, random_state=666)
    param_grid = {'C': [0.01, 0.1, 1, 10, 100], 'kernel': ['rbf']}
    svm = SVC(probability=True)
    clf = GridSearchCV(svm, param_grid, cv=inner_kf, scoring='roc_auc')
    clf.fit(X_train_fold, y_train_fold)
    best_params = clf.best_params_
    
    # 使用最佳参数训练SVM
    classifier = SVC(kernel=best_params['kernel'], C=best_params['C'], probability=True)
    classifier.fit(X_train_fold, y_train_fold)
    
    # 获取未校准的概率预测
    y_val_fold_probs = classifier.predict_proba(X_val_fold)[:, 1]
    
    # Temperature Scaling 校准
    temp_scaling = TemperatureScaling()
    temp_scaling.fit(y_val_fold_probs, y_val_fold)
    calibrated_val_fold_probs = temp_scaling.predict_proba(y_val_fold_probs)
    
    calibrated_probs.extend(calibrated_val_fold_probs)
    true_labels.extend(y_val_fold)

# 用于测试集的SVM模型训练和校准
classifier_final = SVC(kernel=best_params['kernel'], C=best_params['C'], probability=True)
classifier_final.fit(X_train, y_train)
y_test_probs = classifier_final.predict_proba(X_test)[:, 1]

# Temperature Scaling 校准
temp_scaling_final = TemperatureScaling()
temp_scaling_final.fit(y_test_probs, y_test)
calibrated_test_probs = temp_scaling_final.predict_proba(y_test_probs)

# 预测结果
y_train_pred = (np.array(calibrated_probs) >= 0.5).astype(int)
y_test_pred = (calibrated_test_probs >= 0.5).astype(int)

# 混淆矩阵
cm_test = confusion_matrix(y_test, y_test_pred)
cm_train = confusion_matrix(true_labels, y_train_pred)
print("Training Confusion Matrix:\n", cm_train)
print("Testing Confusion Matrix:\n", cm_test)

# 绘制混淆矩阵函数
def plot_confusion_matrix(cm, classes, title='Confusion Matrix'):
    plt.imshow(cm, cmap=plt.cm.Blues)
    indices = range(len(cm))
    plt.xticks(indices, classes)
    plt.yticks(indices, classes)
    plt.colorbar()
    plt.xlabel('Predicted')
    plt.ylabel('Actual')
    for first_index in range(len(cm)):
        for second_index in range(len(cm[first_index])):
            plt.text(second_index, first_index, cm[first_index][second_index])
    plt.title(title)
    plt.show()

# 绘制测试集混淆矩阵
plot_confusion_matrix(cm_test, list(set(y_test)), 'Confusion Matrix (Test)')

# 绘制训练集混淆矩阵
plot_confusion_matrix(cm_train, list(set(true_labels)), 'Confusion Matrix (Train)')

# 计算并打印性能参数
def calculate_metrics(cm, y_true, y_pred_prob):
    a = cm[0, 0]
    b = cm[0, 1]
    c = cm[1, 0]
    d = cm[1, 1]
    acc = (a + d) / (a + b + c + d)
    error_rate = 1 - acc
    sen = d / (d + c)
    sep = a / (a + b)
    precision = d / (b + d)
    F1 = (2 * precision * sen) / (precision + sen)
    MCC = (d * a - b * c) / (np.sqrt((d + b) * (d + c) * (a + b) * (a + c)))
    auc_score = roc_auc_score(y_true, y_pred_prob)
    brier_score = brier_score_loss(y_true, y_pred_prob)
    
    metrics = {
        "Accuracy": acc,
        "Error Rate": error_rate,
        "Sensitivity": sen,
        "Specificity": sep,
        "Precision": precision,
        "F1 Score": F1,
        "MCC": MCC,
        "AUC": auc_score,
        "Brier Score": brier_score
    }
    return metrics

metrics_test = calculate_metrics(cm_test, y_test, calibrated_test_probs)
metrics_train = calculate_metrics(cm_train, true_labels, np.array(calibrated_probs))

print("Performance Metrics (Test):")
for key, value in metrics_test.items():
    print(f"{key}: {value:.4f}")

print("\nPerformance Metrics (Train):")
for key, value in metrics_train.items():
    print(f"{key}: {value:.4f}")

# 绘制校准曲线
def plot_calibration_curve(y_true, probs, title='Calibration Curve'):
    fraction_of_positives, mean_predicted_value = calibration_curve(y_true, probs, n_bins=10)
    plt.plot(mean_predicted_value, fraction_of_positives, "s-", label="Temperature Scaling Calibration")
    plt.plot([0, 1], [0, 1], "k--")
    plt.xlabel('Mean predicted value')
    plt.ylabel('Fraction of positives')
    plt.title(title)
    plt.legend()
    plt.show()

# 绘制校准曲线
plot_calibration_curve(y_test, calibrated_test_probs, title='Calibration Curve (Test)')
plot_calibration_curve(true_labels, np.array(calibrated_probs), title='Calibration Curve (Train)')

输出:

效果一般般吧。

五、最后

各位可以去试一试在其他数据或者在其他机器学习分类模型中使用的效果。

数据不分享啦。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2196015.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于PHP猫咖私人影院系统【附源码】

效果如下: 系统首页界面 用户注册界面 包厢信息界面 零食信息界面 管理员登录界面 包厢预订界面 猫咪信息界面 研究背景 近年来,随着生活品质的提升和个性化消费需求的增长,猫咖和私人影院等新兴休闲娱乐方式逐渐受到年轻人的青睐。猫咖结合…

Github 2024-10-08 Python开源项目日报Top10

根据Github Trendings的统计,今日(2024-10-08统计)共有10个项目上榜。根据开发语言中项目的数量,汇总情况如下: 开发语言项目数量Python项目10JavaScript项目1系统设计指南 创建周期:2507 天开发语言:Python协议类型:OtherStar数量:241693 个Fork数量:42010 次关注人数…

毕设 深度学习图像搜索算法-图像搜索引擎(源码分享)

文章目录 0 简介1 前言2 图像检索介绍(1) 无监督图像检索(2) 有监督图像检索 3 图像检索步骤4 应用实例最后 0 简介 今天学长向大家分享一个毕业设计项目 毕业设计 深度学习图像搜索算法-图像搜索引擎(源码分享) 项目运行效果: 毕业设计 深度学习图像搜索算法-图…

【ESP32】ESP-IDF开发 | Timer硬件定时器+定时器闹钟例程

1. 简介 ESP32内置4个64-bit通用定时器。每个定时器包含一个16-bit预分频器和一个64-bit可自动重新加载向上/向下计数器。ESP32的定时器分为2组,每组2个。定时器具有闹钟功能,闹钟事件会引发重新加载和触发中断。 硬件定时器的时钟是由APB时钟提供的&…

sqli-labs靶场第三关less-3

sqli-labs靶场第三关less-3 1、确定注入点 http://192.168.128.3/sq/Less-3/?id1 http://192.168.128.3/sq/Less-3/?id2 有不同回显,判断可能存在注入, 2、判断注入类型 输入 http://192.168.128.3/sq/Less-3/?id1 and 11 http://192.168.128.3/sq/L…

Linus Torvalds 要求内核开发人员编写更好的 Git 合并提交信息

昨天在宣布 Linux 6.12-rc2 内核时,Linus Torvalds 要求内核维护者在提交信息方面做得更好。Torvalds 尤其希望内核维护者在描述拉取请求中的变更时,能更好地使用积极、命令式的语气。 Linux创建者在6.12-rc2 公告中解释道: 总之&#xff0c…

Arduino UNO R3自学笔记21 之 Arduino基础篇学习总结

注意:学习和写作过程中,部分资料搜集于互联网,如有侵权请联系删除。 前言:目前将Arduino的大多数基础内容学习了,做个总结。 1.编程语言 学习单片机,在面向单片机编程时,语言是最基础的&#…

Docker exec bash -c 使用详解与 Python 封装示例

简介:docker exec 是 Docker 的一个实用命令,允许在正在运行的容器中执行命令。通过 bash -c 选项,可以执行复杂的命令串。 历史攻略: go:远程执行系统命令 Python:subprocess模块 Python-subprocess激…

代数结构基础 - 离散数学系列(八)

目录 1. 群(Group) 群的定义 群的示例 2. 环(Ring) 环的定义 环的示例 3. 域(Field) 域的定义 域的示例 域在密码学中的应用 4. 实际应用场景 1. 对称性与加密 2. 误差检测与纠正 3. 数据编码…

Maven介绍和使用

Maven是apache旗下的一个开源项目,是一款用于管理和构建Java项目的工具,它基于项目对象模型(POM)的概念,通过一小段描述信息来管理项目的构建。 依赖管理:方便快捷的管理项目依赖的资源包,避免…

消峰限流有哪几种方式?

消峰限流的方式 业务视角 验证码回答问题环节 技术视角 消息队列异步化用户请求 限流,对流量进行层层过滤 nginx 层限流, 一是控制速率 limit_req 漏桶算法 limit_req_zone $binary_remote_addr zonemylimit:10m rate2r/s; server { location / { lim…

Java面试题——第八篇(JVM)

1. JVM中有哪些垃圾回收算法 Java中的垃圾回收算法有以下几种 1. 标记-清除算法 工作原理:首先遍历堆中的对象,标记出所有存活的对象,接着清除未标记的对象。优点:实现简单,能够处理堆中的所有对象缺点:…

vue3 antd-design-vue3 日期组件语言不显示中文问题

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言一、修改步骤 前言 随着ant-design-vue v3的推出,ant-design-vue官方把时间组件中的momentjs 替换成了dayjs,升级完后发现日期显示不正…

swift使用internvl2微调ocr文字检测(目标检测)

详细记录swfit微调interVL2-8B多模态大模型进行目标检测(附代码)-CSDN博客文章浏览阅读2k次,点赞45次,收藏14次。目标检测任务已经不是一个新鲜事了,但是多模态大模型作目标检测任务并不多见,本文详细记录swfit微调interVL2-8B多模态大模型进行目标检测的过程,旨在让更多…

Linux驱动开发(速记版)--单总线

第124章 单总线简介 124.1 单总线概述 单总线是一种串行通信协议,由Dallas Semiconductor开发,特点是用一根信号线实现双向数据传输和时钟同步,节省IO口且结构简单。 它广泛应用于传感器、存储器等。 硬件包括信号线、上拉电阻、设备和处理器…

代码随想录--字符串--重复的子字符串

题目 给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。 示例 1: 输入: "abab" 输出: True 解释: 可由子字符串 "ab" 重复两次构成。示例 2: 输入: "…

javaweb - 请求响应代码实现

简单参数 原始方式 在原始的web程序中,获取请求参数,需要通过HttpServletRequest对象手动获取。 RequestMapping("/simpleParam")public String simpleParam(HttpServletRequest request) {String name request.getParameter("name&…

基于Springboot+Vue的养老院管理系统的设计与实现 (含源码数据库)

1.开发环境 开发系统:Windows10/11 架构模式:MVC/前后端分离 JDK版本: Java JDK1.8 开发工具:IDEA 数据库版本: mysql5.7或8.0 数据库可视化工具: navicat 服务器: SpringBoot自带 apache tomcat 主要技术: Java,Springboot,mybatis,mysql,vue 2.视频演示地址 3.功能 这个系…

TMC2209堵转检测配置详细教程

按如下图将TMC2209和串口模块连接: 配置流程: 寄存器配置: 通用寄存器: 校验码见我之前文章:使用uart串口配置TMC2209模块_tmc2209 uart-CSDN博客 通用寄存器主要是配置第0和第1位,第1位要给1&#xff0…

python之详解列表

有序的可变容器,可以存储不同类型的元素。用中括号[]表示。 1、列表的查找访问 1.1、通过下标查找。 与字符串类似,列表也可通过 列表名[index] 的方式查找其中的元素。 索引的初始值为0,最大值为列表长度-1。 示例: list1 …