When R² Turns Negative — And What It Really Means

Negative R Squared

We’re often told that the R² value in a regression model ranges between 0 and 1. A score close to 1? Great model! A score near 0? Not so great.

But here’s a question most textbooks skip:
Can R² be negative?

Yes. And when it is, it’s a big red flag.
Let me walk you through why — with code, plots, and a surprising mathematical twist.

When Guessing Outperforms Your Model

Imagine you’re trying to predict house prices.
But instead of using real-world features like square footage or number of rooms…
You train your model using just the row index of the dataset (0, 1, 2, …).

You know it won’t perform well — but how badly?

Let’s find out:

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
import matplotlib.pyplot as plt

# Actual data: decreasing trend
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([10, 8, 6, 4, 2])

# Bad model: predict constant (wrong!) values
y_bad = np.array([5, 5, 5, 5, 5])
model = LinearRegression()
model.fit(X, y_bad)  # Fitting on wrong y

# Predict on true y values
y_pred = model.predict(X)
r2 = r2_score(y, y_pred)

# Output R²
print("R² Score:", r2)

# Plot
plt.scatter(X, y, color='blue', label='Actual data')
plt.plot(X, y_pred, color='red', label='Bad model')
plt.axhline(np.mean(y), color='green', linestyle='--', label='Mean of y')
plt.title(f"Bad Model Fit (R² = {r2:.2f})")
plt.legend()
plt.grid(True)
plt.show()

The model is worse than predicting the average, which gives you a negative R². That’s not a bug — that’s your model admitting defeat.

So :

  • R² is not a square in the arithmetic sense.
  • Squaring a number like x^2 is different — even complex numbers behave differently.
  • But R² is about how well your model captures variability. And if it performs poorly, R² will let you know — even with a minus sign.
Bottom line:

If you get a negative R², it’s your model’s polite way of saying:

“You’d be better off guessing the mean.”

What Does Negative R² Really Mean?

Mathematically, R² is defined as:

textCopyEditR² = 1 - (SS_res / SS_tot)
  • SS_res: residual sum of squares (errors of the model)
  • SS_tot: total sum of squares (errors of the mean-only model)

If your model’s error is larger than that of a “dumb” average-based prediction,
then SS_res > SS_tot → R² becomes negative.

So, in plain English:

A negative R² means your model performs worse than no model at all.

Let’s Clear Up a Common Misconception: “Squared” Doesn’t Mean Power

The name R-squared misleads many into thinking it’s always non-negative — like squaring a number.

But here’s the catch:

  • The “squared” in R² comes from squaring residuals (the errors),
    not from squaring some kind of correlation coefficient.
  • It’s a statistical measure, not a mathematical power operation.

In fact, real squaring behaves differently:

x = 3
print(x**2)  # 9
print((-3)**2)  # 9

Always positive.

But when you move into complex numbers, things get spicier:

import cmath
z = complex(0, 1)  # i
print(z**2)  # Output: (-1+0j)

Yes — i² = -1.
So, squaring in complex math can result in negative values.

Key Takeaways for Readers

  1. R² < 0 means your model is worse than guessing.
    Always check your features and assumptions.
  2. “Squared” in R² doesn’t mean it behaves like math powers.
    It’s a statistical ratio, not a square root or power-of-two operation.
  3. In complex numbers, squared values can be negative — just like R².
    That’s a fun coincidence, not a cause — but it’s a helpful analogy.
  4. Always use R² with other metrics: residual plots, p-values, and domain intuition.

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!")