<jupyter_start><jupyter_text>Programming for Data Analysis Weight gain and hormonal imbalance in women  IntroductionWeight gain is an increase in body weight. This can involve an increase in muscle mass, fat deposits, excess fluids such as water or other factors. Weight gain can be a symptom of a serious medical condition (en.wikipedia.org).It is a multifaceted problem with many contributing factors including but not limited to genetics, hormone levels, overconsumption of food, and sedentary lifestyle (www.ncbi.nlm).Hormones are the body's chemical messengers. They carry vital information to the cells through blood. Typically, hormones affect only certain cells, or target cells. They are produced by the endocrine glands and travel through the bloodstream to various tissues and organs. Each hormone has its own specific goal, carrying a key message to certain parts of the body. The body's hormones are essentially responsible for controlling and balancing nearly every major system. Hormones impact your growth and development, control your mood, determine how you will handle stress, and influence how the body breaks down food (www.vivo.colostate.edu). All these aspects could have influence on your weight. As the human body is extremely complicated, there are certainly more features that could influence changes in your weight but in this project I will focus only on hormonal imbalance conditions that could have impact on someone's weight taking into consideration other relevant characteristics like age and Body Mass index and look into their relationship. In the next few paragraphs I will give better overview of weight gain and conditions that could influence it and types of hormonal imbalance that could have negative impact on weight gain.  Previous findings on hormonal imbalance and weight gainWhat are the different types of hormones?Endocrine glands are located throughout the body. These glands include:- Hypothalamus: controls thirst, hunger, sleep, sex drive, moods, body temperature, and the release of other hormones- Parathyroid: controls calcium- Thymus: controls the adaptive immune system- Pancreas: controls blood sugar levels- Thyroid: controls heart rate and calorie burn- Adrenal: controls stress and sex drive- Pituitary: controls growth- Pineal: controls sleep- Ovaries, in women: controls female sex hormonesThere are several different types of hormones in a body. When you have a hormonal imbalance, you may have a problem in one of more of these glands. The specific hormone that's imbalanced will determine the signs and symptoms that you experience as a result (www.hormone.org).Weight gain develops gradually from poor diet and lifestyle choices and, medical conditions and to some extent, from your genes. According to Irish Health Service Executive (Feidhmeannacht na Seirbhise Slainte, hse.ie) there are 4 main reasons why people gain weight. I will detail each of them below.  Lifestyle choicesLifestyle choices are an important factor in influencing weight. Eating more calories than you need may be down to unhealthy food choices. For example, unhealthy food choices could be:- eating processed or fast food - drinking too much alcohol- not eating fruit, vegetables and unrefined carbohydrates- eating larger portions than you need Lack of physical activityLack of physical activity is another important factor that is related to weight gain. Many people have jobs that involve sitting at a desk for most of the day, and rely heavily on their cars to get around. When it is time to relax, people tend to watch TV, or play computer games, and rarely take any regular exercise.If you are not active enough, you do not use up the energy provided by the food you eat, and the extra calories are stored as fat instead.The National Guidelines on Physical Activity for Ireland recommend that adults do at least 150 minutes (2 hours and 30 minutes) of moderate-intensity aerobic activity (i.e. cycling or fast walking) every week (www.gov.ie). GenesSome people tend to stay the same weight for years without much effort, whereas others find they put on weight quickly if they are not careful about what they eat. This could be due, in part, to genes.Some genetic conditions can increase appetite, so people end up eating too much. There are also genes that determine how much fat your body stores. A particular genetic variation could mean that your body is more likely to store fat than somebody else's.  Medical reasonsMedical conditions that can cause weight gain include:- Cushing's syndrome - a rare disorder that causes an over-production of steroid hormones (chemicals produced by the body),- an under-active thyroid gland (hypothyroidism) - when your thyroid gland does not produce enough thyroid hormone (called thyroxine, or T4), and- polycystic ovary syndrome (PCOS) - when women have a large number of cysts in their ovaries.- Certain medicines, including some corticosteroids and antidepressants, can also contribute to weight gain. Weight gain can also be a side effect of taking the combined contraceptive pill, and from quitting smoking.(www.mayoclinic.org)In this work I will focus only on weight changes that are related to hormonal imbalance. As we can see above, there are a lot of reasons why a person can gain some weight, from life style, genes or medical conditions. There is variety of hormones that regulate our body, but not all of them have a negative impact on our weight gain. According to various researchers most common hormones that can influence our body are: 1. EstrogenIt should be noted that both low and high levels of estrogen can lead to weight gain. Overproduction of estrogen by the ovarian calls or eating food rich in estrogen can cause high estrogen levels. A healthy body produces desired amount of insulin and keeps blood sugar levels in check. However, high levels of estrogen in the body stresses the cells that produce insulin. This makes our body insulin resistant and lead to high glucose levels, which in turn lead to weight gain. Mostly, lower levels of estrogen are found in older people when there is less production of estrogen hormones. To produce more estrogen levels, body extracts fatty cells and converts all energy to fat to reload glucose levels. This is another reason for weight gain. (timesofindia.indiatimes.com)2. Thyroid hormonesThis gland is positioned at the base of a neck. It is responsible for producing T3, T4 and calcitonin, which maintain body's metabolism. If these hormones are underproduced, it can lead to hypothyroidism, which is associated with weight gain. 3. InsulinInsulin is secreted by the pancreas and is responsible to carry glucose into the cells. It is used as energy or stored as fat, which in turn maintains blood glucose levels. When there is an interruption in insulin levels, the body gets resistant to insulin. Muscle cells, then, fail to recognize the glucose-bound insulin and glucose remains in the bloodstream. Hence, it causes a spike in the blood sugar levels and leads to weight gain.4. TestosteroneTestosterone is often considered as a male hormone, but women's bodies also secrete this hormone. Testosterone helps to maintain libido, burn fat and strengthen bones and muscles. However, due to various lifestyle factors, such as age, stress can reduce testosterone levels and can lead to obesity.5. ProgesteroneProgesterone is also required for the smooth functioning of the body. It can drop due to stress, menopause and also by the intake of contraceptive pills. This can cause weight gain. Now when we have some theoretical background of hormonal imbalance and its influence on gaining weight, I will go deeper into the objective of this work. Firstly I will be talking about aims of this work and methods that I will use to simulate data.   Aim and MethodThe aim of this work is to simulate data that would correspond real world phenomenon. I will look into the difference in weight when a person is going through some hormonal imbalance problems. I will focus on data that shows the influence of BMI and age of a person on weight gain. Relationship of weight and hormonal imbalances will be assessed using numpy.random package which will also be used to simulate data. So, this is not a research based on real-life data, it is based on simulation. Nevertheless, data will be programmed in order to show as close relationship with real-life data as possible. As mentioned before, the focus of this project is to get simulated data that will reflect real-life data. Numpy.random pseudorandom numbers are a sample of numbers that look close to true random numbers but are generated using some deterministic process. As computers can not produce random numbers itself, they need packages and algorithms that would deal with it. Numpy.random package is one of the libraries in Python that generates pseudorandom data.Within the package there are many different functions and distributions. You can find more information about numpy.random package and its features here: https://docs.scipy.org/doc/numpy-1.15.0/reference/routines.random.htmlNumpy.random package consists of 4 parts:1. Simple random dataThere are 10 different functions that give random values in a given shape, intervals or distribution. Most common distributions are standard normal distribution, discrete uniform and continuous uniform distributions. 2. PermutationsA random permutation is a random ordering of a set of objects, that is, a permutation-valued random variable. The use of random permutations is often fundamental to fields that use randomized algorithms such as coding theory, cryptography, and simulation. A good example of a random permutation is the shuffling of a deck of cards: this is ideally a random permutation of the 52 cards (https://en.wikipedia.org). A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list. This method takes a list as an input and return an object list of tuples that contain all permutation in a list form (https://www.geeksforgeeks.org). There are 2 permutation functions: shuffle(x) and permutation(x).3. DistributionsEvery time we are working with a dataset, our dataset represents some kind of a sample and using this sample, we need to understand its patterns so that we can make predictions based on them. Datasets are composed of two main types of data: Numerical (eg. integers), and categorical (eg. names). Based on that data it is possible to calculate some predictions like Probability Mass Functions and Probability Density Functions (https://www.kdnuggets.com) 4. Random generatorComputers can't produce random numbers itself, they need human help. That is the reason why random numbers are deterministic which means that they operate by a set of rules, and we call them pseudorandom numbers. The pseudorandom number generator is a mathematical function that generates a sequence of nearly random numbers. It takes a parameter to start off the sequence, called the seed. As the function is deterministic, the same seed will produce the same sequence of numbers every time. (https://yourbasic.org)I won't discus each of these functions and distributions individually as I will be focusing only on data and distributions necessary for this project. Main distribution used in this project is Normal distribution. 1. Normal distributionIt represents the behavior of most of the situations in the universe. That is why it's called a “normal” distribution. The large sum of (small) random variables often turns out to be normally distributed, contributing to its widespread application. Any distribution is known as Normal distribution if it has the following characteristics:- The mean, median and mode of the distribution coincide.- The curve of the distribution is bell-shaped and symmetrical about the line x=μ.- The total area under the curve is 1.- Exactly half of the values are to the left of the center and the other half to the right.![alt text](N1.png "Normal distribution")Image taken from: https://towardsdatascience.com/understanding-the-68-95-99-7-rule-for-a-normal-distribution-b7b7cbf760c2The normal distribution is commonly associated with the 68-95-99. A rule which you can see in the image above. 68% of the data is within 1 standard deviation (σ) of the mean (μ), 95% of the data is within 2 standard deviations (σ) of the mean (μ), and 99.7% of the data is within 3 standard deviations (σ) of the mean (μ).  Interpretation of variables  1. AgeAge is important variable in this research because as we move through the stages of life, our hormone levels fluctuate; aging means that we produce more of some hormones and less of others. The most common consequence of aging-related hormonal changes is menopause. Around age 50, women's ovaries begin producing decreasing amounts of estrogen and progesterone; the pituitary gland tries to compensate by producing more follicle stimulating hormone (FSH). It can be easy to chalk up changes in mood, weight and menstrual patterns to the normal hormonal fluctuations of aging, but they can also be the result of thyroid disease, which affects 30 million Americans of all ages (https://www.rush.edu).Although certain age is more likely to be affected by hormonal changes, in this research I will focus on women of mature age, hence I will use random.normal distribution with the mean of 35 years old. My focus will be on mature women. There will be a sample of 500 data. I have chosen 500 rows of data as I think sample size of 500 is a good number to make some predictions and investigate relationship between the variables. In order to simulate data with numpy random package, I will use random.normal distribution. Age variable will have mean of 35 years old, but with standard deviation of 6 it will spread from 17 years of age all the way up to almost 53. That is the time when women are mostly affected by hormonal changes.  ``` Returns random  numbers in normal distribution.Age = np.random.normal(35,6, 500)``` As you can see above, there is "Age" variable shown. I used np.random.normal function that has three parameters (35, 6, 500). Number 35 signifies the mean around which the data is distributed. Number 6 is standard deviation which spreads the range. In this case range is from 17 to 53 but majority of data is scattered around 35 years of age. Number 500 is number of the sample size. It will be interesting to see the difference of weight gain related to certain age.   2. Weight Weight gain occurs when you regularly eat more calories than you use through normal bodily functions and physical activity. But the lifestyle habits causing your weight gain aren't always obvious. Losing weight means eating fewer calories and burning more energy through physical activity. It sounds simple. But more than 60% of adults in England are overweight or obese. Our lifestyles see many of us eating more calories than we need and not doing enough physical activity (https://www.nhs.uk).Obesity is becoming one of the fastest growing health problems in Ireland as well. One in eight Irish people are obese and every second person is overweight. The trends from the second SLÁN survey on people’s lifestyles show that as a nation we are becoming progressively heavier – witnessed by the 30% increase in reported obesity levels over the last four years (https://myknee.ie).In this research I will simulate my data with random.normal distribution as weight variable is usually distributed in accordance with normal distribution which means it has its mean (average) and standard deviation. In order to get as closer data as the one in the real world I  will write code for two outcomes. One is for women who have hormonal imbalance, and the other one is for those who  don't have it. If there is hormonal imbalance, the mean will be set to 83 kg to fit real world data, and if there is no hormonal imbalance mean will be 68 which is an average weight for women.  ```def new_weight(weight):        if weight == 'Yes':            return np.random.normal(83.00, 10)        elif weight == 'No':            return np.random.normal(68.00, 10)```  3. HeightI have chosen to implement this variable since it is necessary to calculate Body Mass Index (BMI) which tells us a lot about the level of fat in human body. I will run random.normal distribution because height is a type of variable that suits normal distribution in a real life. It has its average and variance that is further away from its peak. Average height for women in Ireland is 165 cm (https://www.thejournal.ie). The function will be run in a way that 68% of data will be grouped around 165 cm with the standard deviation of 10 and the size of 500. The code that I will run to simulate height variable is: ``` Height variable set with random normal distributionHeight = np.random.normal (165.00, 10.00, 500)```  4. Body mass index (BMI)Body mass index (BMI) is a value derived from the mass (weight) and height of a person. The BMI is defined as the body mass divided by the square of the body height, and is universally expressed in units of kg/m2, resulting from mass in kilograms and height in metres. The BMI is a convenient rule of thumb used to broadly categorize a person as underweight, normal weight, overweight, or obese based on tissue mass (muscle, fat, and bone) and height (https://en.wikipedia.org).Body Mass Index or BMI is a way of checking to see if you are a healthy weight. BMI uses your height and weight to calculate if you are a healthy weight, overweight or underweight. Obesity is when a person is carrying too much body fat for their height. A person is considered obese if they have a body mass index (BMI) of 30 or greater (https://www.hse.ie/eng/).What does your BMI mean?- If your BMI is less than 18.5 then you are probably underweight - If your BMI is between 18.5 and 25, then you probably have a healthy weight - If your BMI is between 25 and 30 then you are probably overweight - If your BMI is over 30 then you are probably obese(https://www.indi.ie)In the following code I will calculate BMI based on 2 other variables, weight and height. To calculate BMI weight needs to be divided by height and multiplied by 2. In order to get data that represent above mentioned scale I will multiply it with 10000.  ``` BMI calculationdf['BMI'] = df['Weight']/df['Height']**2*10000``` You can find body mass calculator here:  https://bmicalculatorireland.com/  5. Hormonal imbalanceHormones are your body's chemical messengers. Produced in the endocrine glands, these powerful chemicals travel around your bloodstream telling tissues and organs what to do. They help control many of your body's major processes, including metabolism and reproduction. When you have a hormonal imbalance, you have too much or too little of a certain hormone. Even tiny changes can have serious effects throughout your whole body (https://www.healthline.com). Hormones regulate appetite and metabolism, sleep cycles, heart rate, sexual function, general mood and stress levels, and body temperature (https://flo.health).In this work I will simulate data that relates to hormonal imbalance. As there are so many types of hormonal imbalances and factors that can affect it I decided to define it with yes or no. So, in the real world a person should only answer if they suffer from any type of hormonal imbalance (Yes, No). Have a look at the code that I will run in a data set. ``` Hormonal imbalance variableHor_imba = ['Yes', 'No'] Random choice, size 500, ratio df['Hor_imba'] = np.random.choice(Hor_imba, 500, p=[0.70, 0.30]) ``` Statistics show that 80 percent of women suffer from hormonal imbalance. Some women live with these imbalances without even realizing it so I will set the ratio to 70% of women who have some hormonal imbalance, and 30% who don't have any hormonal problems.   Data frame My simulated data frame has 5 variables that I find relevant to see if there is any relationship between hormonal imbalance and weight changes in women. To see the relationship between these variables I will include some demographics like age. As I want to determine relationship between hormonal imbalance and weight I needed to include height variable to calculate Body Mass Index which will give us significant information about the shape of human body. To start with my data frame I will include below mentioned libraries.<jupyter_code># Import pandas
# Import numpy
# Import seaborn
import pandas as pd
import numpy as np
import seaborn as sns
# Data frame that consists of 6 variables: Age, Weight, Height, BMI, Hor_imba
df = pd.DataFrame(columns=['Age','Weight', 'Height', 'BMI', 'Hor_imba'])<jupyter_output><empty_output><jupyter_text>1. Age<jupyter_code># Returns a random  numbers in normal distribution.
Age = np.random.normal(35,6, 500)

