项目准备(flask+pyhon+MachineLearning)- 3

目录

1.商品信息

2. 商品销售预测

2.1 机器学习

2.2 预测功能

3. 模型评估


1.商品信息

@app.route('/products')
def products():"""商品分析页面"""data = load_data()# 计算当前期间和上期间current_period = data[data['成交时间'] >= data['成交时间'].max() - timedelta(days=30)]previous_period = data[(data['成交时间'] < data['成交时间'].max() - timedelta(days=30)) & (data['成交时间'] >= data['成交时间'].max() - timedelta(days=60))]# 计算商品指标current_sales = current_period.groupby('商品ID').apply(lambda x: (x['销量'] * x['单价']).sum())previous_sales = previous_period.groupby('商品ID').apply(lambda x: (x['销量'] * x['单价']).sum())product_metrics = pd.DataFrame({'current_sales': current_sales,'previous_sales': previous_sales}).fillna(0)product_metrics['growth_rate'] = ((product_metrics['current_sales'] - product_metrics['previous_sales']) / product_metrics['previous_sales']).fillna(0)max_competitor_sales = product_metrics['current_sales'].max()product_metrics['market_share'] = (product_metrics['current_sales'] / max_competitor_sales)# BCG矩阵分类growth_rate_threshold = product_metrics['growth_rate'].median()market_share_threshold = product_metrics['market_share'].median()def classify_product(row):if row['growth_rate'] >= growth_rate_threshold:return '明星商品' if row['market_share'] >= market_share_threshold else '问题商品'else:return '现金牛' if row['market_share'] >= market_share_threshold else '瘦狗'product_metrics['category'] = product_metrics.apply(classify_product, axis=1)# 统计分类结果category_stats = product_metrics.groupby('category').agg({'current_sales': ['count', 'sum']})category_stats.columns = ['product_count', 'sales_amount']category_stats['sales_percentage'] = (category_stats['sales_amount'] / category_stats['sales_amount'].sum())return render_template('products.html',category_statistics=category_stats.to_dict('index'),growth_rate_threshold=float(growth_rate_threshold),market_share_threshold=float(market_share_threshold))

2. 商品销售预测

2.1 机器学习

def prepare_features(data):"""准备特征数据"""# 删除包含NaN的行data = data.dropna(subset=['销量', '单价', '类别ID', '门店编号'])# 时间特征data['weekday'] = data['成交时间'].dt.weekdaydata['month'] = data['成交时间'].dt.monthdata['hour'] = data['成交时间'].dt.hour# 类别编码le_category = LabelEncoder()le_store = LabelEncoder()# 拟合编码器le_category.fit(data['类别ID'].astype(str))  # 将类别ID转换为字符串le_store.fit(data['门店编号'].astype(str))# 转换数据data['类别编码'] = le_category.transform(data['类别ID'].astype(str))data['门店编码'] = le_store.transform(data['门店编号'].astype(str))# 特征选择features = ['类别编码', '门店编码', '单价', 'weekday', 'month', 'hour']target = '销量'# 确保所有特征都是数值类型X = data[features].astype(float)y = data[target].astype(float)return X, y, le_category, le_store# 创建全局变量来存储模型和编码器
model = None
scaler = None
label_encoder_category = None
label_encoder_store = Nonedef initialize_model():"""初始化模型和编码器"""global model, scaler, label_encoder_category, label_encoder_storetry:data = load_data()X, y, le_category, le_store = prepare_features(data)# 训练模型X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 标准化特征scaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)# 训练决策树模型model = DecisionTreeRegressor(random_state=42, max_depth=10)model.fit(X_train_scaled, y_train)# 保存编码器label_encoder_category = le_categorylabel_encoder_store = le_storereturn Trueexcept Exception as e:print(f"模型初始化错误: {str(e)}")return False

2.2 预测功能

