【天池学习赛】数据分析达人赛3:汽车产品聚类分析

赛题背景

赛题以竞品分析为背景,通过数据的聚类,为汽车提供聚类分类。对于指定的车型,可以通过聚类分析找到其竞品车型。通过这道赛题,鼓励学习者利用车型数据,进行车型画像的分析,为产品的定位,竞品分析提供数据决策。

赛题数据

数据源:car_price.csv,数据包括了205款车的26个字段

1 Car_ID Unique id of each observation (Interger) 唯一id
2 Symboling Its assigned insurance risk rating, A value of +3 indicates that the auto is risky, -3 that it is probably pretty safe.(Categorical) 风险等级(值越大风险越高)
3 CarName Name of car company (Categorical) 车型(汽车所属公司信息)
4 fueltype Car fuel type i.e gas or diesel (Categorical) 汽车燃料类型(汽油 or 柴油)
5 aspiration Aspiration used in a car (Categorical) 吸气装置类型
6 doornumber Number of doors in a car (Categorical) 车门数量
7 carbody body of car (Categorical) 车身类型
8 drivewheel type of drive wheel (Categorical) 驱动轮类型
9 enginelocation Location of car engine (Categorical) 汽车发动机的位置
10 wheelbase Weelbase of car (Numeric) 汽车轴距
11 carlength Length of car (Numeric) 车长
12 carwidth Width of car (Numeric) 车宽
13 carheight height of car (Numeric) 车高
14 curbweight The weight of a car without occupants or baggage. (Numeric) 没有乘客或行李的汽车的重量
15 enginetype Type of engine. (Categorical) 发动机类型
16 cylindernumber cylinder placed in the car (Categorical) (发动机的)气缸数量
17 enginesize Size of car (Numeric) 发送机大小
18 fuelsystem Fuel system of car (Categorical) 汽车燃油系统
19 boreratio Boreratio of car (Numeric) 钻孔率
20 stroke Stroke or volume inside the engine (Numeric) 发动机内的冲程或容积
21 compressionratio compression ratio of car (Numeric) 压缩率
22 horsepower Horsepower (Numeric) 马力(功率单位)
23 peakrpm car peak rpm (Numeric) 最大转速(revolutions per minute 每分钟多少转)
24 citympg Mileage in city (Numeric) 城市里程
25 highwaympg Mileage on highway (Numeric) 高速里程
26 price(Dependent variable) Price of car (Numeric) 价格

赛题任务

选手需要对该汽车数据进行聚类分析,并找到vokswagen汽车的相应竞品。要求选手在天池实验室中用notebook完成以上任务,并分享到比赛论坛。
(聚类分析是常用的数据分析方法之一,不仅可以帮助我们对用户进行分组,还可以帮我们对产品进行分组(比如竞品分析) 这里的聚类个数选手可以根据数据集的特点自己指定,并说明聚类的依据)

代码展示

以下是jupyter notebook代码:

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
import os
from sklearn.preprocessing import LabelEncoder


# 1.读取数据
path = '/Users/weiyi/Applications/jupyter_work/ml/datasets/'
car_data = pd.read_csv(path+'car_analysis/car_price.csv')
car_data.info()

# 2.数据探索
# 判断是否有重复值
car_data.duplicated().sum()
# 查看数据
car_data['CarName'].value_counts().sort_index()
# 复制原始数据
data = car_data.copy()

# 3.特征工程
# 处理字段【CarName】,只保留品牌,并处理品牌中的错误信息
data['CarName']=[i.split(' ')[0] for i in data['CarName']]
# 挑出错误信息,并修改
namedist={'maxda':'mazda','Nissan':'nissan','porcshce':'porsche','toyouta':'toyota','vokswagen':'volkswagen','vw':'volkswagen'}
data['CarName']=data['CarName'].replace(namedist)

# 剔除表征车型的特征
data = data.drop(['car_ID','CarName'], axis=1)


# 将非数值类型的列,编码为数字
# # 定义函数:将字符串列简单编码为数字
# def strToNum(series):
#     key=series.unique()
#     value=[i for i in range(len(key))]
#     dict1={i:j for i,j in zip(key,value)}
#     series=[dict1[i] for i in series] 
#     return series
# # 提取数据类型为字符串的列,并编码为数字
# strCol=data.dtypes[data.dtypes=='object'].index
# for i in strCol:
#     data[i]=strToNum(data[i])
category_fea = list(data.select_dtypes(include=['object']).columns)
for column in category_fea:
    data[column] = LabelEncoder().fit_transform(data[column])

# 数据归一化
from sklearn.preprocessing import MinMaxScaler as MMS
mms=MMS()
data = mms.fit_transform(data) 

# 4.模型训练
# 利用轮廓系数确定最优K值,最终确定为7
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score  # 轮廓系数
x=[]
y=[]
for i in range(2,20):
    clf=KMeans(n_clusters=i,random_state=2021)
    clf=clf.fit(data)
    num=silhouette_score(data, clf.labels_)  # 返回所有样本的平均轮廓系数
    x.append(i)
    y.append(num)
    
# 5.画图
# sns.lineplot(x=x,y=y)
plt.xlabel('K')
plt.ylabel('silhouette_score')
plt.plot(x,y,'o-')
plt.show()  # 如图1

# 6.通过选定的最优K值,创建模型并给原始数据贴标签
clf=KMeans(n_clusters=7)
clf=clf.fit(data)
car_data['label']=clf.labels_

# 展示分类完的数据
car_data.head(5)

# 7.分析:找到volkswagen各车型的相应竞品

# 7.1 找出volkswagen对应的所有车型及其分类
# car_data[car_data.CarName.str.contains('volkswagen')][['CarName','label']]
# 'volkswagen 1131 deluxe sedan'.find('volkswagen')  返回0
volkswagen_data=car_data[[i.find('volkswagen')==0 for i in car_data['CarName']]][['CarName','label']]
volkswagen_data   # 如图2

# 7.2 对应竞品明细
vol_dict=dict(zip(volkswagen_data['CarName'],volkswagen_data['label']))
for k in vol_dict.keys():
    car_list=car_data[car_data['label']==vol_dict.get(k)]['CarName'].unique().tolist()
    car_list.remove(k)
    print('车型 '+k+'对应的竞品有如下'+str(len(car_list))+'种:')
    print(car_list)
    print()   # 如图3

图1: 

【天池学习赛】数据分析达人赛3:汽车产品聚类分析_第1张图片

图2:

【天池学习赛】数据分析达人赛3:汽车产品聚类分析_第2张图片 

图3:

 

 

 

 

你可能感兴趣的:(机器学习-大赛,机器学习,python,聚类算法)