# Meaan of age
np.mean(Age)
# Median of age
np.median(Age)
# Import seaborn to show distribution on the plot
import seaborn as sns
Age = sns.distplot(Age, bins=20, color="blue")<jupyter_output><empty_output><jupyter_text>2. Weight<jupyter_code># Weight will be run with normal distribution. If there is hormonal imbalance the weight is set to 83 kg. 
Weight = np.random.normal (83.00, 10, 500)
print ('Average weight(kg):')
print (np.mean(Weight).round(2))
print ('Minimum weight(kg):')
print  (np.min(Weight).round(2))
print ('Maximum weight(kg):')
print (np.max(Weight).round(2))
# Import seaborn to show distribution on the plot
import seaborn as sns
# Weight variable shown on the plot
Weight = sns.distplot(Weight, bins=20, color="blue")
# Weight will be run with normal distribution. If there is no hormonal imbalance, the weight is set to 68 kg.
Weight2 = np.random.normal (68.00, 10, 500)
# Import seaborn to show distribution on the plot
import seaborn as sns
# Weight variable shown on the plot
Weight2 = sns.distplot(Weight2, bins=20, color="blue")<jupyter_output><empty_output><jupyter_text>3. Height<jupyter_code># Height will be run with normal distribution
Height = np.random.normal (165.00, 10.00, 500)
print ('Average height(cm):')
print (np.mean(Height).round(2))
print ('Minimum Height(cm):')
print  (np.min(Height).round(2))
print ('Maximum Height(cm):')
print (np.max(Height).round(2))
# Import seaborn to show distribution on the plot
import seaborn as sns
Height = sns.distplot(Height, bins=20, color="blue")<jupyter_output><empty_output><jupyter_text>4. BMI<jupyter_code># Body Mass Index is weight variable divided by height variable multiplied by 2
BMI = df['Weight']/df['Height']*2<jupyter_output><empty_output><jupyter_text>5. Hormonal Imbalance<jupyter_code># Hormonal imbalance, ratio 60-40
Hor_imba = ['Yes', 'No']
df['Hor_imba'] = np.random.choice(Hor_imba, 500, p=[0.60, 0.40])

