本题数据集是来自kaggle的Historical Sales and Active Inventory数据集,该数据集包含了历史销售记录数据和当前活跃库存的数据,在原始数据集中通过FileType特征进行区分(取值分别为Historical和Active),并且在当前活跃库存数据中不存在SoldFlag和SoldCount的值,所以无法用于训练或验证模型。我们去除了当前活跃库存数据,只保留了历史销售记录数据,该数据保存了过去6个月的销售信息。
该数据集包含14个特征,目标特征为SoldFlag(取值0代表无售出,取值1代表有售出),特征SoldCount表示售出的数目,可以用于训练回归模型,在这里不符合我们分类器训练的目的,因此我们将SoldCount列删除掉。
最终数据集包含75996个样本,我们将其中的80%作为训练集(正负类均衡),剩余的20%作为测试集。
包括目标特征在内的13个特征的详细描述如下:
列名 | 说明 | 类型 | 示例 |
---|---|---|---|
SoldFlag | 产品是否售出:1表示在过去的六个月中有售出;0表示无售出 | Float | 0 |
Order | 序号 | Int | 2 |
File_Type | 区分本条数据是历史销售记录还是当前的活跃库存,由于在原始数据集的基础上去除了当前活跃库存数据,故只含0值 | Int | 0 |
SKU_number | 每个产品的唯一标识符 | Int | 1737127 |
MarketingType | 市场销售类型(即不同的销售渠道):0或者1 | Int | 0 |
ReleaseNumber | 释放库存数目 | Int | 15 |
New_Release_Flag | 是否为新释放库存的货物:0代表否,1代表是 | Int | 1 |
StrengthFactor | 推广强度系数 | Float | 682743 |
PriceReg | 标签价格 | Float | 44.99 |
ReleaseYear | 释放库存年份 | Int | 2015 |
Itemcount | 数目 | Int | 8 |
LowUserPrice | 低端用户价格 | Float | 28.97 |
LowNetPrice | 低端社区价格 | Float | 31.84 |
dataset = pd.read_csv("E:\\tianchi\\salesanalysis1\\SalesKaggle3.csv")
dataset.columns=['Order','File_Type','SKU_number','SoldFlag','SoldCount','MarketingType','ReleaseNumber',\
'New_Release_Flag','StrengthFactor','PriceReg','ReleaseYear','ItemCount','LowUserPrice','LowUserPrice']
读入文件后选出file_type为历史销售记录的。
dataset=dataset[dataset.File_Type=='Historical']
dataset=dataset[['SoldFlag','Order','SKU_number','MarketingType','ReleaseNumber',\
'New_Release_Flag','StrengthFactor','PriceReg','ReleaseYear','ItemCount','LowUserPrice','LowUserPrice']]
用随机森林分类,注意这里要先把字母分类转换成01分类,另外还要注意正负样本平衡,二八比例分出测试机和训练集
from sklearn.ensemble import RandomForestClassifier
import numpy as np
import pandas as pd
dataset['MarketingType']=dataset.MarketingType.apply(lambda x: 0 if x=='D' else 1)
dataset_0=dataset[dataset.SoldFlag=='0']
dataset_1=dataset[dataset.SoldFlag=='1']
dataset_train=pd.concat([dataset_0.iloc[:int(len(dataset_0)*0.8)],dataset_1.iloc[:int(len(dataset_1)*0.8)]])
dataset_test=pd.concat([dataset_0.iloc[int(len(dataset_0)*0.8):],dataset_1.iloc[int(len(dataset_1)*0.8):]])
train_y = dataset_train[[0]].values.ravel()
train_x = dataset_train.iloc[:,1:].values
test_x = dataset_test.iloc[:,1:].values
test_y=dataset_test[[0]].values.ravel()
# create and train the random forest
# multi-core CPUs can use: rf = RandomForestClassifier(n_estimators=100, n_jobs=2)
rf = RandomForestClassifier(n_estimators=100)
rf.fit(train_x, train_y)
pred = rf.predict(test_x)
print rf.score(test_x,test_y)