数据分析案例-苹果品质数据可视化分析+建模预测
🤵♂️ 个人主页:@艾派森的个人主页
✍🏻作者简介:Python学习者
🐋 希望大家多多支持,我们一起进步!😄
如果文章对你有帮助的话,
欢迎评论 💬点赞👍🏻 收藏 📂加关注+
目录
1.项目背景
2.数据集介绍
3.技术工具
4.导入数据
5.数据可视化
6.特征工程
7.模型构建
8.模型评估
1.项目背景
在当今社会中,消费者对产品质量和安全性的关注越来越高。苹果作为一种常见的水果,其品质对消费者来说至关重要。因此,对苹果品质数据进行可视化分析并建立预测模型,对于生产者和消费者都具有重要意义。
苹果品质受多种因素影响,包括但不限于栽培环境、品种、采摘时间、运输条件等。通过对苹果品质数据进行可视化分析,我们可以探索这些因素之间的关系,并了解它们对苹果品质的影响程度。这有助于生产者优化栽培管理、采摘和运输过程,以提高苹果的质量。
另外,建立预测模型可以帮助生产者预测苹果品质,提前发现可能影响苹果品质的因素,并采取相应的措施,以保证苹果质量的稳定和可靠性。这对于生产者来说是一种重要的管理工具,可以帮助他们更好地管理生产过程,提高苹果的市场竞争力。
综上所述,通过对苹果品质数据进行可视化分析和建模预测,可以帮助生产者更好地了解苹果品质的形成机制,优化生产管理,并提高产品质量,从而满足消费者对高质量和安全的苹果的需求。
2.数据集介绍
本数据集来源于Kaggle,原始数据集共有4001条,9个变量,包括苹果的相关品质信息,比如大小、重量、甜度、酸度等等。
3.技术工具
Python版本:3.9
代码编辑器:jupyter notebook
4.导入数据
导入第三方库并加载数据集
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import LabelEncoder
import plotly.express as px
df = pd.read_csv("apple_quality.csv")
df.head()
查看数据大小
查看数据基本信息
c
查看数据描述性统计分析
统计缺失值情况
5.数据可视化
# 显示交互式散点图
fig = px.scatter(df, x='Size', y='Weight', color='Quality', hover_data=['Sweetness', 'Crunchiness'],
title='Interactive Scatter Plot: Size vs. Weight', labels={'Size': 'Apple Size', 'Weight': 'Apple Weight'})
# 展示
fig.show()
scatter_3d_fig = px.scatter_3d(df, x='Sweetness', y='Crunchiness', z='Juiciness', color='Quality',
title='3D Scatter Plot: Sweetness vs. Crunchiness vs. Juiciness',
labels={'Sweetness': 'Sweetness', 'Crunchiness': 'Crunchiness', 'Juiciness': 'Juiciness'})
scatter_3d_fig.show()
pie_fig = px.pie(df, names='Quality', title='Distribution of Apple Quality')
pie_fig.show()
le = LabelEncoder()
df['Quality'] = le.fit_transform(df['Quality'])
# 计算相关矩阵
correlation_matrix = df.corr()
# 热力图
heatmap_fig = px.imshow(correlation_matrix, color_continuous_scale='Viridis',
labels=dict(color='Correlation'), title='Correlation Heatmap')
heatmap_fig.show()
parallel_fig = px.parallel_coordinates(df, color='Quality',
dimensions=['Size', 'Weight', 'Sweetness', 'Crunchiness', 'Juiciness', 'Ripeness'],
labels={'Quality': 'Apple Quality'},
title='Parallel Coordinates Plot of Apple Attributes')
parallel_fig.show()
box_fig = px.box(df, x='Quality', y=['Size', 'Weight', 'Sweetness', 'Crunchiness', 'Juiciness', 'Ripeness'],
labels={'variable': 'Attribute', 'value': 'Value'},
title='Distribution of Attributes by Apple Quality')
box_fig.show()
scatter_matrix_fig = px.scatter_matrix(df, dimensions=['Size', 'Weight', 'Sweetness', 'Crunchiness', 'Juiciness', 'Ripeness'],
color='Quality',
title='Scatter Matrix: Pairwise Relationships between Attributes')
scatter_matrix_fig.show()
agg_df = df.groupby('Quality').mean().reset_index()
melted_df = pd.melt(agg_df, id_vars=['Quality'], value_vars=['Size', 'Weight', 'Sweetness', 'Crunchiness', 'Juiciness', 'Ripeness'],
var_name='Attribute', value_name='Value')
radar_fig = px.line_polar(melted_df, r='Value', theta='Attribute', line_close=True, color='Quality',
title='Radar Chart: Profile of Apple Attributes')
radar_fig.show()
line_chart_fig = px.line(df, x='Size', y='Sweetness', color='Quality',
title='Line Chart: Trend of Sweetness over Size')
line_chart_fig.show()
6.特征工程
准备建模数据并拆分数据集为训练集和测试集
df = pd.get_dummies(df, columns=['Quality'], drop_first=True)
# 准备建模数据
X = df.drop(['A_id', 'Quality_1'], axis=1)
y = df['Quality_1']
# 拆分数据集为训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
7.模型构建
构建逻辑回归模型
from sklearn.linear_model import LogisticRegression
# 构建逻辑回归模型
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
8.模型评估
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
# 评估模型
accuracy = accuracy_score(y_test, y_pred)
classification_report_result = classification_report(y_test, y_pred)
confusion_matrix_result = confusion_matrix(y_test, y_pred)
print("Accuracy:", accuracy)
print("\nClassification Report:\n", classification_report_result)
print("\nConfusion Matrix:\n", confusion_matrix_result)
源代码
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import LabelEncoder
import plotly.express as px
df = pd.read_csv("apple_quality.csv")
df.head()
df.shape
df.info()
df.describe()
df.isnull().sum()
# 删除具有非数字“Acidity”值的行
df = df[pd.to_numeric(df['Acidity'], errors='coerce').notnull()]
# “Acidity”列转换为浮点数
df['Acidity'] = df['Acidity'].astype(float)
df.info()
# 显示交互式散点图
fig = px.scatter(df, x='Size', y='Weight', color='Quality', hover_data=['Sweetness', 'Crunchiness'],
title='Interactive Scatter Plot: Size vs. Weight', labels={'Size': 'Apple Size', 'Weight': 'Apple Weight'})
# 展示
fig.show()
scatter_3d_fig = px.scatter_3d(df, x='Sweetness', y='Crunchiness', z='Juiciness', color='Quality',
title='3D Scatter Plot: Sweetness vs. Crunchiness vs. Juiciness',
labels={'Sweetness': 'Sweetness', 'Crunchiness': 'Crunchiness', 'Juiciness': 'Juiciness'})
scatter_3d_fig.show()
pie_fig = px.pie(df, names='Quality', title='Distribution of Apple Quality')
pie_fig.show()
le = LabelEncoder()
df['Quality'] = le.fit_transform(df['Quality'])
# 计算相关矩阵
correlation_matrix = df.corr()
# 热力图
heatmap_fig = px.imshow(correlation_matrix, color_continuous_scale='Viridis',
labels=dict(color='Correlation'), title='Correlation Heatmap')
heatmap_fig.show()
parallel_fig = px.parallel_coordinates(df, color='Quality',
dimensions=['Size', 'Weight', 'Sweetness', 'Crunchiness', 'Juiciness', 'Ripeness'],
labels={'Quality': 'Apple Quality'},
title='Parallel Coordinates Plot of Apple Attributes')
parallel_fig.show()
box_fig = px.box(df, x='Quality', y=['Size', 'Weight', 'Sweetness', 'Crunchiness', 'Juiciness', 'Ripeness'],
labels={'variable': 'Attribute', 'value': 'Value'},
title='Distribution of Attributes by Apple Quality')
box_fig.show()
scatter_matrix_fig = px.scatter_matrix(df, dimensions=['Size', 'Weight', 'Sweetness', 'Crunchiness', 'Juiciness', 'Ripeness'],
color='Quality',
title='Scatter Matrix: Pairwise Relationships between Attributes')
scatter_matrix_fig.show()
agg_df = df.groupby('Quality').mean().reset_index()
melted_df = pd.melt(agg_df, id_vars=['Quality'], value_vars=['Size', 'Weight', 'Sweetness', 'Crunchiness', 'Juiciness', 'Ripeness'],
var_name='Attribute', value_name='Value')
radar_fig = px.line_polar(melted_df, r='Value', theta='Attribute', line_close=True, color='Quality',
title='Radar Chart: Profile of Apple Attributes')
radar_fig.show()
line_chart_fig = px.line(df, x='Size', y='Sweetness', color='Quality',
title='Line Chart: Trend of Sweetness over Size')
line_chart_fig.show()
df = pd.get_dummies(df, columns=['Quality'], drop_first=True)
# 准备建模数据
X = df.drop(['A_id', 'Quality_1'], axis=1)
y = df['Quality_1']
# 拆分数据集为训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
from sklearn.linear_model import LogisticRegression
# 构建逻辑回归模型
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
# 评估模型
accuracy = accuracy_score(y_test, y_pred)
classification_report_result = classification_report(y_test, y_pred)
confusion_matrix_result = confusion_matrix(y_test, y_pred)
print("Accuracy:", accuracy)
print("\nClassification Report:\n", classification_report_result)
print("\nConfusion Matrix:\n", confusion_matrix_result)
心得与体会:
通过这次Python项目实战,我学到了许多新的知识,这是一个让我把书本上的理论知识运用于实践中的好机会。原先,学的时候感叹学的资料太难懂,此刻想来,有些其实并不难,关键在于理解。
在这次实战中还锻炼了我其他方面的潜力,提高了我的综合素质。首先,它锻炼了我做项目的潜力,提高了独立思考问题、自我动手操作的潜力,在工作的过程中,复习了以前学习过的知识,并掌握了一些应用知识的技巧等
在此次实战中,我还学会了下面几点工作学习心态:
1)继续学习,不断提升理论涵养。在信息时代,学习是不断地汲取新信息,获得事业进步的动力。作为一名青年学子更就应把学习作为持续工作用心性的重要途径。走上工作岗位后,我会用心响应单位号召,结合工作实际,不断学习理论、业务知识和社会知识,用先进的理论武装头脑,用精良的业务知识提升潜力,以广博的社会知识拓展视野。
2)努力实践,自觉进行主角转化。只有将理论付诸于实践才能实现理论自身的价值,也只有将理论付诸于实践才能使理论得以检验。同样,一个人的价值也是透过实践活动来实现的,也只有透过实践才能锻炼人的品质,彰显人的意志。
3)提高工作用心性和主动性。实习,是开端也是结束。展此刻自我面前的是一片任自我驰骋的沃土,也分明感受到了沉甸甸的职责。在今后的工作和生活中,我将继续学习,深入实践,不断提升自我,努力创造业绩,继续创造更多的价值。
这次Python实战不仅仅使我学到了知识,丰富了经验。也帮忙我缩小了实践和理论的差距。在未来的工作中我会把学到的理论知识和实践经验不断的应用到实际工作中,为实现理想而努力。
资料获取,更多粉丝福利,关注下方公众号获取