{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "\n", "## [mlcourse.ai](https://mlcourse.ai) - Open Machine Learning Course\n", " \n", "Authors: [Ilya Baryshnikov](https://www.linkedin.com/in/baryshnikov-ilya/), [Maxim Uvarov](https://www.linkedin.com/in/maxis42/), and [Yury Kashnitsky](https://www.linkedin.com/in/festline/). Translated and edited by [Inga Kaydanova](https://www.linkedin.com/in/inga-kaidanova-a92398b1/), [Egor Polusmak](https://www.linkedin.com/in/egor-polusmak/), [Anastasia Manokhina](https://www.linkedin.com/in/anastasiamanokhina/), and [Yuanyuan Pao](https://www.linkedin.com/in/yuanyuanpao/). All content is distributed under the [Creative Commons CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) license." ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "#
Assignment #2 (demo). Solution\n", "##
Analyzing cardiovascular disease data \n", " \n", " \n", "**Same assignment as a [Kaggle Kernel](https://www.kaggle.com/kashnitsky/a2-demo-analyzing-cardiovascular-data) + [solution](https://www.kaggle.com/kashnitsky/a2-demo-analyzing-cardiovascular-data-solution).**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this assignment, you will answer questions about a dataset on cardiovascular disease. You do not need to download the data: it is already in the repository. There are some Tasks that will require you to write code. Complete them and then answer the questions in the [form](https://docs.google.com/forms/d/13cE_tSIb6hsScQvvWUJeu1MEHE5L6vnxQUbDYpXsf24).\n", "\n", "#### Problem\n", "\n", "Predict presence or absence of cardiovascular disease (CVD) using the patient examination results.\n", "\n", "#### Data description\n", "\n", "There are 3 types of input features:\n", "\n", "- *Objective*: factual information;\n", "- *Examination*: results of medical examination;\n", "- *Subjective*: information given by the patient.\n", "\n", "| Feature | Variable Type | Variable | Value Type |\n", "|---------|--------------|---------------|------------|\n", "| Age | Objective Feature | age | int (days) |\n", "| Height | Objective Feature | height | int (cm) |\n", "| Weight | Objective Feature | weight | float (kg) |\n", "| Gender | Objective Feature | gender | categorical code |\n", "| Systolic blood pressure | Examination Feature | ap_hi | int |\n", "| Diastolic blood pressure | Examination Feature | ap_lo | int |\n", "| Cholesterol | Examination Feature | cholesterol | 1: normal, 2: above normal, 3: well above normal |\n", "| Glucose | Examination Feature | gluc | 1: normal, 2: above normal, 3: well above normal |\n", "| Smoking | Subjective Feature | smoke | binary |\n", "| Alcohol intake | Subjective Feature | alco | binary |\n", "| Physical activity | Subjective Feature | active | binary |\n", "| Presence or absence of cardiovascular disease | Target Variable | cardio | binary |\n", "\n", "All of the dataset values were collected at the moment of medical examination." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's get to know our data by performing a preliminary data analysis.\n", "\n", "# Part 1. Preliminary data analysis\n", "\n", "First, we will initialize the environment:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import all required modules\n", "# Disable warnings\n", "import warnings\n", "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "warnings.filterwarnings(\"ignore\")\n", "\n", "# Import plotting modules\n", "import seaborn as sns\n", "\n", "sns.set()\n", "import matplotlib\n", "import matplotlib.pyplot as plt\n", "import matplotlib.ticker\n", "\n", "%config InlineBackend.figure_format = 'retina'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You should use the `seaborn` library for visual analysis, so let's set it up too:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tune the visual settings for figures in `seaborn`\n", "sns.set_context(\n", " \"notebook\", font_scale=1.5, rc={\"figure.figsize\": (11, 8), \"axes.titlesize\": 18}\n", ")\n", "\n", "from matplotlib import rcParams\n", "\n", "rcParams[\"figure.figsize\"] = 11, 8" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To make it simple, we will work only with the training part of the dataset:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = pd.read_csv(\"../../data/mlbootcamp5_train.csv\", sep=\";\")\n", "print(\"Dataset size: \", df.shape)\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It would be instructive to peek into the values of our variables.\n", " \n", "Let's convert the data into *long* format and depict the value counts of the categorical features using [`factorplot()`](https://seaborn.pydata.org/generated/seaborn.factorplot.html)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_uniques = pd.melt(\n", " frame=df,\n", " value_vars=[\"gender\", \"cholesterol\", \"gluc\", \"smoke\", \"alco\", \"active\", \"cardio\"],\n", ")\n", "df_uniques = (\n", " pd.DataFrame(df_uniques.groupby([\"variable\", \"value\"])[\"value\"].count())\n", " .sort_index(level=[0, 1])\n", " .rename(columns={\"value\": \"count\"})\n", " .reset_index()\n", ")\n", "\n", "sns.factorplot(\n", " x=\"variable\", y=\"count\", hue=\"value\", data=df_uniques, kind=\"bar\", size=12\n", ");" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "We can see that the target classes are balanced. That's great!\n", "\n", "Let's split the dataset by target values: sometimes you can immediately spot the most significant feature on the plot." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_uniques = pd.melt(\n", " frame=df,\n", " value_vars=[\"gender\", \"cholesterol\", \"gluc\", \"smoke\", \"alco\", \"active\"],\n", " id_vars=[\"cardio\"],\n", ")\n", "df_uniques = (\n", " pd.DataFrame(df_uniques.groupby([\"variable\", \"value\", \"cardio\"])[\"value\"].count())\n", " .sort_index(level=[0, 1])\n", " .rename(columns={\"value\": \"count\"})\n", " .reset_index()\n", ")\n", "\n", "sns.factorplot(\n", " x=\"variable\",\n", " y=\"count\",\n", " hue=\"value\",\n", " col=\"cardio\",\n", " data=df_uniques,\n", " kind=\"bar\",\n", " size=9,\n", ");" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can see that the target variable greatly affects the distribution of cholesterol and glucose levels. Is this a coincidence?\n", "\n", "Now, let's calculate some statistics for the feature unique values:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for c in df.columns:\n", " n = df[c].nunique()\n", " print(c)\n", " if n <= 3:\n", " print(n, sorted(df[c].value_counts().to_dict().items()))\n", " else:\n", " print(n)\n", " print(10 * \"-\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the end, we have:\n", "- 5 numerical features (excluding *id*);\n", "- 7 categorical features;\n", "- 70000 records in total." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1.1. Basic observations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 1.1. (1 point). How many men and women are present in this dataset? Values of the `gender` feature were not expailned (whether \"1\" stands for women or men) – figure this out by looking analyzing height, reasonably assuming that on average men are taller.**\n", "1. 45530 women и 24470 men\n", "2. 45530 men и 24470 women\n", "3. 45470 women и 24530 men\n", "4. 45470 men и 24530 women\n", "\n", "**Answer:** 1." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Solution:" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Let's calculate average height for both values of `gender`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.groupby(\"gender\")[\"height\"].mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "161 cm and almost 170 cm on average, so we make a conclusion that gender=1 represents females, and gender=2 – males. So the sample contains 45530 women и 24470 men." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 1.2. (1 point). Who more often report consuming alcohol - men or women?**\n", "1. women\n", "2. men\n", "\n", "**Answer:** 2." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.groupby(\"gender\")[\"alco\"].mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Well... obvious :)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 1.3. (1 point). What's the rounded difference between the percentages of smokers among men and women?**\n", "1. 4\n", "2. 16\n", "3. 20\n", "4. 24\n", "\n", "**Answer:** 3." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.groupby(\"gender\")[\"smoke\"].mean()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "round(\n", " 100\n", " * (\n", " df.loc[df[\"gender\"] == 2, \"smoke\"].mean()\n", " - df.loc[df[\"gender\"] == 1, \"smoke\"].mean()\n", " )\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 1.4. (1 point). What's the rounded difference between median values of age (in months) for non-smokers and smokers? You'll need to figure out the units of feature `age` in this dataset.**\n", "\n", "1. 5\n", "2. 10\n", "3. 15\n", "4. 20\n", "\n", "**Answer:** 4." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Solution:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Age is given here in days." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.groupby(\"smoke\")[\"age\"].median() / 365.25" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Median age of smokers is 52.4 years, for non-smokers it's 54. We see that the correct answer is 20 months. But here is a way to calculate it exactly:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "(\n", " df[df[\"smoke\"] == 0][\"age\"].median() - df[df[\"smoke\"] == 1][\"age\"].median()\n", ") / 365.25 * 12" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1.2. Risk maps\n", "### Task:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "On the web site of European Society of Cardiology, a [SCORE scale](https://www.escardio.org/Education/Practice-Tools/CVD-prevention-toolbox/SCORE-Risk-Charts) is given. It is used for calculating the risk of death from a cardiovascular decease in the next 10 years. Here it is:\n", "\n", "\n", "\n", "Let's take a look at the upper-right rectangle showing a subset of smoking men aged from 60 to 65. (It's not obvious, but the values in figure represent the upper boundary).\n", "\n", "We see a value 9 in the lower-left corner of the rectangle and 47 in the upper-right. This means that for people in this gender-age group whose systolic pressure is less than 120 the risk of a CVD is estimated to be 5 times lower than for those with the pressure in the interval [160,180).\n", "\n", "Let's calculate the same ratio, but with our data.\n", "\n", "Clarifications:\n", "- Calculate ``age_years`` feature – rounded age in years. For this task, select people aged from 60 to 64 inclusive.\n", "- Cholesterol level categories in the figure and in our data are different. In the figure, the values of ``cholesterol`` feature are as follows: 4 mmol/l $\\rightarrow$ 1, 5-7 mmol/l $\\rightarrow$ 2, 8 mmol/l $\\rightarrow$ 3.\n", "\n", "**Question 1.5. (2 points). Calculate fractions of ill people (with CVD) in two segments described above. What's the quotient of these two fractions?**\n", "\n", "1. 1\n", "2. 2\n", "3. 3\n", "4. 4\n", "\n", "**Answer:** 3." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df[\"age_years\"] = (df[\"age\"] / 365.25).round().astype(\"int\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df[\"age_years\"].max()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The oldest people in the sample are aged 65. Coincidence? Don't think so! Let's select smoking men of age [60,64]." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "smoking_old_men = df[\n", " (df[\"gender\"] == 2)\n", " & (df[\"age_years\"] >= 60)\n", " & (df[\"age_years\"] < 65)\n", " & (df[\"smoke\"] == 1)\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If cholesterol level in this age group is 1, and systolic pressure is below 120, then the proportion of people with CVD is 26%." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "smoking_old_men[\n", " (smoking_old_men[\"cholesterol\"] == 1) & (smoking_old_men[\"ap_hi\"] < 120)\n", "][\"cardio\"].mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If, however, cholesterol level in this age group is 3, and systolic pressure is from 160 to 180, then the proportion of people with a CVD is 86%." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "smoking_old_men[\n", " (smoking_old_men[\"cholesterol\"] == 3)\n", " & (smoking_old_men[\"ap_hi\"] >= 160)\n", " & (smoking_old_men[\"ap_hi\"] < 180)\n", "][\"cardio\"].mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As a result, the difference is approximately 3-fold. Not 5-fold, as the SCORE scale tells us, but it's possible that the SCORE risk of CVD is nonlinearly dependent on the proportion of ill people in the given age group." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1.3. Analyzing BMI\n", "### Task:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create a new feature – BMI ([Body Mass Index](https://en.wikipedia.org/wiki/Body_mass_index)). To do this, divide weight in kilogramms by the square of height in meters. Normal BMI values are said to be from 18.5 to 25. \n", "\n", "**Question 1.6. (2 points). Choose the correct statements:.**\n", "\n", "1. Median BMI in the sample is within boundaries of normal values.\n", "2. Women's BMI is on average higher then men's.\n", "3. Healthy people have, on average, higher BMI than ill people.\n", "4. In the segment of healthy and non-drinking men BMI is closer to the norm than in the segment of healthy and non-drinking women\n", "\n", "**Answer:** 2 and 4\n", "\n", "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df[\"BMI\"] = df[\"weight\"] / (df[\"height\"] / 100) ** 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df[\"BMI\"].median()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First statement is incorrect since median BMI exceeds the norm of 25 points." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.groupby(\"gender\")[\"BMI\"].median()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Seconds statement is correct – women's BMI is higher on average." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Third statement is incorrect." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.groupby([\"gender\", \"alco\", \"cardio\"])[\"BMI\"].median().to_frame()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Comparing BMI values in rows where `alco=0` and `cardio=0`, we see that the last statement is correct." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1.4. Cleaning data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Task:\n", "We can notice, that the data is not perfect. It contains much of \"dirt\" and inaccuracies. We'll see it better when we do data visualization.\n", "\n", "Filter out the following patient segments (that we consider to have erroneous data)\n", "\n", "- diastilic pressure is higher then systolic. \n", "- height is strictly less than 2.5%-percentile (use `pd.Series.quantile`. If not familiar with it – please read the docs)\n", "- height is strictly more than 97.5%-percentile\n", "- weight is strictly less then 2.5%-percentile\n", "- weight is strictly more than 97.5%-percentile\n", "\n", "This is not all we can do to clean the data, but let's stop here by now.\n", "\n", "**Question 1.7. (2 points). How many percents of data (rounded) did we throw away?**\n", "\n", "1. 8\n", "2. 9\n", "3. 10\n", "4. 11\n", "\n", "**Answer:** 3\n", "\n", "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_to_remove = df[\n", " (df[\"ap_lo\"] > df[\"ap_hi\"])\n", " | (df[\"height\"] < df[\"height\"].quantile(0.025))\n", " | (df[\"height\"] > df[\"height\"].quantile(0.975))\n", " | (df[\"weight\"] < df[\"weight\"].quantile(0.025))\n", " | (df[\"weight\"] > df[\"weight\"].quantile(0.975))\n", "]\n", "print(df_to_remove.shape[0] / df.shape[0])\n", "\n", "filtered_df = df[~df.index.isin(df_to_remove)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We've thrown out about 10% of the original data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 2. Visual data analysis\n", "\n", "## 2.1. Correlation matrix visualization\n", "\n", "To understand the features better, you can create a matrix of the correlation coefficients between the features. Use the initial dataset (non-filtered).\n", "\n", "### Task:\n", "\n", "Plot a correlation matrix using [`heatmap()`](http://seaborn.pydata.org/generated/seaborn.heatmap.html). You can create the matrix using the standard `pandas` tools with the default parameters.\n", "\n", "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calculate the correlation matrix\n", "df = filtered_df.copy()\n", "\n", "corr = df.corr(method=\"pearson\")\n", "\n", "# Create a mask to hide the upper triangle of the correlation matrix (which is symmetric)\n", "mask = np.zeros_like(corr, dtype=np.bool)\n", "mask[np.triu_indices_from(mask)] = True\n", "\n", "f, ax = plt.subplots(figsize=(12, 9))\n", "\n", "sns.heatmap(\n", " corr,\n", " mask=mask,\n", " vmax=1,\n", " center=0,\n", " annot=True,\n", " fmt=\".1f\",\n", " square=True,\n", " linewidths=0.5,\n", " cbar_kws={\"shrink\": 0.5},\n", ");" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 2.1. (1 point).** Which pair of features has the strongest Pearson's correlation with the *gender* feature?\n", "\n", "1. Cardio, Cholesterol\n", "2. Height, Smoke\n", "3. Smoke, Alco\n", "4. Height, Weight" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Answer:** 2." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.2. Height distribution of men and women\n", "\n", "From our exploration of the unique values we know that the gender is encoded by the values *1* and *2*. And though you don't have a specification of how these values correspond to men and women, you can figure that out graphically by looking at the mean values of height and weight for each value of the *gender* feature.\n", "\n", "### Task:\n", "\n", "Create a violin plot for the height and gender using [`violinplot()`](https://seaborn.pydata.org/generated/seaborn.violinplot.html). Use the parameters:\n", "- `hue` to split by gender;\n", "- `scale` to evaluate the number of records for each gender.\n", "\n", "In order for the plot to render correctly, you need to convert your `DataFrame` to *long* format using the `melt()` function from `pandas`. Here is [another example](https://stackoverflow.com/a/41575149/3338479) of this.\n", "\n", "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_melt = pd.melt(frame=df, value_vars=[\"height\"], id_vars=[\"gender\"])\n", "\n", "plt.figure(figsize=(12, 10))\n", "ax = sns.violinplot(\n", " x=\"variable\",\n", " y=\"value\",\n", " hue=\"gender\",\n", " palette=\"muted\",\n", " split=True,\n", " data=df_melt,\n", " scale=\"count\",\n", " scale_hue=False,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Task:\n", "\n", "Create two [`kdeplot`](https://seaborn.pydata.org/generated/seaborn.kdeplot.html)s of the *height* feature for each gender on the same chart. You will see the difference between the genders more clearly, but you will be unable to evaluate the number of records in each of them.\n", "\n", "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sns.FacetGrid(df, hue=\"gender\", size=12).map(sns.kdeplot, \"height\").add_legend();" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.3. Rank correlation\n", "\n", "In most cases, *the Pearson coefficient of linear correlation* is more than enough to discover patterns in data. \n", "But let's go a little further and calculate a [rank correlation](https://en.wikipedia.org/wiki/Rank_correlation). It will help us to identify such feature pairs in which the lower rank in the variational series of one feature always precedes the higher rank in the another one (and we have the opposite in the case of negative correlation).\n", "\n", "### Task:\n", "\n", "Calculate and plot a correlation matrix using the [Spearman's rank correlation coefficient](https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient).\n", "\n", "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calculate the correlation matrix\n", "corr = df[\n", " [\"id\", \"age\", \"height\", \"weight\", \"ap_hi\", \"ap_lo\", \"cholesterol\", \"gluc\"]\n", "].corr(method=\"spearman\")\n", "\n", "# Create a mask to hide the upper triangle of the correlation matrix (which is symmetric)\n", "mask = np.zeros_like(corr, dtype=np.bool)\n", "mask[np.triu_indices_from(mask)] = True\n", "\n", "f, ax = plt.subplots(figsize=(12, 10))\n", "\n", "# Plot the heatmap using the mask and correct aspect ratio\n", "sns.heatmap(\n", " corr,\n", " mask=mask,\n", " vmax=1,\n", " center=0,\n", " annot=True,\n", " fmt=\".2f\",\n", " square=True,\n", " linewidths=0.5,\n", " cbar_kws={\"shrink\": 0.5},\n", ");" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 2.2. (1 point).** Which pair of features has the strongest Spearman correlation?\n", "\n", "1. Height, Weight\n", "2. Age, Weight\n", "3. Cholesterol, Gluc\n", "4. Cardio, Cholesterol\n", "5. Ap_hi, Ap_lo\n", "6. Smoke, Alco" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Answer:** 5." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 2.3. (1 point).** Why does these features have strong rank correlation?\n", "\n", "1. Inaccuracies in the data (data acquisition errors).\n", "2. Relation is wrong, these features should not be related.\n", "3. Nature of the data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Answer:** 3." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.4. Age\n", "\n", "Previously we calculated the age of the respondents in years at the moment of examination." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Task:\n", "\n", "Create a *count plot* using [`countplot()`](http://seaborn.pydata.org/generated/seaborn.countplot.html), with the age on the *X* axis and the number of people on the *Y* axis. Each value of the age should have two columns corresponding to the numbers of people of this age for each *cardio* class.\n", "\n", "### Solution:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sns.countplot(x=\"age_years\", hue=\"cardio\", data=df);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 2.4. (1 point).** At what age does the number of people with CVD outnumber the number of people without CVD for the first time?\n", "\n", "1. 44\n", "2. 55\n", "3. 64\n", "4. 70" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Answer:** 2." ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }