Here is a Python implementation of a simple linear regression algorithm that can handle any numerical data provided. This implementation uses gradient descent to optimize the model parameters. It is coded in vanilla Python without the use of any external libraries.
class LinearRegression:
def __init__(self, learning_rate=0.01, iterations=1000):
self.learning_rate = learning_rate # Learning rate for gradient descent
self.iterations = iterations # Number of iterations for training
self.weights = [] # Weights (coefficients) for the model
self.bias = 0 # Bias (intercept) term
def fit(self, X, y):
"""
Train the linear regression model using gradient descent.
Parameters:
X (list of lists): Feature matrix where each sublist represents a sample and contains feature values.
y (list): Target vector containing the target values.
"""
n_samples = len(y) # Number of samples
n_features = len(X[0]) # Number of features
# Initialize weights and bias to zero
self.weights = [0.0 for _ in range(n_features)]
self.bias = 0.0
# Perform gradient descent
for _ in range(self.iterations):
y_predicted = self._predict(X)
# Initialize gradients
dw = [0.0 for _ in range(n_features)]
db = 0.0
# Compute gradients
for i in range(n_samples):
error = y_predicted[i] - y[i]
for j in range(n_features):
dw[j] += (1 / n_samples) * error * X[i][j]
db += (1 / n_samples) * error
# Update weights and bias
for j in range(n_features):
self.weights[j] -= self.learning_rate * dw[j]
self.bias -= self.learning_rate * db
def predict(self, X):
"""
Predict target values for given feature matrix X.
Parameters:
X (list of lists): Feature matrix where each sublist represents a sample and contains feature values.
Returns:
list: Predicted target values.
"""
return self._predict(X)
def _predict(self, X):
y_predicted = []
for sample in X:
prediction = self.bias
for w, x in zip(self.weights, sample):
prediction += w * x
y_predicted.append(prediction)
return y_predicted
# Example usage:
if __name__ == "__main__":
# Sample data: Features and target values
X = [[1], [2], [3], [4], [5]] # Feature matrix with one feature
y = [5, 7, 9, 11, 13] # Target values
# Create an instance of LinearRegression
reg = LinearRegression(learning_rate=0.01, iterations=1000)
# Train the model
reg.fit(X, y)
# Predict target values for new data
X_new = [[6], [7], [8]]
predictions = reg.predict(X_new)
# Output the predictions
print("Predicted values:", predictions)
How to Use the Code:
-
Define your data:
X: A list of lists where each sublist represents a data sample and contains numerical feature values.
y: A list of numerical target values corresponding to each sample in X.
-
Create a Model Instance:
reg = LinearRegression(learning_rate=0.01, iterations=1000)
- You can adjust the
learning_rate and iterations parameters to improve model training as needed.
-
Train the Model:
reg.fit(X, y)
- This method trains the model using the data you provided.
-
Make Predictions:
X_new = [[value1], [value2], ...] # New data for prediction
predictions = reg.predict(X_new)
- Replace
value1, value2, etc., with the feature values of the new samples you want to predict.
-
Output Predictions:
print("Predicted values:", predictions)
- This will display the predicted target values for your new data.
Example Explanation:
In the provided example:
- We have a simple dataset where the relationship between
X and y is linear.
- The model is trained to learn this relationship.
- After training, the model predicts target values for new feature values
[6], [7], [8].
- The output will display the predicted target values for these new samples.
Notes:
- This implementation uses gradient descent to optimize the weights and bias.
- The learning rate and number of iterations are crucial parameters:
- Learning Rate (
learning_rate): Determines the step size during the optimization. A smaller learning rate might lead to slower convergence, while a larger one might overshoot the minimum.
- Iterations (
iterations): Number of times the algorithm will iterate over the training data to update the weights and bias.
- The code is designed to handle multiple features. If your data has more than one feature, make sure each sample in
X contains all feature values.
Customization:
- You can extend the model to handle more complex datasets by adjusting the learning rate, iterations, and ensuring your
X and y data are appropriately structured.
- For datasets with multiple features, ensure that
X is structured correctly, with each inner list containing all feature values for a single sample.