%matplotlib inline
import pandas as pd
import numpy as np
import math
import re
import time
import matplotlib.pyplot as plt # Matlab-style plotting
import seaborn as sns
train = pd.read_csv('../data/round1_ijcai_18_train_20180301.txt', delimiter=' ', header=0, low_memory=False) #(478138, 27)
df = train.copy()
df.info()
df.describe()
df.head(5).T
df.shape
df.dtypes
df['user_age_level'].unique()
df['user_age_level'].value_counts(dropna=False) #添加dropna=False,才会加入统计nan值
df['user_age_level'].hist(bins=20, figsize=(12, 6))
#pandas的DataFrame结构自带绘图功能
df['user_age_level'].value_counts().plot(kind='pie', legend=True, title='user_age_level', rot=90)
df.isnull().sum(axis=0) #统计缺失值
df['user_age_level'].fillna(df['user_age_level'].mode().iloc[0], inplace=True)
#标准化
from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
scaler = MinMaxScaler(feature_range=(0,1)) #压缩到某个区间
scaler = StandardScaler() # 均值为0, 方差为1
sclaer = Normalizer(norm='l2') # l1, l2正则
s = pd.Series([2, 5, 3, 200, 11, 7])
s.rank() #排序后值所对应的index
0 1.0
1 3.0
2 2.0
3 6.0
4 5.0
5 4.0
dtype: float64
#编码
#哑编码
pd.get_dummies(df['user_gender_id'], prefix='user_gender_id_', dummy_na=True)
pd.get_dummies(df, columns=['user_gender_id', 'user_age_level'], dummy_na=True)#对指定列进行哑编码
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from scipy import sparse
LabelEncoder().fit_transform(df['user_gender_id']) #有缺失值时,会对每个缺失值生成一个编码。所以使用LabelEncoder时,要先处理好缺失值
OneHotEncoder().fit_transform(df['user_gender_id']) #有缺失值时,直接报错
==========================================================================
#文档-词频矩阵
#https://datartisan.gitbooks.io/begining-text-mining-with-python/content/%E7%AC%AC5%E7%AB%A0%20%E6%96%87%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%8C%96%E5%A4%84%E7%90%86/5.2%20%E8%AF%8D%E9%A2%91-%E9%80%86%E5%90%91%E6%96%87%E6%A1%A3%E9%A2%91%E7%8E%87.html
from sklearn.feature_extraction.text import CountVectorizer
texts=["dog cat fish","dog cat cat","fish bird", 'bird']
cv = CountVectorizer()
cv_fit=cv.fit_transform(texts)
print(cv.get_feature_names())
print(cv_fit.toarray())
#['bird', 'cat', 'dog', 'fish']
#[[0 1 1 1]
# [0 2 1 0]
# [1 0 0 1]
# [1 0 0 0]]
print(cv_fit.toarray().sum(axis=0))
#[2 3 2 2]
============================
# 将字典转化为文档-词频矩阵
from sklearn.feature_extraction import DictVectorizer
tests = [{'text': 2, 'mining': 3, 'analysis': 1},{'mining':11, 'nami':2} ]
DictVectorizer().fit_transform(tests).toarray()
array([[ 1., 3., 0., 2.],
[ 0., 11., 2., 0.]])
#if-tdf
from sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
corpus=['我是 要 成为 海贼王 的 男人', '我是 路飞 的 伙伴', '天气 成为 制约 因素']#第四类文本的切词结果
#第一种方法
vectorizer=CountVectorizer()#该类会将文本中的词语转换为词频矩阵,矩阵元素a[i][j] 表示j词在i类文本下的词频
transformer=TfidfTransformer()#该类会统计每个词语的tf-idf权值
tfidf=transformer.fit_transform(vectorizer.fit_transform(corpus))#第一个fit_transform是计算tf-idf,第二个fit_transform是将文本转为词频矩阵
word=vectorizer.get_feature_names()#获取词袋模型中的所有词语
weight=tfidf.toarray()#将tf-idf矩阵抽取出来,元素a[i][j]表示j词在i类文本中的tf-idf权重
for i in range(len(weight)):#打印每类文本的tf-idf词语权重,第一个for遍历所有文本,第二个for便利某一类文本下的词语权重
print(u"-------这里输出第",i,u"类文本的词语tf-idf权重------")
for j in range(len(word)):
print(word[j],weight[i][j])
#第二种方法
TfidfVectorizer().fit_transform(corpus).toarray()
sklearn一些常用方法
最新推荐文章于 2024-01-07 15:04:28 发布