Weight to Height Calculator | Linear Regression
To build a weight-to-height calculator using linear regression, you’ll need to follow these steps:
- Collect Data: Gather a dataset that includes weight and height measurements.
- Preprocess Data: Clean the dataset (handle missing values, normalize if necessary).
- Build the Model: Use linear regression to model the relationship between height and weight.
- Train the Model: Fit the model to your data.
- Evaluate the Model: Assess the model’s performance using appropriate metrics.
- Predict: Use the trained model to predict height based on weight.
Here’s a step-by-step implementation in Python:
Step 1: Collect Data
We’ll use a sample dataset for the purpose of this example. Let’s assume we have the following data:
data = {
'weight': [60, 65, 70, 75, 80, 85, 90, 95, 100],
'height': [150, 155, 160, 165, 170, 175, 180, 185, 190]
}
Step 2: Preprocess Data
We’ll convert the data into a format suitable for modeling.
Step 3: Build the Model
We’ll use the LinearRegression
class from the sklearn
library.
Step 4: Train the Model
Fit the linear regression model to our data.
Step 5: Evaluate the Model
We can use metrics like R-squared to evaluate the performance of the model.
Step 6: Predict
We’ll create a function that takes a weight value and returns the predicted height.
Here is the complete code:
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# Sample dataset
data = {
'weight': [60, 65, 70, 75, 80, 85, 90, 95, 100],
'height': [150, 155, 160, 165, 170, 175, 180, 185, 190]
}
# Convert to DataFrame
df = pd.DataFrame(data)
# Features and target variable
X = df[['weight']] # Feature
y = df['height'] # Target variable
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create a Linear Regression model
model = LinearRegression()
# Train the model
model.fit(X_train, y_train)
# Make predictions on the testing set
y_pred = model.predict(X_test)
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"Mean Squared Error: {mse}")
print(f"R-squared: {r2}")
# Function to predict height based on weight
def predict_height(weight):
return model.predict(np.array([[weight]]))[0]
# Test the function
test_weight = 85
predicted_height = predict_height(test_weight)
print(f"Predicted height for weight {test_weight}kg is {predicted_height:.2f}cm")
This code covers the full process from data collection to prediction. You can replace the sample data with a larger, real-world dataset for better accuracy. The predict_height
function can then be used to calculate the height based on a given weight using the trained linear regression model.