当前位置:网站首页>机器学习(一)数据的预处理
机器学习(一)数据的预处理
2022-08-11 07:38:00 【ViperL1】
一、导入标准库(Python)
import numpy as np --数据分析库
import matplotlib.pyplot as plt --绘图库
import pandas as pd --数据集导入
二、导入数据集
1.读取文件
dataset = pd.read_csv('Data.csv') --读取数据集合(csv文件)
2.创建矩阵
x = dataset.iloc[:,:-1].values --自变量
--iloc表示取数据(行,列) 所有行和除最后一列外的数据
y = dataset.iloc[:,:3].values --因变量
--[]内数据的表示
--[x:y,a] x->起始位置,y->终止位置,a->需要处理的数据的位置
三、处理缺失数据
这里使用的策略是使用当列的平均值代替缺失数据,此外常用的还有中位数,众数等方法
from sklearn.preprocessing import Imputer --导入缺失数据处理类
imputer = Imputer(missing_values='NaN',strategy = 'mean',axis=0)
--参数含义:缺失数据,采用策略,作用对象为行/列
imputer = imputer.fit(x[:,1:3]) --数据拟合
x[:,1:3] = imputer.transform(x[:,1:3])
四、分类数据
将不同的类别转换为有意义的数值(例如利用bool、string)
from sklearn.preprocessing import LabelEncoder --标签编码器,转义为数字
labelencoder_X = LabelEncoder(); --创建对象
x[:,0] = labelencoder_X.fit_transform(x[:,0]) --拟合+转换
虚拟编码:将标签转变为编码,使其没有顺序区别
--需要和上面的转换代码混合使用
from sklearn.preprocessing import OneHotEncoder --引入工具
onehotencoder = OneHotEncoder(categorical_features = [0]) --处理数据集的列号
x = onehotencoder.fit_transform(x).toarry()
五、训练集和测试集
from sklearn.model_selection import train_test_split --引入工具
x_train,x_test,y_trian,y_test = train_test_split(x,y,test_size=0.2,random_state = 0)
--参数:需要划分的数据,测试集比重(一般为0.2-0.25),训练集比重(一般不单独赋值),随机数生成方式
--训练集的自变量、因变量 / 测试集的自变量、因变量
六、特征缩放
①用于解决欧氏距离遍历数量级差距过大的问题(若差距过大则会出现由数量关系中的某一组数据主导关系的存在)
欧氏距离:(斜线公式)
②加速决策树的收敛
如何进行特征缩放
1.标准化
mean--平均值 StanderDeviation--标准方差
x会得到一个平均值为0,标准方差为1的分布
2.正常化
0-1区间内的等比缩小
3.进行缩放
from sklearn.preprocessing import standerScaler --导入工具
sc_x = standardScaler() --类对象
x_train = sc_x.fit_transform(x_train) --拟合+转换
x_test = sc_x.transform(x_test) --已经拟合过了,直接转换
七、数据预处理标准模板
一般的数据预处理很少用到缺失数据、分类数据,一般使用以下几步
①读取数据
②测试集和训练集分割
③特征缩放(部分情况需要使用)
边栏推荐
- 1081 Check Password (15 points)
- Project 1 - PM2.5 Forecast
- 1056 Sum of Combinations (15 points)
- 3.2 - classification - Logistic regression
- redis操作
- 1046 划拳 (15 分)
- Item 2 - Annual Income Judgment
- 囍楽云任务源码
- Distributed Lock-Redission - Cache Consistency Solution
- Find the latest staff salary and the last staff salary changes
猜你喜欢
随机推荐
Service的两种启动方式与区别
9、Neural Sparse Voxel Fields
tf.reduce_mean()与tf.reduce_sum()
少年成就黑客,需要这些技能
1046 划拳 (15 分)
1056 组合数的和 (15 分)
1.1-Regression
Four startup modes of Activity
TF中使用softmax函数;
tf.reduce_mean() and tf.reduce_sum()
The growth path of a 40W test engineer with an annual salary, which stage are you in?
【TA-霜狼_may-《百人计划》】图形3.7.2 command buffer简
XXL-JOB 分布式任务调度中心搭建
go 操作MySQL之mysql包
redis operation
抽象类和接口
3.2-分类-Logistic回归
1056 Sum of Combinations (15 points)
Write a resume like this, easy to get the interviewer
leetcode:69. x 的平方根