@app.route('/predict', methods=['POST'])
def predict():"""处理预测请求"""global model, scaler, label_encoder_category, label_encoder_storetry:# 如果模型未初始化,先初始化if model is None or scaler is None:if not initialize_model():return jsonify({'error': '模型初始化失败'}), 500# 获取表单数据category = request.form['category']store = request.form['store']price = float(request.form['price'])weekday = int(request.form['weekday'])month = int(request.form['month'])try:# 转换类别编码和门店编码category_encoded = label_encoder_category.transform([str(category)])[0]store_encoded = label_encoder_store.transform([str(store)])[0]except ValueError as e:return jsonify({'error': f'无效的输入数据: {str(e)}'}), 400# 准备预测数据pred_data = pd.DataFrame([[category_encoded,store_encoded,price,weekday,month,12  # 使用默认时间]], columns=['类别编码', '门店编码', '单价', 'weekday', 'month', 'hour'])# 标准化预测数据pred_data_scaled = scaler.transform(pred_data)# 预测prediction = model.predict(pred_data_scaled)[0]# 确保预测结果为正整数prediction = max(0, round(prediction))# 获取门店信息store_info = STORE_INFO.get(store, {})store_name = store_info.get('name', f'门店{store}')# 加载历史数据进行分析data = load_data()# 计算该类别的历史平均销量category_avg = data[data['类别ID'].astype(str) == str(category)]['销量'].mean()# 计算该门店的历史平均销量store_avg = data[data['门店编号'].astype(str) == str(store)]['销量'].mean()# 计算价格区间的平均销量price_range = 0.1  # 价格范围±10%price_lower = price * (1 - price_range)price_upper = price * (1 + price_range)price_avg = data[(data['单价'] >= price_lower) & (data['单价'] <= price_upper)]['销量'].mean()# 计算同时段(星期几和月份)的历史平均销量time_avg = data[(data['成交时间'].dt.weekday == weekday) & (data['成交时间'].dt.month == month)]['销量'].mean()# 生成分析结果analysis = {'category_comparison': round((prediction / category_avg * 100) if category_avg > 0 else 100),'store_comparison': round((prediction / store_avg * 100) if store_avg > 0 else 100),'price_comparison': round((prediction / price_avg * 100) if price_avg > 0 else 100),'time_comparison': round((prediction / time_avg * 100) if time_avg > 0 else 100),'category_avg': round(category_avg if not pd.isna(category_avg) else 0),'store_avg': round(store_avg if not pd.isna(store_avg) else 0),'price_avg': round(price_avg if not pd.isna(price_avg) else 0),'time_avg': round(time_avg if not pd.isna(time_avg) else 0)}return jsonify({'prediction': int(prediction),'category': category,'category_name': CATEGORY_NAMES.get(category, f'类别{category}'),'store': store,'store_name': store_name,'price': price,'weekday': weekday,'month': month,'analysis': analysis})except Exception as e:print(f"预测错误: {str(e)}")return jsonify({'error': str(e)}), 400@app.route('/prediction')
def prediction_page():"""销售预测页面"""data = load_data()categories = sorted(data['类别ID'].astype(str).unique().tolist())stores = sorted(data['门店编号'].astype(str).unique().tolist())# 创建类别选项列表,包含ID和名称category_options = [{'id': cat_id, 'name': CATEGORY_NAMES.get(cat_id, f'类别{cat_id}')} for cat_id in categories]# 创建门店选项列表store_options = [{'id': store_id, 'name': STORE_INFO.get(store_id, {}).get('name', f'门店{store_id}')}for store_id in stores]# 初始化模型(如果需要)global modelif model is None:initialize_model()return render_template('prediction.html', categories=category_options,stores=store_options)

3. 模型评估

@app.route('/model_evaluation')
def model_evaluation():"""模型评估页面"""data = load_data()# 准备特征X, y, le_category, le_store = prepare_features(data)# 训练模型并获取评估结果_, _, metrics, feature_importance, scatter_data, residual_data, feature_names, importance_scores = train_models(X, y)return render_template('model_evaluation.html',metrics=metrics,feature_importance=feature_importance,scatter_data=scatter_data,residual_data=residual_data,feature_names=feature_names,importance_scores=importance_scores)

4. 训练模型

def train_models(X, y):"""训练模型"""# 数据分割X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 标准化特征scaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test)# 训练决策树模型dt_model = DecisionTreeRegressor(random_state=42, max_depth=10)dt_model.fit(X_train_scaled, y_train)# 预测y_pred = dt_model.predict(X_test_scaled)# 计算模型指标metrics = {'r2_score': r2_score(y_test, y_pred),'mse': mean_squared_error(y_test, y_pred),'mae': mean_absolute_error(y_test, y_pred),'rmse': np.sqrt(mean_squared_error(y_test, y_pred))}# 特征重要性feature_importance = []for name, importance in zip(X.columns, dt_model.feature_importances_):correlation = np.corrcoef(X[name], y)[0, 1]feature_importance.append({'name': name,'importance': importance,'correlation': correlation})# 准备图表数据scatter_data = [[float(actual), float(pred)] for actual, pred in zip(y_test, y_pred)]residuals = y_test - y_predresidual_data = [[float(pred), float(residual)] for pred, residual in zip(y_pred, residuals)]return dt_model, scaler, metrics, feature_importance, scatter_data, residual_data, X.columns.tolist(), dt_model.feature_importances_.tolist()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/27210.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【MySQL】(2) 库的操作

