news 2026/1/24 6:16:41

设计智能体重管理程序,输入每日饮食和运动数据,预测体重变化趋势,给出减重建议。

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
设计智能体重管理程序,输入每日饮食和运动数据,预测体重变化趋势,给出减重建议。

智能体重管理程序设计与实现

一、实际应用场景与痛点分析

应用场景

现代人生活节奏快,体重管理常因缺乏科学指导和持续动力而失败。本程序面向需要科学体重管理的用户,通过记录饮食、运动数据,提供个性化的体重预测和管理建议。

主要痛点

1. 数据记录繁琐 - 手动记录卡路里消耗困难

2. 缺乏科学指导 - 凭感觉减肥效果不佳

3. 缺乏反馈激励 - 难以看到长期趋势和效果

4. 个性化不足 - 通用方案不适用于个体差异

二、核心逻辑与智能控制原理

系统架构

数据采集层 → 数据处理层 → 智能预测层 → 决策输出层

核心智能控制原理

1. 模糊控制 - 处理"轻度运动"、"高热量食物"等模糊概念

2. 专家系统 - 基于营养学和运动科学规则库

3. 预测模型 - 基于能量平衡方程的动态预测

4. 反馈调节 - 根据实际体重调整预测参数

三、代码实现

主程序:smart_weight_manager.py

#!/usr/bin/env python3

"""

智能体重管理程序

基于智能控制原理的个性化体重预测与建议系统

"""

import json

import datetime

import numpy as np

from typing import Dict, List, Tuple, Optional

from dataclasses import dataclass

from enum import Enum

import matplotlib.pyplot as plt

from matplotlib.dates import DateFormatter

import pandas as pd

class ActivityLevel(Enum):

"""活动水平枚举(模糊集合)"""

SEDENTARY = 1.2 # 久坐

LIGHT = 1.375 # 轻度活动

MODERATE = 1.55 # 中度活动

ACTIVE = 1.725 # 活跃

VERY_ACTIVE = 1.9 # 非常活跃

class FoodCategory(Enum):

"""食物类别枚举"""

CARBOHYDRATE = "碳水化合物"

PROTEIN = "蛋白质"

FAT = "脂肪"

VEGETABLE = "蔬菜"

FRUIT = "水果"

SNACK = "零食"

@dataclass

class FoodIntake:

"""食物摄入记录"""

name: str

category: FoodCategory

calories: float # 卡路里

protein: float # 蛋白质(g)

carbs: float # 碳水(g)

fat: float # 脂肪(g)

timestamp: datetime.datetime

@dataclass

class ExerciseRecord:

"""运动记录"""

name: str

duration: float # 分钟

calories_burned: float # 消耗卡路里

intensity: float # 强度系数 0-1

timestamp: datetime.datetime

@dataclass

class UserProfile:

"""用户基本信息"""

name: str

age: int

gender: str # 'male' or 'female'

height: float # 厘米

initial_weight: float # 公斤

target_weight: float # 公斤

activity_level: ActivityLevel

weight_records: List[Tuple[datetime.date, float]] # 历史体重记录

class FuzzyController:

"""

模糊控制器

处理模糊概念如"高强度运动"、"高热量食物"

"""

@staticmethod

def calculate_intensity_level(intensity: float) -> str:

"""模糊化运动强度"""

if intensity < 0.3:

return "低强度"

elif intensity < 0.6:

return "中等强度"

else:

return "高强度"

@staticmethod

def calculate_calorie_level(calories: float, meal_type: str) -> str:

"""模糊化卡路里水平"""

# 不同餐型的基准值

baselines = {

"breakfast": 400,

"lunch": 600,

"dinner": 500,

"snack": 200

}

baseline = baselines.get(meal_type, 500)

ratio = calories / baseline

if ratio < 0.7:

return "低热量"

elif ratio < 1.3:

return "适中"

else:

return "高热量"

@staticmethod

