(自用)机器学习python代码相关笔记

一些自存的机器学习函数和详细方法记录,欢迎指错。

前言:读取数据方法

import pandas as pd

python 复制代码
import pandas as pd

df = pd.read_csv('数据集.csv', header=0)
# header是从哪一行开始读起,一般是0,也可以取'infer'

一、LabelEncoder 编码

from sklearn.preprocessing import LabelEncoder

用于为非数值数据编码

使用例子:

python 复制代码
from sklearn.preprocessing import LabelEncoder #用于将分类变量转换为数字形式。
#对非数值类型数据编码
for i in df.columns: #遍历df中每一列
    if df[i].dtypes == "object": #若该列为非数值数据,则对其编码
        lable = LabelEncoder() #创建新的LabelEncoder()
        lable = lable.fit(df[i]) #训练LabelEncoder(),使其适用于数据
        df[i] = lable.transform(df[i].astype(str)) #将原数据用训练好的LabelEncoder()替换

二、标准化特征

from sklearn.preprocessing import StandardScaler

#用于标准化特征,使其均值为0,方差为1。

from imblearn.over_sampling import RandomOverSampler

#用于处理类别不平衡问题(长尾分布),随机增加少数类样本的数量。

下面是数据挖掘课一个处理长尾分布的实验中对长尾分布数据预处理的一部分

python 复制代码
from sklearn.preprocessing import StandardScaler
from imblearn.over_sampling import RandomOverSampler 
import pandas as pd

ros = RandomOverSampler(sampling_strategy='minority')
# 初始化RandomOverSampler,samping_strategy='minority'表示要增加少数类样本的数量
X, y = ros.fit_resample(X, y)
# 执行RandomOverSampler,平衡特征X和标签y

scaler = StandardScaler()
# 初始化StandardScaler
X_standardized = scaler.fit_transform(X)
# 使用StandardScaler对X进行拟合并转换,返回标准化后的数据X_standardized

X_std = pd.DataFrame(X_standardized, columns = X.columns)
#使用pandas.DataFrame将标准化后的数据转换为数据框形式,并保留原始的列名

三、train_test_split划分训练集测试集

from sklearn.model_selection import train_test_split

用于划分数据

python 复制代码
from sklearn.model_selection import train_test_split

X = df.drop("region",axis=1)
# 将读取的处理好的数据去除特征行存入X中
y = df['region']
# 将特征行分开存入y中

X_train, X_test, y_train, y_test = train_test_split(X_std, y, test_size=0.6, random_state=42)
#其中test_size表示划分比例,如值为0.6表示训练集占0.6
#random_state表示随机数,取的随机数相同那么划分也会一模一样

四、一些机器学习模型(分类)

支持向量机(SCV):from sklearn.svm import SVC

K近邻:from sklearn.neighbors import KNeighborsClassifier

随机森林:from sklearn.ensemble import RandomForestClassifier

多层感知机(神经网络)(MLP):from sklearn.neural_network import MLPClassifier

高斯朴素贝叶斯:from sklearn.naive_bayes import GaussianNB

决策树:from sklearn.tree import DecisionTreeClassifier

梯度提升树:from xgboost import XGBClassifier

使用实例(都套这个模板就行):

python 复制代码
from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier()

model.fit(X_train, y_train)

y_pred = model.predict(X_predict)

五、一些机器学习模型(回归)

决策树:from sklearn.tree import DecisionTreeRegressor

(别的把上面的Classifier改成Regressor应该就行了)

六、准确度计算

from sklearn.metrics import accuracy_score

计算准确度,前一个参数是实际结果,后一个参数是预测结果。

python 复制代码
from sklearn.metrics import accuracy_score

ACC = accuracy_score(y_test, y_pred)

七、画图方法

import matplotlib.pyplot as plt

比如要画出样本特征柱状图:

python 复制代码
import matplotlib.pyplot as plt

plt.figure(figsize=(15,5)) # 图的大小

plt.subplot(121) # 分成两个图,121分别是三个参数,表示有1行表2列表(共两个表),现在取第1行表
df['type'].hist() # 生成'type'的柱状图
plt.subplot(122) # 现在取第二行表
df['region'].hist() # 生成'region'的柱状图
相关推荐
HERR_QQ24 分钟前
强化学习的数学原理 学习笔记
人工智能·笔记·学习·自动驾驶
z小猫不吃鱼2 小时前
03 Optimal Brain Surgeon 详解:Hessian 剪枝为什么有效?
算法·机器学习·剪枝
weixin_400005603 小时前
RL-frenet-trajectory-planning-in-CARLA
人工智能·深度学习·算法·机器学习·自动驾驶
大鱼>4 小时前
超参数调优进阶:Optuna/Bayesian/Early Stopping
人工智能·学习·机器学习·聚类
z小猫不吃鱼4 小时前
02 Optimal Brain Damage 详解:二阶信息剪枝的起点
算法·机器学习·剪枝
m0_626535204 小时前
近似attention
人工智能·算法·机器学习
liuyicenysabel4 小时前
多服务上线日记二:
服务器·笔记·学习
大鱼>5 小时前
模型可解释性:特征重要性/SHAP/LIME
人工智能·python·机器学习·lstm
霖大侠5 小时前
Decoupled and Reusable Adaptation for Efficient Cross-Modal Transfer
人工智能·深度学习·算法·机器学习·transformer
辰海Coding5 小时前
MiniSpring框架学习笔记-动态代理:如何在运行时插入逻辑?
java·笔记·学习·spring·动态代理