红酒数据集分析(纯数字数据集)

红酒数据集数据分析

  • 导入相关包
  • 导入数据及总览
  • 单变量分析
    • 处理红酒的酸度特征
    • 处理甜度特征
  • 双变量分析
    • 红酒品质vs.其他特征
    • 密度vs.酒精浓度
    • 酸性物质含量vs.pH
  • 多变量分析
    • pH,非挥发性酸,和柠檬酸

目标:了解影响红酒品质的主要理化因素

导入相关包

#import相关的库
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="darkgrid") #这是seaborn默认的风格
pd.set_option('precision',3) #设置数据精度

导入数据及总览


df = pd.read_csv("datasets/wine/winequality-red.csv",sep = ';')
df.head()
fixed acidity	volatile acidity	citric acid	residual sugar	chlorides	free sulfur dioxide	total sulfur dioxide	density	pH	sulphates	alcohol	quality
0	7.4	0.70	0.00	1.9	0.076	11.0	34.0	0.998	3.51	0.56	9.4	5
1	7.8	0.88	0.00	2.6	0.098	25.0	67.0	0.997	3.20	0.68	9.8	5
2	7.8	0.76	0.04	2.3	0.092	15.0	54.0	0.997	3.26	0.65	9.8	5
3	11.20.28	0.56	1.9	0.075	17.0	60.0	0.998	3.16	0.58	9.8	6
4	7.4	0.70	0.00	1.9	0.076	11.0	34.0	0.998	3.51	0.56	9.4	5

各指标介绍
-fixed acidity	         固定酸度
-volatile acidity	     挥发性酸度
-citric acid	         柠檬酸
-residual sugar	         残留糖
-chlorides	             氯化物
-free sulfur dioxide	 游离二氧化硫
-total sulfur dioxide	 总二氧化硫
-density	             密度
-pH	                     酸碱度
-sulphates	             硫酸盐
-alcohol	             酒精度
-quality                 品质

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1599 entries, 0 to 1598
Data columns (total 12 columns):
 #   Column                Non-Null Count  Dtype  
---  ------                --------------  -----  
 0   fixed acidity         1599 non-null   float64
 1   volatile acidity      1599 non-null   float64
 2   citric acid           1599 non-null   float64
 3   residual sugar        1599 non-null   float64
 4   chlorides             1599 non-null   float64
 5   free sulfur dioxide   1599 non-null   float64
 6   total sulfur dioxide  1599 non-null   float64
 7   density               1599 non-null   float64
 8   pH                    1599 non-null   float64
 9   sulphates             1599 non-null   float64
 10  alcohol               1599 non-null   float64
 11  quality               1599 non-null   int64  
dtypes: float64(11), int64(1)
memory usage: 150.0 KB
查看红酒品质分布
df["quality"].value_counts()

5    681
6    638
7    199
4     53
8     18
3     10
Name: quality, dtype: int64
查看下与品质相关度最高的特征
corr_matrix = df.corr()
corr_matrix["quality"].sort_values(ascending= False)

quality                 1.000
alcohol                 0.476
sulphates               0.251
citric acid             0.226
fixed acidity           0.124
residual sugar          0.014
free sulfur dioxide    -0.051
pH                     -0.058
chlorides              -0.129
density                -0.175
total sulfur dioxide   -0.185
volatile acidity       -0.391
Name: quality, dtype: float64

单变量分析

首先简单查看每个变量分布情况

colnm = df.columns.tolist()#把列名转换为列表
fig = plt.figure(figsize = (10, 6))

for i in range(12):
    plt.subplot(3,4,i+1)
    sns.boxplot(df[colnm[i]], orient="v", width = 0.5, color = color[0])#箱图显示
    plt.ylabel(colnm[i],fontsize = 12)#设置y轴名称

plt.tight_layout()#自动调整子图参数,使之填充整个图像区域
print('\nFigure 1: Univariate Boxplots')

红酒数据集分析(纯数字数据集)_第1张图片

colnm = df.columns.tolist()# 将每一列放入列表
plt.figure(figsize = (10, 8)) #生成画布

for i in range(12):
    plt.subplot(4,3,i+1)
    df[colnm[i]].hist(bins = 100, color = color[0])#直方图显示
    plt.xlabel(colnm[i],fontsize = 12)
    plt.ylabel('Frequency')
plt.tight_layout()
print('\nFigure 2: Univariate Histograms')

红酒数据集分析(纯数字数据集)_第2张图片

处理红酒的酸度特征

由于pH影响红酒酸度,故考察与pH相关度高的几个特征

corr_matrix = df.corr()
corr_matrix["pH"].sort_values(ascending= False)

pH                      1.000
volatile acidity        0.235
alcohol                 0.206
free sulfur dioxide     0.070
quality                -0.058
total sulfur dioxide   -0.066
residual sugar         -0.086
sulphates              -0.197
chlorides              -0.265
density                -0.342
citric acid            -0.542
fixed acidity          -0.683
Name: pH, dtype: float64

观察到volatile acidity 、alcohol、citric acid、fixed acidity这四个因素与pH相关度较高

acidityFeat = ['fixed acidity', 'volatile acidity', 'citric acid',
               'alcohol']
plt.figure(figsize=(12,6))
for i in range(4):
    ax = plt.subplot(2,2,i+1)
    v = np.log10(np.clip(df[acidityFeat[i]].values,a_min = 0.001, a_max = None))
    plt.hist(v, bins = 50, color = color[0])#直方图看分布
    plt.xlabel('log(' + acidityFeat[i] + ')',fontsize = 12)#横坐标名称
    plt.ylabel('Frequency')                                #纵坐标名称