def fuzzy_weight_assessment(bmi: float) -> Dict[str, float]:

"""模糊体重评估"""

membership = {

"偏瘦": max(0, 1 - abs(bmi - 18.5) / 2),

"正常": max(0, 1 - abs(bmi - 22) / 3),

"超重": max(0, 1 - abs(bmi - 27) / 3),

"肥胖": max(0, (bmi - 25) / 10)

}

# 归一化

total = sum(membership.values())

if total > 0:

return {k: v/total for k, v in membership.items()}

return membership

class MetabolicCalculator:

"""

代谢计算器

基于Harris-Benedict方程等计算基础代谢和能量需求

"""

@staticmethod

def calculate_bmr(weight: float, height: float, age: int, gender: str) -> float:

"""计算基础代谢率(BMR) - Harris-Benedict方程"""

if gender.lower() == 'male':

bmr = 88.362 + (13.397 * weight) + (4.799 * height) - (5.677 * age)

else: # female

bmr = 447.593 + (9.247 * weight) + (3.098 * height) - (4.330 * age)

return bmr

@staticmethod

def calculate_tdee(bmr: float, activity_level: ActivityLevel) -> float:

"""计算每日总能量消耗(TDEE)"""

return bmr * activity_level.value

@staticmethod

def calculate_weight_change(calorie_balance: float) -> float:

"""

根据能量平衡计算体重变化

7700大卡 ≈ 1公斤体重变化

"""

return calorie_balance / 7700

class WeightPredictor:

"""

体重预测器

基于能量平衡方程预测未来体重变化

"""

def __init__(self, user_profile: UserProfile):

self.user = user_profile

self.prediction_days = 30

def predict_weight_trend(self,

daily_calorie_intake: float,

daily_exercise_calories: float = 0) -> List[Tuple[datetime.date, float]]:

"""

预测未来体重趋势

使用基于能量平衡的动力学模型

"""

predictions = []

current_date = datetime.date.today()

current_weight = self.user.weight_records[-1][1] if self.user.weight_records else self.user.initial_weight

for day in range(self.prediction_days):

date = current_date + datetime.timedelta(days=day)

# 计算当日BMR

bmr = MetabolicCalculator.calculate_bmr(

current_weight,

self.user.height,

self.user.age,

self.user.gender

)

# 计算TDEE

tdee = MetabolicCalculator.calculate_tdee(bmr, self.user.activity_level)

# 计算能量平衡

calorie_balance = daily_calorie_intake - (tdee + daily_exercise_calories)

# 计算体重变化

weight_change = MetabolicCalculator.calculate_weight_change(calorie_balance)

# 更新体重

current_weight -= weight_change

current_weight = max(current_weight, 30) # 设置最小体重

predictions.append((date, current_weight))

return predictions

def adaptive_predict(self,

historical_data: List[Tuple[datetime.date, float, float]],

learning_rate: float = 0.1) -> List[float]:

"""

自适应预测(带学习功能)

根据历史数据调整预测参数

"""

if len(historical_data) < 7:

return self.predict_weight_trend(2000, 300)[:7]

# 简单线性回归调整

weights = [d[1] for d in historical_data[-7:]]

calories = [d[2] for d in historical_data[-7:]]

# 计算实际与预测的偏差

actual_changes = np.diff(weights)

# 返回调整后的预测

return [w + np.mean(actual_changes) * learning_rate for w in weights[-7:]]

class NutritionAdvisor:

"""

营养建议专家系统

基于规则库提供个性化建议

"""

def __init__(self):

self.rules = self._load_rules()

def _load_rules(self) -> Dict:

"""加载专家规则"""

