红酒数据分析

本文深入探讨了如何运用机器学习技术对红酒数据进行分析,揭示其中的品质特征和市场趋势,为品鉴和市场策略提供科学依据。
摘要由CSDN通过智能技术生成

红酒数据分析

**机器学习---数据分析**

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    color = sns.color_palette()  #创建调色板
pd.set_option('precision',3)  #设置精度

df = pd.read_csv('./winequality-red.csv',sep = ';')
#print(df.head(5))
#print(df.info())
#print(df.describe())
plt.style.use('ggplot')` `
colnm = df.columns.tolist()  #将df.columns转换为列表
fig = plt.figure(figsize=(10,6))
for i in range(12):
    plt.subplot(2,6,i+1)
    sns.boxplot(df[colnm[i]],orient='v',width=0.5,color=color[0])  #orient:图像方向,v:水平
    plt.ylabel(colnm[i],fontsize=12)
plt.tight_layout()  #tight_layout会自动调整子图参数,使之填充整个图像区域。
#print('\nFigure 1: Univariate Boxplots')
#plt.show()
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()
#plt.show()
#print('\nFigure 2: Univariate Histograms')
"""这个数据集有7个酸度相关的特征:fixed acidity, volatile acidity, citric acid, free sulfur dioxide, total sulfur dioxide, sulphates, pH。
   前6个特征都与红酒的pH的相关。
   pH是在对数的尺度,下面对前6个特征取对数然后作histogram。
"""
acidityFeat = ['fixed acidity', 'volatile acidity', 'citric acid',
               'free sulfur dioxide', 'total sulfur dioxide', 'sulphates']
plt.figure(figsize=(10,4))
for i in range(6):
    ax=plt.subplot(2,3,i+1)
    v=np.log10(np.clip(df[acidityFeat[i]].values,a_min=0.001,a_max=None))
               #np.clip()将一个数组元素的值限制在一个范围内
    plt.hist(v,bins=50,color=color[0])
    plt.xlabel('log('+acidityFeat[i]+')',fontsize=12)
    plt.ylabel('Frequency')
plt.tight_layout()
#plt.show()
#print('\nFigure 3: Acidity Features in log10 Scale')
plt.figure(figsize=(6,3))
bins = 10**(np.linspace(-2,2))
plt.hist(df['fixed acidity'],bins=bins,edgecolor='k',label='Fixed Acidity')  #bins: 直方图的柱数,可选项,默认为10
plt.hist(df['volatile acidity'],bins=bins,edgecolor='k',label='Volatile acidity')
plt.hist(df['citric acid'],bins=bins,edgecolor='k',label='Citric Avid')
plt.xscale('log')
plt.xlabel('Acid Concentration (g/dm^3)')
plt.ylabel('Frequency')
plt.title('Histogram or Acid Concentration')
plt.legend()
plt.tight_layout()
#plt.show()
#print('Figure 4')
"""pH值主要是与fixed acidity有关,
fixed acidity比volatile acidity和citric acid高1到2个数量级(Figure 4),比free sulfur dioxide, total sulfur dioxide, sulphates高3个数量级。
   一个新特征total acid来自于前三个特征的和。
"""
df['total acid'] = df['fixed acidity']+df['volatile acidity']+df['citric acid']
plt.figure(figsize=(8,3))
plt.subplot(121)
plt.hist(df['total acid'],bins=50,color=color[0])
plt.xlabel('total acid')
plt.ylabel('Frequency')
plt.subplot(122)
plt.hist(np.log(df['total acid']),bins=50,color=color[0])
plt.xlabel('log(total acid)')
plt.ylabel('Frequency')
plt.tight_layout()
#plt.show()
#print("Figure 5: Total Acid Histogram")
"""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"])
plt.figure(figsize=(5,3))
df['sweetness'].value_counts().plot(kind='bar',color=color[0])
plt.xticks(rotation=0)
plt.xlabel('sweetness',fontsize=12)
plt.ylabel('Frequency',fontsize=12)
plt.tight_layout()
#plt.show()
#print("Figure 6: Sweetness")

#双变量分析
sns.set_style('ticks')  #设置图表主题背景为十字叉
sns.set_context('notebook',font_scale=1.1)  #设置图表样式
colnm1 = df.columns.tolist()[:11]+['total acid']
plt.figure(figsize=(10,8))
for i in range(12):
    plt.subplot(4,3,i+1)
    sns.boxplot(x='quality',y=colnm[i],data=df,color=color[1],width=0.6)
plt.tight_layout()
#plt.show()
#print("\nFigure 7: Physicochemical Properties and Wine Quality by Boxplot")
sns.set_style('dark')
plt.figure(figsize=(10,8))
colnm=df.columns.tolist()[:11]+['total acid','quality']
mcorr = df[colnm].corr()  #相关系数矩阵,即给出了任意两个变量之间的相关系数
mask = np.zeros_like(mcorr,dtype=np.bool)
mask[np.triu_indices_from(mask)] = True  # 角分线右侧为True
cmap = sns.diverging_palette(220,10,as_cmap=True)  #创建分散颜色
g = sns.heatmap(mcorr,mask=mask,cmap=cmap,square=True,annot=True,fmt='0.2f')
#plt.show()
#print("\nFigure 8: Pairwise Correlation Plot")
#从图8可看出密度和酒精度数有较大的相关性
sns.set_style('ticks')
sns.set_context("notebook",font_scale=1.4)
plt.figure(figsize=(6,4))
#画出双变量的散点图,然后以y~x拟合回归方程和预测值95%置信区间并将其画出。
sns.regplot(x='density',y='alcohol',data=df,scatter_kws={'s':10},color=color[1])
plt.xlim(0.989, 1.005)
plt.ylim(7,16)
#plt.show()
#print('Figure 9: Density vs Alcohol')
#pH和非挥发性酸性物质有-0.683的相关性

acidity_related = ['fixed acidity', 'volatile acidity', 'total sulfur dioxide',
                   'sulphates', 'total acid']
plt.figure(figsize = (10,6))
for i in range(5):
    plt.subplot(2,3,i+1)
    sns.regplot(x='pH', y = acidity_related[i], data = df, scatter_kws = {'s':10}, color = color[1])
plt.tight_layout()
#print("Figure 10: pH vs acid")
#与品质相关性最高的三个特征是酒精浓度,挥发性酸度,和柠檬酸。
plt.style.use('ggplot')
sns.lmplot(x = 'alcohol', y = 'volatile acidity', hue = 'quality',
           data = df, fit_reg = False, scatter_kws={'s':10}, size = 5)
#print("Figure 11-1: Scatter Plots of Alcohol, Volatile Acid and Quality")
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})
#pH和非挥发性的酸以及柠檬酸有相关性。整体趋势也很合理,即浓度越高,pH越低。
sns.set_style('ticks')
sns.set_context("notebook", font_scale= 1.4)
plt.figure(figsize=(6,5))
cm = plt.cm.get_cmap('RdBu')
sc = plt.scatter(df['fixed acidity'], df['citric acid'], c=df['pH'], vmin=2.6, vmax=4, s=15, 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)
print('Figure 12: pH with Fixed Acidity and Citric Acid')
**"""总结:
       红酒的品质主要与酒精浓度,挥发性酸,和柠檬酸有关。
       于品质优于7,或者劣于4的酒,直观上是线性可分的。但是品质为5,6的酒很难线性区分。
"""**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值