What is p-value?

This image effectively conveys how statistical significance and p-values are used to assess the strength of evidence against the null hypothesis in hypothesis testing

A p-value is a concept used in statistics to help us decide whether the results of an experiment or study are meaningful or just happened by chance.

Imagine This Scenario: Suppose you have a coin, and you want to test if it’s fair (has an equal chance of landing heads or tails). You flip it 100 times, and it comes up heads 60 times. You might wonder: Is this coin actually unfair, or did I just get an unusual result by chance?

What Exactly is a P-Value? The p-value tells you the probability of getting results at least as extreme as the ones you observed, assuming that the null hypothesis is true.

  • The Null Hypothesis (H₀) : This is the default assumption.
  • The Alternative Hypothesis (H₁) : This is what you want to prove.

Mathematical Formula

The p-value can be calculated using various statistical tests. A common formula for the p-value in hypothesis testing is:

    $$ p\_value = P\left(X \geq x \mid H_0\right) $$

This formula represents the probability of observing a test statistic as extreme as $x$(or more extreme) under the assumption that the null hypothesis $H0$​ is true.

relationship between probability, statistical significance, and the p-value in the context of a hypothesis test

The image shows that if an observed result (like the orange dot) is far from the true value under the null hypothesis and falls within the green shaded area (p-value), it is considered statistically significant. This indicates that the result is unlikely to have occurred by random chance.

Key Takeaways:

  • P-Value helps determine the significance of your results.
  • Low P-Value (< 0.05): Strong evidence against the null hypothesis.
  • High P-Value (> 0.05): Weak evidence against the null hypothesis; results could be due to chance.
  • Always consider p-values in the context of your study and alongside other statistical measures.

Remember: P-values don’t tell you the probability that the null hypothesis is true; they tell you how compatible your data is with the null hypothesis.

Let’s say you are testing a new drug that you think lowers blood pressure more effectively than an existing drug. Here’s how the p-value and statistical significance would play a role:

Scenario: Testing a New Drug

  • Null Hypothesis (H₀):
    The new drug has no effect on blood pressure compared to the existing drug (i.e., the difference in effectiveness is zero).
  • Alternative Hypothesis (H₁):
    The new drug is more effective at lowering blood pressure than the existing drug (i.e., there is a difference in effectiveness).
  • Experiment:
    You conduct a study with two groups: one takes the new drug, and the other takes the existing drug.
    After the study, you calculate the average reduction in blood pressure for both groups.
  • Observed Result:
    Suppose the group taking the new drug shows a reduction of 8 mmHg in blood pressure, while the group taking the existing drug shows a reduction of 5 mmHg.
  • Statistical Test:
    You perform a statistical test (e.g., a t-test) to compare the blood pressure reductions between the two groups.
    The test generates a p-value, which represents the probability of observing a difference as extreme as 3 mmHg (8 mmHg – 5 mmHg) or more, assuming the null hypothesis is true (i.e., assuming the drugs are equally effective).