return {

"high_carb_low_protein": {

"condition": lambda data: data.get('carb_ratio', 0) > 0.6 and data.get('protein_ratio', 0) < 0.15,

"advice": "碳水摄入过高,蛋白质不足。建议增加蛋白质食物如鸡胸肉、鱼、豆制品,减少精制碳水。",

"priority": 2

},

"low_calorie_intake": {

"condition": lambda data: data.get('total_calories', 0) < 1200,

"advice": "热量摄入过低,可能影响新陈代谢。建议适当增加健康食物摄入。",

"priority": 1

},

"high_fat_intake": {

"condition": lambda data: data.get('fat_ratio', 0) > 0.35,

"advice": "脂肪摄入比例偏高。建议减少油炸食品,选择健康脂肪如坚果、牛油果。",

"priority": 2

},

"insufficient_vegetables": {

"condition": lambda data: data.get('veggie_servings', 0) < 3,

"advice": "蔬菜摄入不足。建议每餐至少包含一份蔬菜,增加膳食纤维摄入。",

"priority": 1

},

"good_balance": {

"condition": lambda data: (

0.45 <= data.get('carb_ratio', 0) <= 0.55 and

0.15 <= data.get('protein_ratio', 0) <= 0.25 and

0.2 <= data.get('fat_ratio', 0) <= 0.3

),

"advice": "营养比例良好,继续保持!",

"priority": 3

}

}

def analyze_diet(self, food_records: List[FoodIntake]) -> List[str]:

"""分析饮食并提供建议"""

if not food_records:

return ["暂无饮食数据,请记录您的饮食"]

# 计算营养素总量

total_calories = sum(f.calories for f in food_records)

total_carbs = sum(f.carbs for f in food_records)

total_protein = sum(f.protein for f in food_records)

total_fat = sum(f.fat for f in food_records)

# 计算比例

carb_ratio = total_carbs * 4 / total_calories if total_calories > 0 else 0

protein_ratio = total_protein * 4 / total_calories if total_calories > 0 else 0

fat_ratio = total_fat * 9 / total_calories if total_calories > 0 else 0

# 蔬菜份数估算

veggie_servings = sum(1 for f in food_records if f.category == FoodCategory.VEGETABLE)

# 准备数据

data = {

'total_calories': total_calories,

'carb_ratio': carb_ratio,

'protein_ratio': protein_ratio,

'fat_ratio': fat_ratio,

'veggie_servings': veggie_servings

}

# 应用规则

triggered_rules = []

for rule_name, rule in self.rules.items():

if rule['condition'](data):

triggered_rules.append((rule['priority'], rule['advice']))

# 按优先级排序

triggered_rules.sort(reverse=True)

return [advice for _, advice in triggered_rules[:3]] # 返回前3条建议

class ExerciseAdvisor:

"""

运动建议专家系统

"""

def analyze_exercise(self,

exercise_records: List[ExerciseRecord],

weight: float,

target_weight: float) -> List[str]:

"""分析运动并提供建议"""

advice_list = []

if not exercise_records:

advice_list.append("暂无运动记录。建议每周至少进行150分钟中等强度有氧运动。")

return advice_list

# 分析最近一周数据

week_ago = datetime.datetime.now() - datetime.timedelta(days=7)

recent_exercises = [e for e in exercise_records if e.timestamp > week_ago]

if not recent_exercises:

advice_list.append("最近一周无运动记录。建议开始规律运动。")

return advice_list

# 计算运动量

total_duration = sum(e.duration for e in recent_exercises)

total_calories = sum(e.calories_burned for e in recent_exercises)

avg_intensity = np.mean([e.intensity for e in recent_exercises])

# 提供建议

if total_duration < 150:

advice_list.append(f"本周运动时长不足(仅{total_duration:.0f}分钟)。建议增加至150分钟以上。")

if avg_intensity < 0.4:

advice_list.append("运动强度偏低。可尝试增加高强度间歇训练(HIIT)。")

if total_calories < 1000:

needed = 7700 * (weight - target_weight) / 0.5

weekly_needed = needed / 10 # 10周目标

advice_list.append(f"为达到目标,建议增加运动消耗,每周约{weekly_needed:.0f}大卡。")

# 多样性建议

