Shivya0410's picture
Create app.py
27132ea verified
Raw History Blame Contribute Delete
15.4 kB
# Download latest version
path = kagglehub.dataset_download("irkaal/foodcom-recipes-and-reviews") # Changed this line to only include the dataset handle
# Access the recipes.csv file within the downloaded dataset
recipes_csv_path = os.path.join(path, "recipes.csv")
dataset_dir = '/root/.cache/kagglehub/datasets/irkaal/foodcom-recipes-and-reviews/versions/2/' # Changed to the directory containing recipes.csv
# Find the CSV file within the directory
for filename in os.listdir(dataset_dir):
if filename.endswith('.csv'):
csv_file = os.path.join(dataset_dir, filename)
break
# Load the dataset from the identified CSV file
data = pd.read_csv(recipes_csv_path)
df = data.copy()
# Select and reorder columns in the dataset for further analysis
selected_columns = ['RecipeId', 'Calories', 'FatContent', 'SaturatedFatContent',
'CholesterolContent', 'SodiumContent', 'CarbohydrateContent',
'FiberContent', 'SugarContent', 'ProteinContent']
# Check if all selected columns exist in the DataFrame
missing_columns = [col for col in selected_columns if col not in df.columns]
if missing_columns:
print(f"The following columns are not in the DataFrame: {missing_columns}")
# Option 1: Raise an error to stop execution
# raise KeyError(f"Missing columns: {missing_columns}")
# Option 2: Select only the available columns
selected_columns = [col for col in selected_columns if col in df.columns]
print(f"Proceeding with available columns: {selected_columns}")
# Apply the selected columns to the DataFrame
df = df[selected_columns]
# Display summary statistics of the DataFrame, including specified percentiles
# Transpose the result for better readability
summary_statistics = df.describe(percentiles=[0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95]).T
# Define the columns to filter based on the 95th percentile
# Ensure these column names exactly match the names in your DataFrame
# Check for case sensitivity and typos
filter_columns = ['Calories', 'FatContent', 'SaturatedFatContent',
'CholesterolContent', 'SodiumContent',
'CarbohydrateContent', 'FiberContent',
'SugarContent', 'ProteinContent']
# Before calculating quantiles, check if the columns exist in the DataFrame:
for column in filter_columns:
if column not in df.columns:
print(f"Column '{column}' not found in DataFrame. Please check the column names.")
# You might want to raise an exception or handle the missing column in a way that suits your needs.
# Compute the 95th percentile values for each specified column
percentile_95_thresholds = df[filter_columns].quantile(0.95)
# Apply filtering to the DataFrame based on the 95th percentile values
filtered_df = df[(df[filter_columns] <= percentile_95_thresholds).all(axis=1)]
# Drop the 'RecipeId' column from the DataFrame and assign the result to X
X = df.drop(columns=['RecipeId'])
# Assign the 'RecipeId' column to y
y = df['RecipeId']
# Initialize the MinMaxScaler
scaler = MinMaxScaler()
# Fit the scaler to X and transform it
X_scaled = scaler.fit_transform(X)
# Split the already scaled data into training and evaluation sets
X_train_scaled, X_eval_scaled = train_test_split(X_scaled, train_size=0.8, random_state=42)
# Neural Network Model Architecture
num_features = X_train_scaled.shape[1] # Number of features in the input data
# Define the autoencoder model
model = Sequential([
# Encoder
Dense(256, input_shape=(num_features,)), # Input layer with 256 neurons
LeakyReLU(), # Activation function with a small slope for negative inputs
Dropout(0.2), # Dropout layer with 20% dropout rate to prevent overfitting
Dense(128), # Hidden layer with 128 neurons
LeakyReLU(), # Activation function
Dropout(0.2), # Dropout layer
Dense(64), # Hidden layer with 64 neurons
LeakyReLU(), # Activation function
Dropout(0.2), # Dropout layer
# Bottleneck
Dense(32), # Bottleneck layer with 32 neurons, this is the compressed representation of the input data
# The bottleneck layer reduces the dimensionality of the input data, capturing essential features
# Decoder
Dense(64), # Hidden layer in the decoder with 64 neurons
LeakyReLU(), # Activation function
Dropout(0.2), # Dropout layer
Dense(128), # Hidden layer with 128 neurons
LeakyReLU(), # Activation function
Dropout(0.2), # Dropout layer
Dense(256), # Hidden layer with 256 neurons
LeakyReLU(), # Activation function
# Output layer
Dense(num_features, activation='linear') # Output layer with the same number of neurons as features, linear activation
# The linear activation function in the output layer allows the network to reconstruct the input data directly
])
# Define the optimizer with a learning rate
optimizer = Adam(learning_rate=0.0001)
# Compile the model
model.compile(optimizer=optimizer,
loss='mse', # Mean Squared Error for regression
metrics=['mae']) # Mean Absolute Error for regression evaluation
# Fit the model with scaled training data as both input and target
training_history = model.fit(X_train_scaled, X_train_scaled,
validation_data=(X_eval_scaled, X_eval_scaled),
epochs=10)
# Extract validation loss from the training history
validation_loss = training_history.history['val_loss']
# Predict latent features using the trained model
predicted_latent_features = model.predict(X_scaled)
# Manual calculation of cosine similarity
# Compute the Dot Product:
# This calculates the dot product between each pair of latent feature vectors.
# The result is a matrix where each entry represents the dot product (or similarity) between two feature vectors.
similarity_matrix = np.dot(predicted_latent_features, predicted_latent_features.T)
# Calculate the Norms:
# The norm (or magnitude) of each latent feature vector is calculated.
# 'axis=1' indicates that the norm is computed for each row (each feature vector).
# 'keepdims=True' keeps the dimensions of the output the same for broadcasting purposes.
norms = np.linalg.norm(predicted_latent_features, axis=1, keepdims=True)
# Normalize the Similarity Matrix:
# Each entry in the similarity matrix is divided by the product of the norms of the vectors being compared.
# This normalizes the similarity scores to cosine similarity, which ranges from -1 to 1.
similarity_matrix /= np.dot(norms, norms.T)
similarity_matrix_sklearn = cosine_similarity(predicted_latent_features)
# Initialize a dictionary to store recommendations
recommendations_dict = {}
# Iterate over each item in the dataset
for item_index in range(len(X_scaled)):
# Sort indices based on similarity in descending order
sorted_indices = similarity_matrix[item_index].argsort()[::-1]
# Create a list of tuples with similarity scores and indices, excluding the item itself
similar_items_list = [(similarity_matrix[item_index][idx], idx) for idx in sorted_indices if idx != item_index]
# Store the list of similar items for the current item in the recommendations dictionary
recommendations_dict[item_index] = similar_items_list
# Calculate Basal Metabolic Rate (BMR)
def compute_bmr(gender, body_weight, body_height, age):
"""
Calculate Basal Metabolic Rate (BMR) based on gender, body weight, body height, and age.
Args:
gender (str): Gender of the individual ('male' or 'female').
body_weight (float): Body weight of the individual in kilograms.
body_height (float): Body height of the individual in centimeters.
age (int): Age of the individual in years.
Return:
float: Basal Metabolic Rate (BMR) value.
"""
if gender == 'male':
# For Men: BMR = (10 x weight in kg) + (6.25 x height in cm) - (5 x age in years) + 5
bmr_value = 10 * body_weight + 6.25 * body_height - 5 * age + 5
elif gender == 'female':
# For Women: BMR = (10 x weight in kg) + (6.25 x height in cm) - (5 x age in years) - 161
bmr_value = 10 * body_weight + 6.25 * body_height - 5 * age - 161
else:
raise ValueError("Invalid gender. Please choose 'male' or 'female'.")
return bmr_value
def compute_daily_caloric_intake(bmr, activity_intensity, objective):
"""
Calculate total daily caloric intake based on Basal Metabolic Rate (BMR), activity level, and personal goal.
Args:
bmr (float): Basal Metabolic Rate (BMR) value.
activity_intensity (str): Activity level of the individual ('sedentary', 'lightly_active', 'moderately_active', 'very_active', 'extra_active').
objective (str): Personal goal of the individual ('weight_loss', 'muscle_gain', 'health_maintenance').
Return:
int: Total daily caloric intake.
"""
# Define activity multipliers based on intensity
intensity_multipliers = {
'sedentary': 1.2,
'lightly_active': 1.375,
'moderately_active': 1.55,
'very_active': 1.725,
'extra_active': 1.9
}
# Define goal adjustments based on objective
objective_adjustments = {
'weight_loss': 0.8,
'muscle_gain': 1.2,
'health_maintenance': 1
}
# Calculate maintenance calories based on activity intensity
maintenance_calories = bmr * intensity_multipliers[activity_intensity]
# Adjust maintenance calories based on personal objective
total_caloric_intake = maintenance_calories * objective_adjustments[objective]
return round(total_caloric_intake)
def suggest_recipes(category, body_weight, body_height, age, activity_intensity, objective):
"""
Generate food recommendations based on the user's profile and dietary goals.
Args:
category (str): Gender category of the user ('male' or 'female').
body_weight (float): Weight of the user in kilograms.
body_height (float): Height of the user in centimeters.
age (int): Age of the user in years.
activity_intensity (str): Physical activity level of the user ('sedentary', 'lightly_active', 'moderately_active', 'very_active', 'extra_active').
objective (str): Dietary objective of the user ('weight_loss', 'muscle_gain', 'health_maintenance').
Return:
pd.DataFrame: Recommended recipes including name and calorie content.
"""
# Calculate the Basal Metabolic Rate (BMR) for the user
bmr = compute_bmr(category, body_weight, body_height, age)
# Calculate the total daily caloric intake based on activity intensity and dietary objective
total_calories = compute_daily_caloric_intake(bmr, activity_intensity, objective)
# Prepare input data for the model with desired total calories
user_input_features = np.array([[total_calories, 0, 0, 0, 0, 0, 0, 0, 0]])
# Scale the input data to match the model's training scale
scaled_input_features = scaler.transform(user_input_features)
# Predict latent features for the input data
predicted_latent_features = model.predict(scaled_input_features)
# Find the index with the highest prediction probability
top_prediction_index = np.argmax(predicted_latent_features.flatten())
# Retrieve recommended recipes based on the highest prediction
similar_recipe_indices = np.array(recommendations_dict[top_prediction_index])
recommended_recipes = data.iloc[similar_recipe_indices[:, 1].astype(int)][['Name', 'Calories']]
return recommended_recipes.head(5)
# Define the input values
user_category = 'male'
user_body_weight = 80 # in kilograms
user_body_height = 170 # in centimeters
user_age = 50 # in years
user_activity_intensity = 'moderately_active'
user_objective = 'weight_loss'
# Generate suggested recipes
suggested_recipes = suggest_recipes(
category=user_category,
body_weight=user_body_weight,
body_height=user_body_height,
age=user_age,
activity_intensity=user_activity_intensity,
objective=user_objective
)
# Calculate required daily calories
required_calories = compute_daily_caloric_intake(
bmr=compute_bmr(user_category, user_body_weight, user_body_height, user_age),
activity_intensity=user_activity_intensity,
objective=user_objective
)
# Function to calculate BMR
def compute_bmr(gender, body_weight, body_height, age):
if gender == 'male':
return 10 * body_weight + 6.25 * body_height - 5 * age + 5
elif gender == 'female':
return 10 * body_weight + 6.25 * body_height - 5 * age - 161
else:
raise ValueError("Invalid gender. Choose 'male' or 'female'.")
# Function to calculate daily caloric intake
def compute_daily_caloric_intake(bmr, activity_intensity, objective):
intensity_multipliers = {
'sedentary': 1.2,
'lightly_active': 1.375,
'moderately_active': 1.55,
'very_active': 1.725,
'extra_active': 1.9
}
objective_adjustments = {
'weight_loss': 0.8,
'muscle_gain': 1.2,
'health_maintenance': 1
}
maintenance_calories = bmr * intensity_multipliers[activity_intensity]
return round(maintenance_calories * objective_adjustments[objective])
# Function to suggest recipes
def suggest_recipes(category, body_weight, body_height, age, activity_intensity, objective):
# Calculate BMR and daily caloric intake
bmr = compute_bmr(category, body_weight, body_height, age)
total_calories = compute_daily_caloric_intake(bmr, activity_intensity, objective)
# Prepare input for the model
user_input_features = np.array([[total_calories, 0, 0, 0, 0, 0, 0, 0, 0]])
scaled_input_features = scaler.transform(user_input_features)
# Predict latent features
predicted_latent_features = model.predict(scaled_input_features)
# Find recommendations
top_prediction_index = np.argmax(predicted_latent_features.flatten())
similar_recipe_indices = np.array(recommendations_dict[top_prediction_index])
recommended_recipes = data.iloc[similar_recipe_indices[:, 1].astype(int)][['Name', 'Calories']]
# Return the top 5 suggested recipes
return recommended_recipes.head(5).to_dict(orient='records')
# Define the Gradio interface function
def gradio_diet_recommender(category, body_weight, body_height, age, activity_intensity, objective):
try:
recommendations = suggest_recipes(category, body_weight, body_height, age, activity_intensity, objective)
result = f"Top Recommended Recipes:\n\n"
for idx, recipe in enumerate(recommendations):
result += f"{idx + 1}. {recipe['Name']} - {recipe['Calories']} Calories\n"
return result
except Exception as e:
return str(e)
# Create the Gradio interface
interface = gr.Interface(
fn=gradio_diet_recommender,
inputs=[
gr.Radio(choices=['male', 'female'], label="Gender"),
gr.Number(label="Body Weight (kg)"),
gr.Number(label="Body Height (cm)"),
gr.Number(label="Age (years)"),
gr.Dropdown(choices=['sedentary', 'lightly_active', 'moderately_active', 'very_active', 'extra_active'], label="Activity Intensity"),
gr.Dropdown(choices=['weight_loss', 'muscle_gain', 'health_maintenance'], label="Objective")
],
outputs="text",
title="Diet Recommender System",
description="Provide your details to receive a customized diet plan."
)
# Launch the Gradio app
interface.launch()