RDS_Course
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 4.2 Building a simple model <!-- Assumed known preliminaries from M1-3 + 4.1 - Module 1: The dichotomisation of the self reported health: we are grouping [“”Very good”, “Good” and “Fair”] as good and [“”Bad”, “Very Bad”] as bad. This results in an imbalanced dataset, but it feels like is the most appropriate grouping. However, in the paper they group “fair” in the bad outcome, this might have been done to fix the imbalance issue, but it doesn’t feel right. In any case, there is a lot of issues in this measure, there are cultural differences in what people find good or bad, and it seems that there is a lot of variability in the distributions of these answers between different countries. It would be good that these things get discussed and the resulting limitations of the analysis are understood. - Module 2: Missigness, the analysis from Christina shows a lot of missing variables in Wave 2, so we decided to stick to Wave 3 only. But it could be a good hand-on exercise for the students to motivate this. Furthermore, in Wave 3 there is variables with a large percentage of missing data that we end up dropping (for variables with less data missing we’ll use imputation). It could be good that this is understood, and the students also investigate if there are groups (countries, sectors of populations) where there is more data missing than others, and what could be the consequences of any imputation we might do. - Module 3: In here we will explore relationships between the variables in the data and will motivate the features that will be used in Module 4. --> ## Introduction For the remainder of this module we will use the the European Quality of Life Time Series (EQLTS) dataset to ilustrate the steps and considerations to have in mind when building a simple module. More details about this dataset can be found in [here](https://beta.ukdataservice.ac.uk/datacatalogue/studies/study?id=7724#!/details). As discussed in Module 1, we want to investigate the contribution of material, occupational, and psychosocial factors on the self reported health (SRH) across different European countries. In this particular excersice we will focus on the data from the UK taken for Wave 3. In the survey self reported health was assessed using the following question: “In general, would you say your health is …” and response categories were “very good”, “good”, “fair”, and “bad” and "very bad". For simplicity, we will follow the strategy from (Aldabe et al.) of dicotomising the variable as “good” (“very good”, “good”, “fair”) health versus “bad” health (“bad” and “very bad”). In figure X you can see the frequency distribution of the answers that individuals from the UK provided Wave 3 of the survey. TODO: DEPENDING IN HOW THE FIGURE LOOK ADD TEXT ON THE ADVANTAGE OF DICHOTOMISING. # Models To the goal of our stury is to capture the relationships that certain socialfactors have with our target variable, the self reported health. A straight forward way of doing this is to think in a multiple linear regression which attempts to model the relationship between two or more explanatory variables and a response variable by fitting a linear equation to observed data. In a multiple linear regression every value of the $n$ independent variables is associated with a value of the dependent variable in the following way: $$ Y = \beta_0 + \beta_1 x_{1} + \beta_2 x_{2} + ...+ \beta_q x_{q} + \epsilon $$ where $Y$ is the value of the dependent variable, $\beta_0$ is the intercept, the coefficients $\beta_1$, $\beta_2$, $\beta_3$ and $\beta_q$ describe the mathematical relationship between each independent variable and the dependent variable are to be estimated and $\epsilon$ is used to account for error and is a normal random variables with mean $0$ and variance $\sigma^2$. In our particular case our target variable is an ordered categorical variable that we decided to dichotomise, but we we'll get to this later when we introduce logistic regression. For now, let's use a simple toy dataset to explore further how to fit a MLR module and how to assess its quality. ## A toy example: Polynomial Curve Fitting from Bishops A python demo of bishops that we can use for this section https://mantas.info/wp/wp-content/uploads/learn/curve-over-fitting.html - high-level overview of how models are fitted (e.g. wrt some cost function). - Cost of error function - choosing the order M of the polynomial, and as we shall see this will turn out to be an example of an important concept called model comparison or model selection. - Model complexity and over fitting - By adopting a Bayesian approach, the over-fitting problem can be avoided? - Colinearity <!--Introduce regression - predicting an outcome as a combination of other variables. - most models are regression models of different forms. - briefly cover the mathematics and necessary assumptions when making a simple regression model. - Discuss colinearity - here have a very simple toy example with exaggerated examples. - Graphs + easy calculations - How to assess for coliniarity (correlations, [VIFs](https://www.geeksforgeeks.org/detecting-multicollinearity-with-vif-python/)) - Here also discuss uncertainty (cue this in 4.1 and maybe bring the same figures - but adapted to show where the difference lies - into this module) _mimic the way that bishop describes modelling in his introductory pages_ --> ## From linear regression to logistic regression The previous sections have given you an idea of the fundamental concepts of building and testing a linear model regresion model, but the problem we are trying to solve with our research question is not a regression problem but a classification one. We want to predict a binary dependent variable that has 2 values: either 1 or 0. $$ Y = \begin{cases} 1 & \text{good health} \\ 0 & \text{bad health} \end{cases} $$ This kind of binary choices are represented by a Bernoulli variable where the probabilities of an event belonging to a given class are bounded on both ends (they must be between 0 and 1). In this case we'll mostly focus on the case when $Y = 1$ (good health), defined with the following way: $$ p({\bf x}) = P[Y = 1 \mid {\bf X} = {\bf x}] $$ Our usual linear regression can deals continuous variables instead of Bernoulli variables, which means that the predictions are not sensible for classification since the true probability must fall between 0 and 1, but the prediction from linear regression it can take any continous values incluing larger than 1 or smaller than 0 as seeen in the Figure X. ![](https://i.imgur.com/PrZtchW.png) Figure from here[https://www.javatpoint.com/linear-regression-vs-logistic-regression-in-machine-learning The solution to this issue (and a way to continously using a linear, understandable model) is to transform the linear regression to a logistic regression curve. This means feeding the the predicted values into a sigmoid function, thus converting them into probability as shown next: In order to see this more formaly lets define now the **logistic regression** model. $$ \log\left(\frac{p({\bf x})}{1 - p({\bf x})}\right) = \beta_0 + \beta_1 x_1 + \ldots + \beta_{p - 1} x_{p - 1} $$ The left hand side is called the **log odds**, which is the log of the odds. The odds are the probability for a positive event $(Y = 1)$ divided by the probability of a negative event $(Y = 0)$. So when the odds are $1$, the two events have equal probability. Odds greater than $1$ favor a positive event. The opposite is true when the odds are less than $1$. Essentially, the log odds are the [logit](https://en.wikipedia.org/wiki/Logit) transform applied to $p({\bf x})$. $$ \text{logit}(\xi) = \log\left(\frac{\xi}{1 - \xi}\right) $$ The inverse logit, otherwise known as the "logistic" or [sigmoid](https://en.wikipedia.org/wiki/Sigmoid_function) function is defined as follows: $$ \text{logit}^{-1}(\xi) = \frac{e^\xi}{1 + e^{\xi}} = \frac{1}{1 + e^{-\xi}} $$ Note that for $x \in (-\infty, \infty))$, this function outputs values between 0 and 1. Where is the error term? Notice that the linear regression model with the error term, $$ Y = \beta_0 + \beta_1x_1 + \ldots + \beta_qx_q + \epsilon, \ \ \epsilon \sim N(0, \sigma^2) $$ can instead be written as $$ Y \mid {\bf X} = {\bf x} \sim N(\beta_0 + \beta_1x_1 + \ldots + \beta_qx_q, \ \sigma^2). $$ While our main focus is on estimating the mean, $\beta_0 + \beta_1x_1 + \ldots + \beta_qx_q$, there is also another parameter, $\sigma^2$ which needs to be estimated. With logistic regression, which uses the Bernoulli distribution, we only need to estimate the Bernoulli distribution's single parameter $p({\bf x})$, which happens to be its mean. $$ \log\left(\frac{p({\bf x})}{1 - p({\bf x})}\right) = \beta_0 + \beta_1 x_1 + \ldots + \beta_{q} x_{q} $$ So even though we introduced ordinary linear regression first, in some ways, logistic regression is actually simpler. Note that applying the inverse logit transformation allow us to obtain an expression for $p({\bf x})$. $$ p({\bf x}) = P[Y = 1 \mid {\bf X} = {\bf x}] = \frac{e^{\beta_0 + \beta_1 x_{1} + \cdots + \beta_{p-1} x_{(p-1)}}}{1 + e^{\beta_0 + \beta_1 x_{1} + \cdots + \beta_{p-1} x_{(p-1)}}} $$ ## Practical tought session Now that we have all the theoretical basis covered, we can start getting with our dataset ready for modeling. As discussed in Module 2, missing data is an important step that needs to solved before building a model. A strategy to deal with missing data is to discard entire rows and/or columns containing missing values. However, this comes with a price os losing data and predictive power or further distorting our sample if the data is not missing completly at random (this could have some serious ethical implications e.g [What gets counted counts](https://data-feminism.mitpress.mit.edu/pub/h1w0nbqp/release/3) TODO: Find others). A better strategy is to do data imputation of the missing values, i.e., to infer them from the known part of the data. Data pipelines allow one to transform data from one representation to another through a series of steps. Pipelines allow one to apply and chain intermediate steps of transform to our data. For example, one can fill missing values, pass the output to cross validation and grid search and then fit the model in series of steps chained together where the output of one is the input to another. ## Preparing our data for modeling - Simple imputation of missing values - Data wrangling step but has such an effect on modelling, and has ethical implications (e.g. persisting dominant norms but imputing the mean or most common values), that it should be considered a key part of the model. - Note that some models (bayesian) have the imputation step explicitly stated within it. ## Fitting a logistic regression - Turining our regression model to solve a classification problem. - First fit of out data - First tipical output of the fit: MSE and classification matrix for test sample. - This move us to 4.3 # Refereces Aldabe, et al. (2011). Contribution of material, occupational, and psychosocial factors in the explanation of social inequalities in health in 28 countries in Europe. Journal of epidemiology and community health, 65(12), 1123–1131. https://doi.org/10.1136/jech.2009.102517 Logistic regresssion discussion from https://daviddalpiaz.github.io/appliedstats/logistic-regression.html#binary-response

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully