电子商务+seaborn画图+线性回归

2022-08-03,,,,

数据集https://download.csdn.net/download/qq_42363032/12615450

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import scipy.stats as sci


# 加载数据集
customers = pd.read_csv('Ecommerce Customers.csv')
print(customers.head())

打印散点图+分布图

# 打印散点图+分布图
# sns.jointplot(x='Time on Website',y='Yearly Amount Spent',data=customers)
sns.jointplot(x='Time on Website', y='Yearly Amount Spent',  # 设置xy轴,显示columns名称
              data=customers,  # 设置数据
              color='b',  # 设置颜色
              s=50, edgecolor='w', linewidth=1,  # 设置散点大小、边缘颜色及宽度(只针对scatter)
              stat_func=sci.pearsonr,   # 皮尔森相关系数
              kind='scatter',  # 设置类型:'scatter','reg','resid','kde','hex'
              # stat_func=<function pearsonr>,
              space=0.1,  # 设置散点图和布局图的间距
              size=8,  # 图表大小(自动调整为正方形))
              ratio=5,  # 散点图与布局图高度比,整型
              marginal_kws=dict(bins=15, rug=False),  # 设置柱状图箱数,是否设置rug(粗糙齿状小线)
              )
plt.show()

sns.jointplot(x='Time on App', y='Yearly Amount Spent', data=customers)
plt.show()

六边形图

# 六边形图
sns.jointplot(x='Time on Website', y='Yearly Amount Spent', data=customers,  # 设置数据
              color='b',  # 设置颜色
              # s = 50, edgecolor = 'w', linewidth = 1,#设置散点大小、边缘颜色及宽度(只针对scatter)
              stat_func=sci.pearsonr,
              kind='hex',  # 设置类型:'scatter','reg','resid','kde','hex'
              space=0.1,  # 设置散点图和布局图的间距
              size=8,  # 图表大小(自动调整为正方形))
              ratio=5,  # 散点图与布局图高度比,整型
              # marginal_kws = dict(bins=15, rug =True) #设置柱状图箱数,是否设置rug
              )
plt.show()

矩阵散点图

sns.pairplot(customers)
plt.show()
# sns.pairplot(customers,
#              kind = 'scatter', #散点图/回归分布图{'scatter', 'reg'})
#              diag_kind = 'hist', #直方图/密度图{'hist', 'kde'}
#              hue = 'species',   #按照某一字段进行分类
#              palette = 'husl',  #设置调色板
#              markers = ['o', 's', 'D'], #设置不同系列的点样式(这里根据参考分类个数)
#              size = 2  #图标大小
#              )

完整代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import scipy.stats as sci

warnings.filterwarnings('ignore')

'''
Seaborn是一个用Python制作统计图形的库。它构建在matplotlib之上,并与pandas数据结构紧密集成。 以下是seaborn提供的一些功能:

一个面向数据集的API,用于检查多个变量之间的关系
专门支持使用分类变量来显示观察结果或汇总统计数据
用于可视化单变量或双变量分布以及在数据子集之间比较它们的选项
各种因变量线性回归模型的自动估计与绘图
方便查看复杂数据集的总体结构
用于构造多图网格的高级封装,可以轻松地构建复杂的数据图表
使用几个内置主题对matplotlib图形样式进行简洁控制
用于选择能够真实显示数据中模式的调色板的工具
Seaborn的目标是使可视化成为探索和理解数据的核心部分。它面向数据集的绘图功能对包含整个数据集的数据流和数组进行操作,并在内部执行必要的语义映射和统计聚合以生成信息图。
'''

# 加载数据集
customers = pd.read_csv('Ecommerce Customers.csv')
print(customers.head())

# 打印散点图+分布图
sns.jointplot(x='Time on Website', y='Yearly Amount Spent',  # 设置xy轴,显示columns名称
              data=customers,  # 设置数据
              color='b',  # 设置颜色
              s=50, edgecolor='w', linewidth=1,  # 设置散点大小、边缘颜色及宽度(只针对scatter)
              stat_func=sci.pearsonr,  # 皮尔森相关系数
              kind='scatter',  # 设置类型:'scatter','reg','resid','kde','hex'
              # stat_func=<function pearsonr>,
              space=0.1,  # 设置散点图和布局图的间距
              size=8,  # 图表大小(自动调整为正方形))
              ratio=5,  # 散点图与布局图高度比,整型
              marginal_kws=dict(bins=15, rug=False),  # 设置柱状图箱数,是否设置rug(粗糙齿状小线)
              )
# sns.jointplot(x='Time on App', y='Yearly Amount Spent', data=customers)

# 矩阵散点图
sns.pairplot(customers)

plt.show()

y = customers['Yearly Amount Spent']
X = customers[['Avg. Session Length', 'Time on App', 'Time on Website', 'Length of Membership']]

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)

from sklearn.linear_model import LinearRegression

lm = LinearRegression()
lm.fit(X_train, y_train)
print('Coefficients: \n', lm.coef_)  # coef_  theta、w     intercept_ 截距、b

predictions = lm.predict(X_test)
plt.scatter(y_test, predictions)
plt.xlabel('Y Test')
plt.ylabel('Predicted Y')
plt.show()

# 评估指标
from sklearn import metrics

print('MAE:', metrics.mean_absolute_error(y_test, predictions))
print('MSE:', metrics.mean_squared_error(y_test, predictions))
print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))
print('====================================================================================')
coeffecients = pd.DataFrame(lm.coef_, X.columns)
coeffecients.columns = ['Coeffecient']  # 设置列名
print(coeffecients.head())



本文地址:https://blog.csdn.net/qq_42363032/article/details/107346579

《电子商务+seaborn画图+线性回归.doc》

下载本文的Word格式文档,以方便收藏与打印。