数据处理trick

本文介绍了一种结合sklearn库处理连续特征和离散特征的方法,通过LabelEncoder和OneHotEncoder实现特征编码,以及如何使用CountVectorizer进行文本特征提取。此外,还提供了逐行扫描数据并删除异常值的策略,包括检查缺失值、时间范围、气象参数等条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下都是从一些博客收集的数据处理trick,方便日后使用

1.基于sklearn同时处理连续特征和离散特征

核心思路:

先用LabelEncoder对离散特征编码,因为onehotencoder只能处理数值

然后使用OneHotEncoder编码,生成稀疏表示的特征

再使用sparse.hstack连接连续特征和稀疏特征

为什么不使用pd.get_dummy呢,因为这样是直接生成的稠密矩阵,内存开销太大、

from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from scipy import sparse

for feature in cate_feature + con_feature:
    data[feature] = LabelEncoder().fit_transform(data[feature].values)
enc = OneHotEncoder()
train_x=train[numeric_feature]
test_x=test[numeric_feature]
for feature in cate_feature+con_feature:
    enc.fit(data[feature].values.reshape(-1, 1))
    train_a=enc.transform(train[feature].values.reshape(-1, 1))
    test_a = enc.transform(test[feature].values.reshape(-1, 1))
    train_x= sparse.hstack((train_x, train_a))
    test_x = sparse.hstack((test_x, test_a))

# 文本one hot
from sklearn.feature_extraction.text import CountVectorizer
# 每行用空格join起来
data['corpus']=data['corpus'].apply(lambda x:' '.join(x.split(';')))
#如果corpus里面是数字,可能会提示empty vocabulary; perhaps the documents only contain stop words
#改成这样就行了CountVectorizer(token_pattern='(?u)\\b\\w+\\b')
property_feature = CountVectorizer().fit_transform(data['corpus'])
train_x=sparse.hstack((train_property_feature,train_x))

2.逐行扫描数据,只要此行存在一个异常值。对此行进行删除

这里,any([])函数如若里面一个为真,则返回True.即逐行扫描,发现‘missing’存在此行中,或此行时间不落在0-24之间,或气压rpessure大于1500,或风向不落在0-360度之间,或风速大于10级,或precipitation降雨量大于10,则此行数据为异常数据进行删除。

for i in range(data.index.max()):
	if any([
		'missing' in data.loc[i,:].values,
		data.loc[i,'hour'] not in range(25),
		data.loc[i,'pressure']>1500,
		data.loc[i,'wind_direction']<0 or data.loc[i,'wind_direction']>360,
		data.loc[i,'wind_speed']>10,
		data.loc[i,'precipitation']>10
		]):
 
		print('已删除存在异常值 %s 行数据'%i)
		data.drop([i],inplace=True)

3.统计极差、变异系数和四位数间距


print('\n-----------------------极差变异系数四分位间距-------------------------')
statistics = data.describe() #保存基本统计量
statistics.loc['range'] = statistics.loc['max']-statistics.loc['min'] #极差
statistics.loc['var'] = statistics.loc['std']/statistics.loc['mean'] #变异系数
statistics.loc['dis'] = statistics.loc['75%']-statistics.loc['25%'] #四分位数间距
# print(statistics)

参考
[1] https://blog.youkuaiyun.com/Bryan__/article/details/79911768?utm_source=blogxgwz2
[2] https://blog.youkuaiyun.com/qton_csdn/article/details/70475286

### Python 数据增强技巧 数据增强是一种用于扩展训练集的技术,在机器学习和深度学习领域广泛应用。对于图像数据,常见的增强方式包括旋转、翻转、缩放等;而对于其他类型的数据,则可能涉及更复杂的方法。 #### 图像数据增强示例 使用 `imgaug` 库可以方便地实现多种图像变换: ```python import imgaug.augmenters as iaa from PIL import Image import numpy as np # 定义一系列增强操作 seq = iaa.Sequential([ iaa.Fliplr(0.5), # 随机水平翻转 iaa.Crop(percent=(0, 0.1)), # 随机裁剪 iaa.Sometimes( 0.5, iaa.GaussianBlur(sigma=(0, 0.5)) ), iaa.LinearContrast((0.75, 1.5)), ]) image = np.array(Image.open('example.jpg')) # 加载图片 images_aug = seq(images=[image] * 8) # 对同一张图片应用不同参数的增强效果 ``` 此段代码展示了如何利用随机化的方式对输入图像施加各种几何与颜色空间的变化[^1]。 #### 文本数据增强实例 针对自然语言处理任务中的文本序列,可以通过同义词替换来增加样本多样性: ```python from nltk.corpus import wordnet import random def synonym_replacement(words, n=1): new_words = words.copy() for _ in range(n): rand_idx = random.randint(0, len(new_words)-1) synonyms = [] for syn in wordnet.synsets(new_words[rand_idx]): for lemma in syn.lemmas(): synonyms.append(lemma.name()) if len(synonyms)>0: replacement_word=random.choice(synonyms) new_words[rand_idx]=replacement_word sentence=" ".join(new_words) return sentence text='The quick brown fox jumps over the lazy dog' words=text.split() print(synonym_replacement(words,n=2)) ``` 上述脚本实现了基于WordNet库查找并替换单词同义词的功能,从而达到扩充语料的目的[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值