HOW TO TRAIN A MODEL STEP BY STEP IN PYTHON:
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, r2_score
data = {
'Hours': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'Scores': [10, 20, 30, 40, 50, 60, 70, 80, 85, 95]
}
df = pd.DataFrame(data)
print(df.head())
Hours Scores 0 1 10 1 2 20 2 3 30 3 4 40 4 5 50
plt.scatter(df['Hours'], df['Scores']) plt.xlabel('Hours Studied') plt.ylabel('Scores') plt.title('Hours vs Scores') plt.show()
X = df[['Hours']] # Independent variable y = df['Scores'] # Dependent variable #Now split 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)
model = LinearRegression() model.fit(X_train, y_train)y_pred = model.predict(X_test) print(y_pred)[88.01724138 20.73275862]
print("Mean Squared Error:", mean_squared_error(y_test, y_pred)) print("R2 Score:", r2_score(y_test, y_pred))Mean Squared Error: 4.820340368608807 R2 Score: 0.9954363641480627hours = np.array([[7.5]]) predicted_score = model.predict(hours) print(f"Predicted Score for 7.5 hours: {predicted_score[0]}")
plt.scatter(X, y, color='blue') plt.plot(X, model.predict(X), color='red') plt.xlabel('Hours Studied') plt.ylabel('Scores') plt.title('Linear Regression - Hours vs Scores') plt.show()Predicted Score for 7.5 hours: 73.59913793103448
No comments:
Post a Comment