把图片生成二维码的软件,什么优化,案例分析网站,wordpress打电话插件一些自存的机器学习函数和详细方法记录#xff0c;欢迎指错。 前言#xff1a;读取数据方法
import pandas as pd
import pandas as pddf pd.read_csv(数据集.csv, header0)
# header是从哪一行开始读起#xff0c;一般是0#xff0c;也可以取infer
一、数据处理#…一些自存的机器学习函数和详细方法记录欢迎指错。 前言读取数据方法
import pandas as pd
import pandas as pddf pd.read_csv(数据集.csv, header0)
# header是从哪一行开始读起一般是0也可以取infer
一、数据处理基本
数据编码
from sklearn.preprocessing import LabelEncoder
用于为非数值数据编码
使用例子
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()替换
缺失值处理
删除缺失值函数pandas库里的dropna
df[year] df[year].replace(N.V., np.nan)
df df.dropna(howany)
#any表示只要有空缺就删除还可选all
也可以采用平均值/中位数/knn填补法
from sklearn.impute import KNNImputer # sklearn自带knn填补模型
# 平均值填补
pj np.nanmean(X_train, axis0)
for i in range(X_train.shape[0]):for j in range(X_train.shape[1]):if math.isnan(X_train[i][j]):X_train[i][j] pj[j]
for i in range(X_test.shape[0]):for j in range(X_test.shape[1]):if math.isnan(X_test[i][j]):X_test[i][j] pj[j]# 中位数填补
zw np.nanmedian(X_train, axis0)
print(zw)
for i in range(X_train.shape[0]):for j in range(X_train.shape[1]):if math.isnan(X_train[i][j]):X_train[i][j] zw[j]
# KNN填补
imputer KNNImputer(n_neighbors5)
X_train pd.DataFrame(imputer.fit_transform(X_train))
数据类型转换
df[year] df[year].astype(np.int64)
#将year这一列转化为int数据类型
文本类型转数值
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizerver CountVectorizer()
X ver.fit_transform(df[text]).toarray()
二、标准化特征
from sklearn.preprocessing import StandardScaler
#用于标准化特征使其均值为0方差为1。
from imblearn.over_sampling import RandomOverSampler
#用于处理类别不平衡问题长尾分布随机增加少数类样本的数量。
下面是数据挖掘课一个处理长尾分布的实验中对长尾分布数据预处理的一部分
from sklearn.preprocessing import StandardScaler
from imblearn.over_sampling import RandomOverSampler
import pandas as pdros RandomOverSampler(sampling_strategyminority)
# 初始化RandomOverSamplersamping_strategyminority表示要增加少数类样本的数量
X, y ros.fit_resample(X, y)
# 执行RandomOverSampler平衡特征X和标签yscaler StandardScaler()
# 初始化StandardScaler
X_standardized scaler.fit_transform(X)
# 使用StandardScaler对X进行拟合并转换返回标准化后的数据X_standardizedX_std pd.DataFrame(X_standardized, columns X.columns)
#使用pandas.DataFrame将标准化后的数据转换为数据框形式并保留原始的列名 三、train_test_split划分训练集测试集
from sklearn.model_selection import train_test_split
用于划分数据
from sklearn.model_selection import train_test_splitX df.drop(region,axis1)
# 将读取的处理好的数据去除特征行存入X中
y df[region]
# 将特征行分开存入y中X_train, X_test, y_train, y_test train_test_split(X_std, y, test_size0.6, random_state42)
#其中test_size表示划分比例如值为0.6表示训练集占0.6
#random_state表示随机数取的随机数相同那么划分也会一模一样 四、一些机器学习模型分类
支持向量机SCVfrom sklearn.svm import SVC
K近邻from sklearn.neighbors import KNeighborsClassifier
随机森林from sklearn.ensemble import RandomForestClassifier
多层感知机神经网络MLPfrom sklearn.neural_network import MLPClassifier
高斯朴素贝叶斯from sklearn.naive_bayes import GaussianNB
决策树from sklearn.tree import DecisionTreeClassifier
梯度提升树from xgboost import XGBClassifier
使用实例都套这个模板就行
from sklearn.ensemble import RandomForestClassifiermodel RandomForestClassifier()model.fit(X_train, y_train)y_pred model.predict(X_predict)
在长尾分布实验中我学到了一个对数据重加权的方法使用class_weight参数
from sklearn.utils.class_weight import compute_class_weighty_uni y[winery].unique().ravel()classes np.array(y_uni)
class_weights compute_class_weight(balanced, classesclasses, yy)
class_weight_dict {0: class_weights[0], 1: class_weights[1]}model RandomForestClassifier(class_weightclass_weight_dict) 五、一些机器学习模型回归
决策树from sklearn.tree import DecisionTreeRegressor
别的把上面的Classifier改成Regressor应该就行了 六、准确度计算
from sklearn.metrics import accuracy_score
计算准确度前一个参数是实际结果后一个参数是预测结果。
from sklearn.metrics import accuracy_scoreACC accuracy_score(y_test, y_pred) 七、画图方法
import matplotlib.pyplot as plt
比如要画出样本特征柱状图
import matplotlib.pyplot as pltplt.figure(figsize(15,5)) # 图的大小plt.subplot(121) # 分成两个图121分别是三个参数表示有1行表2列表共两个表现在取第1行表
df[type].hist() # 生成‘type’的柱状图
plt.subplot(122) # 现在取第二行表
df[region].hist() # 生成‘region’的柱状图