Spaces:
Runtime error
Runtime error
| # import numpy as np | |
| # import pandas as pd | |
| # from sklearn.model_selection import train_test_split | |
| # from sklearn.neural_network import MLPRegressor | |
| # from sklearn.preprocessing import StandardScaler | |
| # # Step 1: Create random food data | |
| # def create_random_food_data(num_samples=100): | |
| # np.random.seed(42) | |
| # areas = ['American', 'Mexican', 'Italian', 'Indian', 'Chinese'] | |
| # categories = ['Beef', 'Chicken', 'Vegetarian', 'Seafood', 'Pork'] | |
| # vegetarian_categories = ['Vegetarian'] | |
| # data = [] | |
| # for _ in range(num_samples): | |
| # area = np.random.choice(areas) | |
| # category = np.random.choice(categories) | |
| # ingredients_count = np.random.randint(3, 10) | |
| # calories = np.random.randint(200, 600) | |
| # protein = np.random.randint(10, 40) | |
| # carbs = np.random.randint(20, 70) | |
| # fats = np.random.randint(5, 30) | |
| # data.append([area, category, ingredients_count, calories, protein, carbs, fats]) | |
| # df = pd.DataFrame(data, columns=['Area', 'Category', 'IngredientsCount', 'Calories', 'Protein', 'Carbs', 'Fats']) | |
| # return df | |
| # # Step 2: Preprocess the Data | |
| # def preprocess_data(df): | |
| # features = df[['Area', 'Category', 'IngredientsCount']] | |
| # targets = df[['Calories', 'Protein', 'Carbs', 'Fats']] | |
| # # Encode categorical variables | |
| # features = pd.get_dummies(features, columns=['Area', 'Category']) | |
| # return features, targets | |
| # # Step 3: Train the MLP Model | |
| # def train_mlp_model(X, y): | |
| # # Split data into training and test sets | |
| # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) | |
| # # Standardize the features | |
| # scaler = StandardScaler() | |
| # X_train_scaled = scaler.fit_transform(X_train) | |
| # X_test_scaled = scaler.transform(X_test) | |
| # # Initialize and train the MLP model | |
| # mlp_model = MLPRegressor(hidden_layer_sizes=(100, 50), max_iter=500, random_state=42) | |
| # mlp_model.fit(X_train_scaled, y_train) | |
| # return mlp_model, scaler | |
| # # Step 4: Generate Diet Plan | |
| # def generate_diet_plan(mlp_model, scaler, total_calories, num_meals, region, diet_preference, foods_df): | |
| # meal_names = ['Breakfast', 'Morning Snack', 'Lunch', 'Afternoon Snack', 'Dinner'] | |
| # calorie_distribution = [0.25, 0.10, 0.35, 0.10, 0.20] | |
| # # Adjust the distribution if number of meals is less than 5 | |
| # if num_meals < 5: | |
| # calorie_distribution = calorie_distribution[:num_meals] | |
| # calorie_distribution = [x / sum(calorie_distribution) for x in calorie_distribution] | |
| # elif num_meals > 5: | |
| # # Evenly distribute the remaining calories across the extra meals | |
| # extra_meals = num_meals - 5 | |
| # extra_meal_calories = (sum(calorie_distribution) - 1) / extra_meals | |
| # calorie_distribution.extend([extra_meal_calories] * extra_meals) | |
| # calorie_distribution = [x / sum(calorie_distribution) for x in calorie_distribution] | |
| # meal_names.extend([f'Extra Meal {i+1}' for i in range(extra_meals)]) | |
| # diet_plan = [] | |
| # # Filter foods based on the user's region and diet preference | |
| # if diet_preference == 'Vegetarian': | |
| # region_foods = foods_df[(foods_df['Area'] == region) & (foods_df['Category'] == 'Vegetarian')] | |
| # else: | |
| # region_foods = foods_df[foods_df['Area'] == region] | |
| # for i in range(num_meals): | |
| # # Randomly select a food from the filtered region and preference | |
| # food = region_foods.sample(1).iloc[0] | |
| # # Adjust the portion to meet the meal calorie requirement | |
| # portion_factor = (total_calories * calorie_distribution[i]) / food['Calories'] | |
| # diet_plan.append({ | |
| # 'Meal': meal_names[i % len(meal_names)], | |
| # 'Food': food['Category'], | |
| # 'Area': food['Area'], | |
| # 'IngredientsCount': food['IngredientsCount'], | |
| # 'Calories': food['Calories'] * portion_factor, | |
| # 'Protein': food['Protein'] * portion_factor, | |
| # 'Carbs': food['Carbs'] * portion_factor, | |
| # 'Fats': food['Fats'] * portion_factor | |
| # }) | |
| # return diet_plan | |
| # # Main Function | |
| # if __name__ == "__main__": | |
| # # Create random food data | |
| # foods_df = create_random_food_data() | |
| # # Preprocess the data | |
| # X, y = preprocess_data(foods_df) | |
| # # Train the MLP model | |
| # mlp_model, scaler = train_mlp_model(X, y) | |
| # # Get user input | |
| # total_calories = float(input("Enter the total daily calories you want to consume: ")) | |
| # num_meals = int(input("Enter the number of meals per day: ")) | |
| # region = input("Enter your region (American, Mexican, Italian, Indian, Chinese): ") | |
| # diet_preference = input("Enter your diet preference (Vegetarian, Non-Vegetarian): ") | |
| # # Generate and print the diet plan | |
| # diet_plan = generate_diet_plan(mlp_model, scaler, total_calories, num_meals, region, diet_preference, foods_df) | |
| # for meal in diet_plan: | |
| # print(f"{meal['Meal']}: {meal['Food']} ({meal['Area']}) - {meal['Calories']:.2f} kcal, " | |
| # f"{meal['Protein']:.2f}g protein, {meal['Carbs']:.2f}g carbs, {meal['Fats']:.2f}g fats") | |
| import requests | |
| import numpy as np | |
| import pandas as pd | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.neural_network import MLPRegressor | |
| from sklearn.preprocessing import StandardScaler | |
| from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error | |
| # Step 1: Fetch Food Data from TheMealDB API | |
| def fetch_mealdb_data(): | |
| meals = [] | |
| for letter in 'abcdefghijklmnopqrstuvwxyz': | |
| url = f'https://www.themealdb.com/api/json/v1/1/search.php?f={letter}' | |
| response = requests.get(url) | |
| data = response.json() | |
| if data['meals']: | |
| meals.extend(data['meals']) | |
| return meals | |
| # Step 2: Preprocess the Data | |
| # def preprocess_data(meals): | |
| # features = [] | |
| # targets = [] | |
| # for meal in meals: | |
| # area = meal['strArea'] if meal['strArea'] else 'Unknown' | |
| # category = meal['strCategory'] if meal['strCategory'] else 'Unknown' | |
| # meal_type = np.random.choice(['Breakfast', 'Lunch', 'Dinner', 'Snack']) | |
| # ingredients_count = sum([1 for i in range(1, 21) if meal[f'strIngredient{i}']]) | |
| # # Example target values (you can replace these with real data) | |
| # calories = np.random.randint(200, 600) | |
| # protein = np.random.randint(10, 40) | |
| # carbs = np.random.randint(20, 70) | |
| # fats = np.random.randint(5, 30) | |
| # features.append([area, category, meal_type, ingredients_count]) | |
| # targets.append([calories, protein, carbs, fats]) | |
| # feature_df = pd.DataFrame(features, columns=['Area', 'Category', 'MealType', 'IngredientsCount']) | |
| # target_df = pd.DataFrame(targets, columns=['Calories', 'Protein', 'Carbs', 'Fats']) | |
| # # Encode categorical variables | |
| # feature_df = pd.get_dummies(feature_df, columns=['Area', 'Category', 'MealType']) | |
| # return feature_df, target_df | |
| def preprocess_data(meals): | |
| features = [] | |
| targets = [] | |
| for meal in meals: | |
| area = meal['strArea'] if meal['strArea'] else 'Unknown' | |
| category = meal['strCategory'] if meal['strCategory'] else 'Unknown' | |
| meal_type = np.random.choice(['Breakfast', 'Lunch', 'Dinner', 'Snack']) | |
| ingredients_count = sum([1 for i in range(1, 21) if meal[f'strIngredient{i}']]) | |
| meal_name = meal['strMeal'] if meal['strMeal'] else 'Unknown' # Add meal name | |
| # Example target values (replace with real data if available) | |
| calories = np.random.randint(200, 600) | |
| protein = np.random.randint(10, 40) | |
| carbs = np.random.randint(20, 70) | |
| fats = np.random.randint(5, 30) | |
| # Include meal_name in features | |
| features.append([meal_name, area, category, meal_type, ingredients_count]) | |
| targets.append([calories, protein, carbs, fats]) | |
| feature_df = pd.DataFrame(features, columns=['MealName', 'Area', 'Category', 'MealType', 'IngredientsCount']) | |
| target_df = pd.DataFrame(targets, columns=['Calories', 'Protein', 'Carbs', 'Fats']) | |
| # Encode categorical variables except MealName | |
| feature_df = pd.get_dummies(feature_df, columns=['Area', 'Category', 'MealType']) | |
| return feature_df, target_df | |
| # Step 3: Train the MLP Model | |
| def train_mlp_model(X, y): | |
| numeric_X = X.select_dtypes(include=[np.number]) | |
| X_train, X_test, y_train, y_test = train_test_split(numeric_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) | |
| mlp_model = MLPRegressor(hidden_layer_sizes=(150, 100, 50), activation='relu', solver='adam', max_iter=1000, random_state=42) | |
| mlp_model.fit(X_train_scaled, y_train) | |
| y_pred = mlp_model.predict(X_test_scaled) | |
| mse = mean_squared_error(y_test, y_pred) | |
| r2 = r2_score(y_test, y_pred) | |
| mae = mean_absolute_error(y_test, y_pred) | |
| print(f"Model Performance:") | |
| print(f"Mean Squared Error (MSE): {mse:.2f}") | |
| print(f"R-squared (R²): {r2:.2f}") | |
| print(f"Mean Absolute Error (MAE): {mae:.2f}") | |
| return mlp_model, scaler | |
| # Step 4: Generate Diet Plan | |
| def generate_diet_plan(mlp_model, scaler, total_calories, num_meals, region, diet_preference, foods_df): | |
| meal_names = ['Breakfast', 'Morning Snack', 'Lunch', 'Afternoon Snack', 'Dinner'] | |
| calorie_distribution = [0.25, 0.10, 0.35, 0.10, 0.20] | |
| if num_meals < 5: | |
| calorie_distribution = calorie_distribution[:num_meals] | |
| calorie_distribution = [x / sum(calorie_distribution) for x in calorie_distribution] | |
| elif num_meals > 5: | |
| extra_meals = num_meals - 5 | |
| extra_meal_calories = (sum(calorie_distribution) - 1) / extra_meals | |
| calorie_distribution.extend([extra_meal_calories] * extra_meals) | |
| calorie_distribution = [x / sum(calorie_distribution) for x in calorie_distribution] | |
| meal_names.extend([f'Extra Meal {i+1}' for i in range(extra_meals)]) | |
| diet_plan = [] | |
| if diet_preference == 'Vegetarian': | |
| region_foods = foods_df[(foods_df['Area'] == region) & (foods_df['Category'] == 'Vegetarian')] | |
| else: | |
| region_foods = foods_df[foods_df['Area'] == region] | |
| for i in range(num_meals): | |
| meal_type = meal_names[i % len(meal_names)] | |
| meal_foods = region_foods[region_foods['MealType'] == meal_type] | |
| if meal_foods.empty: | |
| continue | |
| food = meal_foods.sample(1).iloc[0] | |
| portion_factor = (total_calories * calorie_distribution[i]) / food['Calories'] | |
| diet_plan.append({ | |
| 'Meal': meal_type, | |
| 'Food': food['Category'], | |
| 'Area': food['Area'], | |
| 'IngredientsCount': food['IngredientsCount'], | |
| 'Calories': food['Calories'] * portion_factor, | |
| 'Protein': food['Protein'] * portion_factor, | |
| 'Carbs': food['Carbs'] * portion_factor, | |
| 'Fats': food['Fats'] * portion_factor | |
| }) | |
| return diet_plan | |
| # Main Function | |
| if __name__ == "__main__": | |
| meals = fetch_mealdb_data() | |
| X, y = preprocess_data(meals) | |
| mlp_model, scaler = train_mlp_model(X, y) | |
| total_calories = float(input("Enter the total daily calories you want to consume: ")) | |
| num_meals = int(input("Enter the number of meals per day: ")) | |
| region = input("Enter your region (American, Mexican, Italian, Indian, Chinese): ") | |
| diet_preference = input("Enter your diet preference (Vegetarian, Non-Vegetarian): ") | |
| diet_plan = generate_diet_plan(mlp_model, scaler, total_calories, num_meals, region, diet_preference, X) | |
| for meal in diet_plan: | |
| print(f"{meal['Meal']}: {meal['Food']} ({meal['Area']}) - {meal['Calories']:.2f} kcal, " | |
| f"{meal['Protein']:.2f}g protein, {meal['Carbs']:.2f}g carbs, {meal['Fats']:.2f}g fats") | |