exercise_types = set(e.name for e in recent_exercises)

if len(exercise_types) < 2:

advice_list.append("运动类型单一。建议结合有氧、力量和柔韧性训练。")

return advice_list

class WeightManager:

"""

体重管理主类

协调各个模块工作

"""

def __init__(self, data_file: str = "weight_data.json"):

self.data_file = data_file

self.user_profile = None

self.food_records = []

self.exercise_records = []

self.fuzzy_controller = FuzzyController()

self.nutrition_advisor = NutritionAdvisor()

self.exercise_advisor = ExerciseAdvisor()

self.load_data()

def load_data(self):

"""加载数据"""

try:

with open(self.data_file, 'r') as f:

data = json.load(f)

# 这里简化处理,实际需要更复杂的反序列化

except FileNotFoundError:

# 创建新用户示例

self.create_example_user()

def save_data(self):

"""保存数据"""

data = {

'user_profile': self.user_profile.__dict__ if self.user_profile else None,

'food_records': [f.__dict__ for f in self.food_records],

'exercise_records': [e.__dict__ for e in self.exercise_records]

}

with open(self.data_file, 'w') as f:

json.dump(data, f, default=str, indent=2)

def create_example_user(self):

"""创建示例用户"""

self.user_profile = UserProfile(

name="张三",

age=30,

gender="male",

height=175,

initial_weight=80,

target_weight=70,

activity_level=ActivityLevel.MODERATE,

weight_records=[(datetime.date.today(), 80)]

)

def add_food_intake(self, food: FoodIntake):

"""添加食物记录"""

self.food_records.append(food)

self.save_data()

def add_exercise(self, exercise: ExerciseRecord):

"""添加运动记录"""

self.exercise_records.append(exercise)

self.save_data()

def add_weight_record(self, weight: float, date: datetime.date = None):

"""添加体重记录"""

if date is None:

date = datetime.date.today()

if self.user_profile:

self.user_profile.weight_records.append((date, weight))

self.save_data()

def get_daily_summary(self, date: datetime.date = None) -> Dict:

"""获取每日总结"""

if date is None:

date = datetime.date.today()

# 过滤当日数据

day_foods = [f for f in self.food_records

if f.timestamp.date() == date]

day_exercises = [e for e in self.exercise_records

if e.timestamp.date() == date]

# 计算各项指标

total_calories_in = sum(f.calories for f in day_foods)

total_calories_out = sum(e.calories_burned for e in day_exercises)

# 获取建议

nutrition_advice = self.nutrition_advisor.analyze_diet(day_foods)

if self.user_profile:

current_weight = self.user_profile.weight_records[-1][1]

target_weight = self.user_profile.target_weight

exercise_advice = self.exercise_advisor.analyze_exercise(

day_exercises, current_weight, target_weight

)

else:

exercise_advice = []

return {

'date': date,

'total_calories_in': total_calories_in,

'total_calories_out': total_calories_out,

'calorie_balance': total_calories_in - total_calories_out,

'nutrition_advice': nutrition_advice,

'exercise_advice': exercise_advice,

'food_count': len(day_foods),

'exercise_count': len(day_exercises)

}

def predict_weight(self, days: int = 30) -> List[Tuple[datetime.date, float]]:

"""预测体重变化"""

if not self.user_profile:

return []

# 获取平均摄入和消耗

recent_days = 7

recent_foods = self.food_records[-recent_days*3:] # 假设每天3餐

recent_exercises = self.exercise_records[-recent_days*2:] # 假设每天2次运动

if not recent_foods:

avg_calories_in = 2000

else:

avg_calories_in = np.mean([f.calories for f in recent_foods])

if not recent_exercises:

avg_calories_out = 300

else:

avg_calories_out = np.mean([e.calories_burned for e in recent_exercises])

# 创建预测器

predictor = WeightPredictor(self.user_profile)

predictor.prediction_days = days

return predictor.predict_weight_trend(avg_calories_in, avg_calories_out)

