a. Supervised Learning: In this type, the model learns from labeled training data, where each example has input features and corresponding target labels. Example code (Python - using scikit-learn library):
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Load the dataset
boston = datasets.load_boston()
X = boston.data
y = boston.target
# Split data 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 and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
b. Unsupervised Learning: In this type, the model learns patterns and relationships in unlabeled data, without any predefined target labels. Example code (Python - using scikit-learn library):
from sklearn.cluster import KMeans
from sklearn import datasets
# Load the dataset
iris = datasets.load_iris()
X = iris.data
# Create and train the model
model = KMeans(n_clusters=3)
model.fit(X)
# Get cluster labels
labels = model.labels_
c. Reinforcement Learning: In this type, an agent learns to interact with an environment and make decisions to maximize rewards or minimize penalties. Example code (Python - using OpenAI Gym library):
import gym
# Create the environment
env = gym.make('CartPole-v1')
# Define agent's behavior
def policy(observation):
# Implement your policy here
# Example: move left if the pole is leaning left, move right otherwise
if observation[2] < 0:
action = 0 # move left
else:
action = 1 # move right
return action
# Run the agent in the environment
observation = env.reset()
done = False
while not done:
action = policy(observation)
observation, reward, done, info = env.step(action)