how to build and train a machine learning model in Python

# Importing Required Libraries
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

# Load the iris dataset
iris = datasets.load_iris()

# Split the dataset into training and testing data
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)

# Initialize the KNN classifier and fit the training data
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)

# Predict the labels of the test data
y_pred = knn.predict(X_test)

# Print the accuracy of the model
print("Accuracy:", knn.score(X_test, y_test))

In this example, we first import the necessary libraries – scikit-learn and datasets. We then load the iris dataset and split it into training and testing data. We initialize the KNN classifier with n_neighbors=3 and fit the training data to the model. We then predict the labels of the test data and print the accuracy of the model.

Please note that this is a simple example, and machine learning models can be much more complex and require more data preprocessing and feature engineering before training. Additionally, there are many other libraries and frameworks for machine learning in Python, such as TensorFlow and PyTorch, which may be better suited for certain tasks.

Leave a Reply