def get_bmi_assessment(self) -> Dict:

"""获取BMI评估"""

if not self.user_profile or not self.user_profile.weight_records:

return {}

current_weight = self.user_profile.weight_records[-1][1]

height_m = self.user_profile.height / 100

bmi = current_weight / (height_m ** 2)

fuzzy_assessment = self.fuzzy_controller.fuzzy_weight_assessment(bmi)

return {

'bmi': bmi,

'assessment': fuzzy_assessment,

'weight_status': max(fuzzy_assessment.items(), key=lambda x: x[1])[0]

}

def plot_weight_trend(self, predictions: List[Tuple[datetime.date, float]] = None):

"""绘制体重趋势图"""

if not self.user_profile:

print("暂无用户数据")

return

# 准备数据

dates = [d for d, _ in self.user_profile.weight_records]

weights = [w for _, w in self.user_profile.weight_records]

fig, ax = plt.subplots(figsize=(10, 6))

# 绘制历史数据

if len(dates) > 1:

ax.plot(dates, weights, 'bo-', label='实际体重', linewidth=2, markersize=8)

# 绘制预测数据

if predictions:

pred_dates = [d for d, _ in predictions]

pred_weights = [w for _, w in predictions]

ax.plot(pred_dates, pred_weights, 'r--', label='预测趋势', linewidth=2)

ax.fill_between(pred_dates, pred_weights, weights[-1], alpha=0.2, color='red')

# 目标体重线

ax.axhline(y=self.user_profile.target_weight, color='g',

linestyle=':', label='目标体重', linewidth=2)

# 设置图表

ax.set_xlabel('日期', fontsize=12)

ax.set_ylabel('体重 (kg)', fontsize=12)

ax.set_title('体重变化趋势', fontsize=14, fontweight='bold')

ax.grid(True, alpha=0.3)

ax.legend()

# 格式化x轴

if len(dates) > 5:

plt.xticks(rotation=45)

plt.tight_layout()

plt.savefig('weight_trend.png', dpi=150, bbox_inches='tight')

plt.show()

def main():

"""主程序示例"""

print("=" * 60)

print("智能体重管理系统")

print("=" * 60)

# 初始化管理器

manager = WeightManager()

# 如果无用户,创建示例

if not manager.user_profile:

manager.create_example_user()

print("已创建示例用户数据")

# 显示用户信息

user = manager.user_profile

print(f"\n用户: {user.name}")

print(f"当前体重: {user.weight_records[-1][1]} kg")

print(f"目标体重: {user.target_weight} kg")

print(f"需要减重: {user.weight_records[-1][1] - user.target_weight:.1f} kg")

# BMI评估

bmi_info = manager.get_bmi_assessment()

if bmi_info:

print(f"\nBMI指数: {bmi_info['bmi']:.1f}")

print(f"体重状态: {bmi_info['weight_status']}")

# 添加示例数据

today = datetime.datetime.now()

# 添加食物记录

breakfast = FoodIntake(

name="燕麦粥+鸡蛋",

category=FoodCategory.CARBOHYDRATE,

calories=350,

protein=15,

carbs=45,

fat=8,

timestamp=today.replace(hour=8, minute=0)

)

lunch = FoodIntake(

name="鸡胸肉沙拉",

category=FoodCategory.PROTEIN,

calories=450,

protein=35,

carbs=20,

fat=15,

timestamp=today.replace(hour=12, minute=30)

)

manager.add_food_intake(breakfast)

manager.add_food_intake(lunch)

# 添加运动记录

exercise = ExerciseRecord(

name="跑步",

duration=30,

calories_burned=300,

intensity=0.7,

timestamp=today.replace(hour=18, minute=0)

)

manager.add_exercise(exercise)

# 获取每日总结

summary = manager.get_daily_summary()

print(f"\n📊 今日总结 ({summary['date']})")

print(f" 摄入热量: {summary['total_calories_in']:.0f} 大卡")