plt.tight_layout()#调整格式自动填充
print('\nFigure 3: Acidity Features in log10 Scale')

查看四个特征分布
红酒数据集分析(纯数字数据集)_第3张图片
构造新特征

df['total acid'] = df['fixed acidity'] + df['volatile acidity'] + df['citric acid'] + df['alcohol']

处理甜度特征

甜度(sweetness)
Residual sugar 与酒的甜度相关,通常用来区别各种红酒,干红(<=4 g/L), 半干(4-12 g/L),半甜(12-45 g/L),和甜(>45 g/L)。 这个数据中,主要为干红,没有甜葡萄酒

df['sweetness'] = pd.cut(df["residual sugar"],bins = [0, 4, 12, 45],labels=["dry", "medium dry", "semi-sweet"])#注意labls参数
plt.hist(df['sweetness'])

红酒数据集分析(纯数字数据集)_第4张图片

双变量分析

红酒品质vs.其他特征

plt.figure(figsize=(10,8))
colnm = df.columns.tolist()[:11] + ['total acid']#转换成list
for i in range(12):
    ax = plt.subplot(4,3,i+1)
    sns.boxplot(data= df ,x ='quality', y= colnm[i],color = color[1], width = 0.6)
    plt.ylabel(colnm[i],fontsize = 12)
plt.tight_layout()
print("\nFigure 7: Physicochemical Properties and Wine Quality by Boxplot")

红酒数据集分析(纯数字数据集)_第5张图片
结论:
正相关:citric acid,sulphates,alcohol,total acid
负相关:volatile acidity,density,pH
转换成人话
1.品质好的酒有更高的柠檬酸,硫酸盐,和酒精度数。硫酸盐(硫酸钙)的加入通常是调整酒的酸度的。其中酒精度数和品质的相关性最高。
2.品质好的酒有较低的挥发性酸类,密度,和pH。
3.残留糖分,氯离子,二氧化硫似乎对酒的品质影响不大。

绘制热力学关系图查看相关性

plt.figure(figsize = (10,8))
cmap = sns.diverging_palette(200, 20)#设置自己的调色盘
sns.heatmap(data=mcorr,cmap=cmap,annot= True,fmt='0.2f')
#annot显示数字,fmt='0.2f'保留两位小数

红酒数据集分析(纯数字数据集)_第6张图片

密度vs.酒精浓度

(sns.regplot线性回归拟合)

# style :风格选择包括:"white", "dark", "whitegrid", "darkgrid", "ticks"
sns.set_style('ticks') 
#设置显示比例尺度  选择包括:'paper', 'notebook', 'talk', 'poster'
sns.set_context("notebook", font_scale= 1.4)

# plot figure
plt.figure(figsize = (6,4))
sns.regplot(x='density', y = 'alcohol', data = df, scatter_kws = {'s':10}, color = color[1])
#scatter_kws 散点大小
plt.xlim(0.989, 1.005)  
plt.ylim(7,16)
print('Figure 9: Density vs Alcohol')

红酒数据集分析(纯数字数据集)_第7张图片

seaborn英文文档
seaborn中文文档

酸性物质含量vs.pH

acidity_related = ['fixed acidity', 'volatile acidity', 'total sulfur dioxide', 
                   'sulphates', 'total acid']
plt.figure(figsize=(10,8))
for i in range(5):
    ax = plt.subplot(3,2,i+1)
    sns.regplot(x='pH', y = acidity_related[i] , data = df, scatter_kws = {'s':5}, color = color[2])

多变量分析

与品质相关性最高的三个特征是酒精浓度,挥发性酸度,和柠檬酸。下面图中显示的酒精浓度,挥发性酸和品质的关系。

酒精浓度,挥发性酸和品质
对于好酒(7,8)以及差酒(3,4),关系很明显。但是对于中等酒(5,6),酒精浓度的挥发性酸度有很大程度的交叉。

sns.lmplot(x = 'alcohol', y = 'volatile acidity', hue = 'quality', 
           data = df, fit_reg = False, scatter_kws={'s':10}, size = 5)
#hue 为类别,fit_reg:是否展示拟合曲线

红酒数据集分析(纯数字数据集)_第8张图片

sns.lmplot(x = 'alcohol', y = 'volatile acidity', col='quality', hue = 'quality', 
           data = df,fit_reg = False, size = 3,  aspect = 0.9, col_wrap=3,
           scatter_kws={'s':20})

红酒数据集分析(纯数字数据集)_第9张图片

pH,非挥发性酸,和柠檬酸

pH和非挥发性的酸以及柠檬酸有相关性。整体趋势也很合理,即浓度越高,pH越低。

plt.figure(figsize=(6,5))
cm = plt.cm.get_cmap('RdBu')#plt设置调色方式
sc = plt.scatter(df['fixed acidity'], df['citric acid'], c=df['pH'], vmin=2.6, vmax=4, s=20, cmap=cm)
bar = plt.colorbar(sc)#设置颜色渐变图例
bar.set_label('pH', rotation = 0)#图例名称,偏移量
plt.xlabel('fixed acidity')
plt.ylabel('citric acid')
plt.xlim(4,18)
plt.ylim(0,1)

红酒数据集分析(纯数字数据集)_第10张图片
总结:
整体而言,红酒的品质主要与酒精浓度,挥发性酸,和柠檬酸有关。对于品质优于7,或者劣于4的酒,直观上是线性可分的。但是品质为5,6的酒很难线性区分。
主要掌握单变量-双变量-多变量分析模式及相应可视化方法
红酒数据分析

你可能感兴趣的:(编程入门,python,机器学习,数据分析)