SQL 关键字&#xff0c;大小写不敏感。 一、查询数据库 show databases; 注意加分号&#xff0c;才算一句结束。 二、创建数据库 {} 表示必选项&#xff0c;[] 表示可选项&#xff0c;| 表示任选其一。 示例&#xff1a;建议加上 if not exists 选项。 三、字符集编码和排序…

AndroidStudio下载旧版本方法

首先&#xff0c;打开Android Studio的官网&#xff1a;https://developer.android.com/studio。 然后&#xff0c;点击【Read release notes】。 然后需要将语言切换成英文&#xff0c;否则会刷不出来。 然后就可以看下各个历史版本了。 直接点链接好像也行&#xff1a;h…

(KTransformers) RTX4090单卡运行 DeepSeek-R1 671B

安装环境为&#xff1a;ubuntu 22.04 x86_64 下载模型 编辑文件vim url.list 写入如下内容 https://modelscope.cn/models/unsloth/DeepSeek-R1-GGUF/resolve/master/DeepSeek-R1-Q4_K_M/DeepSeek-R1-Q4_K_M-00001-of-00009.gguf https://modelscope.cn/models/unsloth/Dee…

C语言(3)—循环、数组、函数的详解

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、函数二、循环与数组 1.循环2.数组 总结 前言 提示&#xff1a;以下是本篇文章正文内容&#xff0c;下面案例可供参考 一、函数 在C语言中&#xff0c;函数…

利用 Python 爬虫进行跨境电商数据采集

1 引言2 代理IP的优势3 获取代理IP账号4 爬取实战案例---&#xff08;某电商网站爬取&#xff09;4.1 网站分析4.2 编写代码4.3 优化代码 5 总结 1 引言 在数字化时代&#xff0c;数据作为核心资源蕴含重要价值&#xff0c;网络爬虫成为企业洞察市场趋势、学术研究探索未知领域…

Minio搭建并在SpringBoot中使用完成用户头像的上传

Minio使用搭建并上传用户头像到服务器操作,学习笔记 Minio介绍 minio官网 MinIO是一个开源的分布式对象存储服务器&#xff0c;支持S3协议并且可以在多节点上实现数据的高可用和容错。它采用Go语言开发&#xff0c;拥有轻量级、高性能、易部署等特点&#xff0c;并且可以自由…

FPGA AXI-Stream协议详解与仿真实践

AXI-Stream协议详解与仿真实践 1 摘要 AXI-Stream总线是一种高效、简单的数据传输协议,主要用于高吞吐量的数据流传输场景。相比于传统的AXI总线,AXI-Stream总线更加简单和轻量级,它通过无需地址的方式,将数据从一个模块传输到另一个模块,适用于需要高速数据传输的应用场…

浙大 DeepSeek 线上课学习笔记

目录 DeepSeek&#xff1a;回望AI三大主义与加强通识教育 从达特茅斯启航的人工智能三大主义 人工智能三剑客之一&#xff1a;符号主义人工智能的逻辑推理 人工智能三剑客之二&#xff1a;连接主义人工智能的数据驱动 人工智能三剑客之三&#xff1a;行为主义人工智能的百…

【Python机器学习】1.2. 线性回归理论:一元线性回归、最小化平方误差和公式(SSE)、梯度下降法

喜欢的话别忘了点赞、收藏加关注哦&#xff08;关注即可查看全文&#xff09;&#xff0c;对接下来的教程有兴趣的可以关注专栏。谢谢喵&#xff01;(&#xff65;ω&#xff65;) 1.2.1. 什么是回归分析(Regressive Analysis)? 一些例子 举一些例子吧&#xff1a; 下图是…

golang介绍,特点,项目结构,基本变量类型与声明介绍(数组,切片,映射),控制流语句介绍(条件,循环,switch case)

