Setting Up Scikit-learn and Training Your First Model
Scikit-learn is a Python library that provides algorithms for classification, regression, clustering, preprocessing, and model evaluation.
Installing Scikit-learn
Install Scikit-learn and its commonly used dependencies:
pip install scikit-learn pandas numpy
Import the libraries required for a basic machine learning workflow:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
Creating a Sample Dataset
Suppose you want to predict a student's examination score based on the number of hours spent studying.
df = pd.DataFrame({
"Study_Hours": [1, 2, 3, 4, 5, 6, 7, 8],
"Exam_Score": [35, 40, 50, 55, 65, 70, 80, 90]
})
X = df[["Study_Hours"]]
y = df["Exam_Score"]
print(df)
Here, X contains the input feature, while y contains the target that the model will learn to predict.
Splitting the Dataset
The model should be evaluated on observations that were not used for training.
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.25,
random_state=42
)
print("Training records:", len(X_train))
print("Testing records:", len(X_test))
The test_size=0.25 setting reserves 25% of the observations for testing. The random_state parameter makes the split reproducible.
Training the Model
model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Predictions:", predictions)
print("Actual values:", y_test.tolist())
The fit() method trains the model using the training data. The predict() method generates estimates for new input values.
Because this is a very small demonstration dataset, its results should not be treated as evidence of real-world predictive performance.
Python for Data Science
Vishalini A








