Supervised machine learning is a type of machine learning where the algorithm learns from labeled data, which means it is provided with a dataset containing input features and their corresponding target labels. The goal is for the algorithm to learn a mapping from the input features to the target labels so that it can make predictions on new, unseen data.
Here's a simple example of supervised machine learning using linear regression to predict stock prices. In this example, we'll use Python and the scikit-learn library to create a linear regression model to predict the stock price of a company based on historical data.
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error data = pd.read_csv('stock_data.csv') X = data['Date'].values.reshape(-1, 1)
y = data['Price'].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = LinearRegression() model.fit(X_train, y_train) y_pred = model.predict(X_test) # Evaluate the model using Mean Squared Error (MSE)
mse = mean_squared_error(y_test, y_pred) print(f"Mean Squared Error: {mse}") # Visualize the results plt.figure(figsize=(12, 6)) plt.scatter(X_test, y_test, color='blue', label='Actual Prices') plt.plot(X_test, y_pred, color='red', linewidth=2, label='Predicted Prices') plt.title('Stock Price Prediction using Linear Regression') plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt.show()