print(f" 消耗热量: {summary['total_calories_out']:.0f} 大卡")

print(f" 热量平衡: {summary['calorie_balance']:+.0f} 大卡")

# 显示建议

if summary['nutrition_advice']:

print(f"\n🍎 营养建议:")

for i, advice in enumerate(summary['nutrition_advice'], 1):

print(f" {i}. {advice}")

if summary['exercise_advice']:

print(f"\n🏃 运动建议:")

for i, advice in enumerate(summary['exercise_advice'], 1):

print(f" {i}. {advice}")

# 预测体重

print(f"\n🔮 未来30天体重预测:")

predictions = manager.predict_weight(30)

if predictions:

print(f" 当前: {user.weight_records[-1][1]:.1f} kg")

print(f" 30天后预测: {predictions[-1][1]:.1f} kg")

print(f" 预测减重: {user.weight_records[-1][1] - predictions[-1][1]:.1f} kg")

# 计算预计达到目标时间

current =

如果你觉得这个工具好用,欢迎关注我!

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/1/14 20:50:34

年会抽奖新纪元:用3D球体系统打造难忘的颁奖时刻

年会抽奖新纪元&#xff1a;用3D球体系统打造难忘的颁奖时刻 【免费下载链接】log-lottery &#x1f388;&#x1f388;&#x1f388;&#x1f388;年会抽奖程序&#xff0c;threejsvue3 3D球体动态抽奖应用。 项目地址: https://gitcode.com/gh_mirrors/lo/log-lottery …

作者头像 李华
网站建设 2026/1/15 3:21:58

Brave浏览器隐私保护深度解析:你的数字安全堡垒

Brave浏览器隐私保护深度解析&#xff1a;你的数字安全堡垒 【免费下载链接】brave-browser Brave browser for Android, iOS, Linux, macOS, Windows. 项目地址: https://gitcode.com/GitHub_Trending/br/brave-browser 在当今互联网时代&#xff0c;每一次点击都可能成…

作者头像 李华
网站建设 2026/1/19 14:30:01

突破性实战:从数据预处理到缺失值插补的完整解决方案

突破性实战&#xff1a;从数据预处理到缺失值插补的完整解决方案 【免费下载链接】machine-learning-yearning-cn 项目地址: https://gitcode.com/gh_mirrors/mac/machine-learning-yearning-cn 在机器学习项目的完整流程中&#xff0c;数据预处理是决定模型成败的关键…

作者头像 李华
网站建设 2026/1/11 18:00:47

跨平台中文字体优化:实现完美显示效果的终极指南

跨平台中文字体优化&#xff1a;实现完美显示效果的终极指南 【免费下载链接】PingFangSC PingFangSC字体包文件、苹果平方字体文件&#xff0c;包含ttf和woff2格式 项目地址: https://gitcode.com/gh_mirrors/pi/PingFangSC 在当今多设备、多平台的时代&#xff0c;字体…

作者头像 李华
网站建设 2026/1/21 2:08:13

Wake-On-LAN 远程唤醒工具终极使用指南:轻松掌握网络开机技术

Wake-On-LAN 远程唤醒工具终极使用指南&#xff1a;轻松掌握网络开机技术 【免费下载链接】wol &#x1f9ad; Wake up your devices with a single command or click. A Wake-On-LAN tool that works via CLI and web interface. 项目地址: https://gitcode.com/gh_mirrors/…

作者头像 李华
网站建设 2026/1/11 13:59:30

AMD ROCm深度学习环境搭建:从入门到精通的完整指南

AMD ROCm深度学习环境搭建&#xff1a;从入门到精通的完整指南 【免费下载链接】ROCm AMD ROCm™ Software - GitHub Home 项目地址: https://gitcode.com/GitHub_Trending/ro/ROCm 想要在Windows系统上充分发挥AMD显卡的深度学习潜力&#xff1f;本指南将带你从零开始构…

作者头像 李华