目录 golang 介绍 面向并发 面向组合 特点 项目结构 图示 入口文件 main.go 基本变量类型与声明 介绍 声明变量 常量 字符串(string) 字符串格式化 空接口类型 数组 切片 创建对象 追加元素 复制切片 map(映射) 创建对象 使用 多重赋值 控制流语句…

《白帽子讲 Web 安全》之移动 Web 安全

目录 摘要 一、WebView 简介 二、WebView 对外暴露 WebView 对外暴露的接口风险 三、通用型 XSS - Universal XSS 介绍 四、WebView 跨域访问 五、与本地代码交互 js 5.1接口暴露风险&#xff1a; 5.2漏洞利用&#xff1a; 5.3JavaScript 与 Native 代码通信 六、Chr…

算法日常刷题笔记(3)

为保持刷题的习惯 计划一天刷3-5题 然后一周总计汇总一下 这是第三篇笔记 笔记时间为2月24日到3月2日 第一天 设计有序流 设计有序流https://leetcode.cn/problems/design-an-ordered-stream/ 有 n 个 (id, value) 对&#xff0c;其中 id 是 1 到 n 之间的一个整数&#xff…

mysql5.7离线安装及问题解决

这次主要是讲解mysql5.7离线安装教程和一主一从数据库配置 1、去官网下载自己对应的mysql https://downloads.mysql.com/archives/community/2、查看需要安装mysql服务器的linux的类型 uname -a第二步看一下系统有没有安装mysql rpm -qa|grep -i mysql3、上传安装包 用远程…

JAVA实战开源项目:安康旅游网站(Vue+SpringBoot) 附源码

本文项目编号 T 098 &#xff0c;文末自助获取源码 \color{red}{T098&#xff0c;文末自助获取源码} T098&#xff0c;文末自助获取源码 目录 一、系统介绍二、数据库设计三、配套教程3.1 启动教程3.2 讲解视频3.3 二次开发教程 四、功能截图五、文案资料5.1 选题背景5.2 国内…

三数之和_算法

1.题目描述 首先我们分析下这道题目:假设给我们一个数组,让数组某三个不同下标的数相加最终得0,那么我就返回这三个数.但是如果返回的多个数组中的元素相同,那么我们还要删掉其中一个保留一个. 注意:这道题的重点是三个数的下标不能相等并且返回的数组中的元素也不能相等,通过…

关于Deepseek本地部署硬件环境检查教程

要在电脑上本地部署DeepSeek&#xff0c;需要关注以下硬件和软件配置&#xff1a; 硬件配置 CPU&#xff1a;至少4核CPU&#xff0c;推荐Intel i5/i7或AMD Ryzen 5/7系列处理器。内存&#xff1a;至少8GB DDR4内存&#xff0c;推荐16GB DDR4内存&#xff0c;对于大型模型建议…

一周一个Unity小游戏2D反弹球游戏 - 移动的弹板(鼠标版)

前言 本文将实现控制弹板移动,通过Unity的New Input System,可以支持鼠标移动弹板跟随移动,触控点击跟随移动,并且当弹板移动到边界时,弹板不会移动超过边界之外。 创建移动相关的InputAction 项目模版创建的时候默认会有一个InputAction类型的文件,名字为InputSystem_Ac…

250302-绿联NAS通过Docker配置SearXNG及适配Open-WebUI的yaml配置

A. 配置Docker中的代理 绿联NAS简单解决docker无法获取镜像-不用软路由 - 哔哩哔哩 B. 下载官网对应的镜像 群晖NAS用docker搭建SearXNG元搜索引擎_哔哩哔哩_bilibili C. 修改默认省略的参数&#xff0c;只配置Base_URL&#xff0c;删除其它默认的空缺项 searxng-docker/REA…

C++-第十九章:异常

目录 第一节&#xff1a;异常有哪些 第二节&#xff1a;异常相关关键字 2-1.抛出异常 2-2.捕获异常 2-3.异常的捕获规则 2-3-1.异常被最近的catch捕获 2-3-2.catch捕获的是异常的拷贝 2-3-3.异常为子类时&#xff0c;可以用父类引用接收 2-4.捕获任意异常 第三节&#xff1…

Redis详解(实战 + 面试)

目录 Redis 是单线程的&#xff01;为什么 Redis-Key(操作redis的key命令) String 扩展字符串操作命令 数字增长命令 字符串范围range命令 设置过期时间命令 批量设置值 string设置对象,但最好使用hash来存储对象 组合命令getset,先get然后在set Hash hash命令: h…