Interpreting the P-Value:

    • If the p-value is low (e.g., p < 0.05): This suggests that the observed difference is unlikely to have occurred by chance. In this case, you might reject the null hypothesis and conclude that the new drug is likely more effective than the existing drug.
    • If the p-value is high (e.g., p > 0.05): This suggests that the observed difference could have occurred by chance. In this case, you would not have enough evidence to reject the null hypothesis, and you might conclude that the new drug is not significantly more effective than the existing drug.

    Example Outcome:

    • Suppose the p-value calculated is 0.03.
    • Since 0.03 is less than the common significance level of 0.05, you would consider this result statistically significant. This means there is a strong indication that the new drug has a different (likely better) effect on blood pressure than the existing drug.

    Conclusion: In this case, because the p-value is low, you might reject the null hypothesis and conclude that the new drug is more effective in reducing blood pressure. This helps support the decision to potentially use the new drug over the existing one.

    This example demonstrates how the p-value helps determine whether an observed effect in an experiment is likely due to a real effect or just random chance.

    Notes:

    The p-value is highly dependent on the sample size. With very large samples, even trivial differences can become statistically significant (low p-value), while small samples may fail to detect meaningful differences.

    The conventional cutoff for statistical significance is often set at p < 0.05. However, this threshold is arbitrary and may not be appropriate in all contexts.

    Focusing solely on p-values can cause researchers to ignore other important aspects of data, such as confidence intervals, effect sizes, and the study’s context. Combine p-values with other statistical measures and the broader context of the research to draw more accurate and meaningful conclusions.

    YoloV9 Code for Object Detection + Segmentation and Tracking

    Yolo V9 Tracking + Object Tracing + Segmentation

    First, See The Video below then see the code to do Object Detection + Segmentation and Tracking in that

    YoloV9 Code for Object Detection + Segmentation and Tracking

    Now, See The Python Code for Video above

    import numpy as np
    import supervision as sv
    from ultralytics import YOLO
    
    model = YOLO("yolov9e-seg.pt")
    tracker = sv.ByteTrack()
    box_annotator = sv.MaskAnnotator()
    label_annotator = sv.LabelAnnotator(text_color=sv.Color.BLACK)
    trace_annotator = sv.TraceAnnotator()
    
    def callback(frame: np.ndarray, _: int) -> np.ndarray:
        results = model(frame)[0]
        detections = sv.Detections.from_ultralytics(results)
        detections = tracker.update_with_detections(detections)
    
        labels = [
            f"#{tracker_id} {results.names[class_id]}"
            for class_id, tracker_id
            in zip(detections.class_id, detections.tracker_id)
        ]
    
        annotated_frame = box_annotator.annotate(
            frame.copy(), detections=detections)
        annotated_frame = label_annotator.annotate(
            annotated_frame, detections=detections, labels=labels)
        return trace_annotator.annotate(
            annotated_frame, detections=detections)
    
    sv.process_video(
        source_path="1.mp4",
        target_path="1-result_2.mp4",
        callback=callback
    )
    

    Extract Voice from a Video and Save that in a file using Python (Speech Recognition)

    Extract Voice from a Video and Save that in a file using Python (Speech Recognition)

    In this video, We see how to extract speech text from video and save it in a file using Python. We use Python Packages and libraries that has trained by deep learning Speech Recognition models and has high accuracy. This is a Simple and Powerful code to Extract Speech from Video and do Speech Recognition on it.

    Python Code of Video is :

    import moviepy.editor as mp 
    import speech_recognition as sr 
    
    clip = mp.VideoFileClip("1.mp4")
    
    clip.audio.write_audiofile("ExtractedAudio.wav")
    
    r = sr.Recognizer()
    audio = sr.AudioFile("ExtractedAudio.wav")
    
    with audio as source:
        audio_file = r.record(source)
    
    try :
        result = r.recognize_google(audio_data= audio_file)
    
        with open("result.txt", "w") as file :
            file.write(result)
            file.close()
    
        print("Runs Successfully")
        
    except sr.UnknownValueError :
        print("Google Speech Recognition Engine Could not Understand Audio.")
    except sr.RequestError as e:
        print("Could not Get response from Google, Error is {0}".format(e))
    except Exception as e:
        print(e)
    
    clip.close()
    print("End")
    

    Automate Sending Scheduled Whatsapp Message in Python

    Automate Sending Scheduled Whatsapp Message in Python

    Task Automation is an easy task on python. Probably the most common task we do every day is sending messages on WhatsApp. in this tutorial we want to Automate Sending whatsapp Message in Python. At first we need pywhatkit library. The pywhatkit library allows you to send individual Whatsapp messages, send messages to groups, and even send images – all from Python!. To install the last version of pywhatkit, open up a terminal and run the following command.

    pip install pywhatkit

    The sendwhatmsg_instantly() function will send a Whatsapp message after running the code, hence the “instantly” in the name. Two parameters are required:

    • phone_no – A phone number to which you want to send the message. Don’t forget to include the country code.
    • message – The actual message you want to send.

    Let’s see it in action:

    import pywhatkit
    
    # syntax: phone number with country code, message
    pywhatkit.sendwhatmsg_instantly(
        phone_no='<phone_number_with_country_code>', 
        message="Howdy! This message is Send Automatically by Python. CodeTipsAcademy.com!",
    )
    

    after running code, you’ll land on a new chat screen with your message populated in the input area. For some reason, the message isn’t sent automatically, and you have to manually click on the send button. So, this is not good and we will fix it in future.

    Send Schedule Whatsapp Messages

    if you want to send Scheduled Whatsapp Message you should use sendwhatmsg() function. sendwhatmsg() has following input parameters.

    • phone_no – A phone number to which you want to send the message. Don’t forget to include the country code.
    • message – The actual message you want to send.
    • time_hour – Integer, represents the hour (24h format) in which you want to send the message.
    • time_min – Integer, represents the minute in which you want to send the message.

    See an example of using sendwhatmsg() function. in code below we send a whatsapp message at 19:30.

    import pywhatkit
    
    # syntax: phone number with country code, message, hour and minutes
    pywhatkit.sendwhatmsg('<phone_number_with_country_code>', 
    "Howdy! This message is Send Automatically by Python. CodeTipsAcademy.com!",
     19, 30)
    

    As before, the message doesn’t get sent automatically, and you have to manually click on the Send button. this issue will be solved in future of this article, keep reading.

    Send Whatsapp Image

    To send Images and GIF’s to WhatsApp users sendwhats_image function must be used. For Linux based distributions you need copyq installed on your system. Windows users can send Images (all formats) and GIF’s. For Linux based distributions, only JPEG and PNG are supported. For MacOS users, only JPEG is supported currently.

    import pywhatkit
    
    # syntax: phone number with country code, Image, caption
    pywhatkit.sendwhats_image('<phone_number_with_country_code>', 
    "C:\\Image.png", "Here is the image", 10, True, 5)
    

    As before, the message doesn’t get sent automatically, and you have to manually click on the Send button. this issue will be solved in next section, keep reading.

    Solve Issue of needing to press send button

    We need 2 additional Python libraries to automatically trigger the Send button. These are pyautogui and pynput. so, cammand below download these packages.

    pip install pyautogui pynput

    The send_whatsapp_message() function does the following:

    1. Opens Whatsapp Web and populates the input field with the specified message.
    2. Sleeps for 20 seconds to ensure everything has loaded properly.
    3. Clicks on the screen to ensure the correct window/tab is selected.
    4. Presses and releases the Enter key on the keyboard to send the message.

    If any of the steps fail, the exception is printed to the console.

    Here’s the entire code snippet for the function with a usage example:

    import time 
    import pywhatkit
    import pyautogui
    from pynput.keyboard import Key, Controller
    
    keyboard = Controller()
    
    def send_whatsapp_message(msg: str):
        try:
            pywhatkit.sendwhatmsg_instantly(
                phone_no='<phone_number_with_country_code>', 
                message=msg,
                tab_close=True
            )
            time.sleep(20)
            pyautogui.click()
            time.sleep(2)
            keyboard.press(Key.enter)
            keyboard.release(Key.enter)
            print("Message sent!")
        except Exception as e:
            print(str(e))
    
    
    if __name__ == "__main__":
        send_whatsapp_message(msg="Test message from a Python script!")