Hor_imba<jupyter_output><empty_output><jupyter_text>Data frame<jupyter_code># Data frame code adjusted from: https://web.microsoftstream.com/video/57715d30-ea78-4003-ba05-2b254ddb3da2
df = pd.DataFrame(columns=['Age', 'Weight', 'Height', 'BMI', 'Hor_imba']) 

# Age variable, random normal distribution. Data is grouped around average of 35 years old. 
df['Age'] = np.random.normal(35,6, 500)

# Hormonal imabalance, ratio 70-30
df['Hor_imba'] = np.random.choice(Hor_imba, 500, p=[0.70, 0.30]) 

# Weight variable distributed with random.normal distribution. Average weight for women is 68 kg. If there is Yes for hormone imbalance
# Weight is increased to 83 kg to resemble more to real life situation.
def new_weight(weight):
        if weight == 'Yes':
            return np.random.normal(83.00, 10)
        elif weight == 'No':
            return np.random.normal(68.00, 10)
df['Weight'] = df['Hor_imba'].apply(new_weight)

# Height variable distributed with random.normal distribution. 165 cm is an average in Ireland for women.
df['Height']= np.random.normal(165.00, 10.00, 500)
       

# BMI variable is calculated by dividing weight by height and multiplied by 2. It is multiplied by 10000 to get round.2 number
df['BMI'] = df['Weight']/df['Height']**2*10000

# Round floats
df.round({'Age':0, 'Height': 2, 'Weight':2, 'BMI': 2})
# Information about the data frame
df.info()
# Data frame described (Age, weight, height, BMI)
df.describe()<jupyter_output><empty_output><jupyter_text>count: in the table above count is 500 which means that count represents the size of the data set.mean: Mean or Average is a central tendency of the data i.e. a number around which a whole data is spread out. In a way, it is a single number which can estimate the value of whole data set.std: Standard deviation is the measurement of average distance between each quantity and mean. That is, how data is spread out from mean. A low standard deviation indicates that the data points tend to be close to the mean of the data set, while a high standard deviation indicates that the data points are spread out over a wider range of values.min: shows the smallest data figure collected, ie. the minimum age.25%: also called first quartile. It means that 25% of data falls behind this measurement, and 75% is above it.50%: The 50 percentile is the same as the median. Half of the data collected falls behind this measurement.75%: also called third quartile. It means that 75% of data falls behind this measurement, and 25% is above it.max: shows the highest data figure collected, ie. maximum BMI.<jupyter_code># Hormonal imbalance count
df['Hor_imba'].value_counts()
# Code adjusted from: http://seaborn.pydata.org/generated/seaborn.pairplot.html
sns.pairplot(df, hue= "Hor_imba", diag_kind = "hist")
# I have added the argument diag_kind hist to plot histograms as I have used the hue argument
# sns.pairplot(df, hue= 'day', diag_kind = 'auto')
# Code adjusted from: https://seaborn.pydata.org/generated/seaborn.relplot.html
# Import numpy as np
import numpy as np
# Import pandas as pd
import pandas as pd 
# Import seaborn as sns
import seaborn as sns
# Import matplotlib as plt
import matplotlib.pyplot as plt
# Set the colours
sns.set(color_codes=True)
g = sns.relplot(x= "Age", y='BMI', hue= "Hor_imba", data = df)

# Code adjusted from: https://seaborn.pydata.org/generated/seaborn.regplot.html
sns.regplot(x= "Age", y='BMI', data = df)
# Code adjusted from: https://seaborn.pydata.org/generated/seaborn.lmplot.html
sns.lmplot(x="Weight", y="BMI", hue="Hor_imba", data=df)
sns.lmplot(x="Age", y="BMI", hue= "Hor_imba", data=df)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.055178686474400274, 'fraction_numerical': 0.014893697654147876, 'mean_word_length': 4.699352051835853, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 20, 'lorem ipsum': 0, 'www.': 13, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '69178', 'license': 'Apache-2.0', 'n_tokens_mistral': 6976, 'n_tokens_neox': 6230, 'n_words': 3927, 'path': 'project.ipynb', 'repo_name': 'doriszd/Programming_project', 'size': '26387'}