47 Exp2 Dav
47 Exp2 Dav
Experiment No.: 02
Roll Number: 47
Evaluation
Marks
Performance Indicator Max. Marks
Obtaine
d
Performance 5
Understanding 5
Journal work and timely submission. 10
Total 20
Objective:- To understand the use of simple linear regression techniques by implementing user define
dataset and importing dataset.
Description:
Procedure:
LM(): Fits a linear model in R. Example: model <- lm(Sales ~ TV, data = df) fits a
regression model predicting Sales from TV ad spend.
Predict(): Makes predictions using the fitted model. Example: predictions <- predict(model,
newdata = test_data).
PROGRAM:- 1. Write a Simple Linear Regression program for user define dataset
X=c(1,2,3,4)
Y=c(3,4,5,7)
plot(X,Y)
relation=lm(Y~X)
print(relation)
print(summary(relation)
) a=data.frame(X=170)
result=predict(relation,a
) print(result)
png(file="linearregression.png")
plot(Y,X,col="green",main="Height & Weight Regression",abline(lm(X~Y)),
cex=1.3,pch=16,Xlab="Weight in kg",Ylab="Height in cm")
dev.off()
RESULT:
Thus the implementation of linear regression was executed and verified successfully.
OUTPUT:
PROGRAM:- 2. Write a Simple Linear Regression program for in-built dataset
data()
print(Orange)
data (Orange)
head (Orange)
print(model)
print(predict(model))
summary(model)
Output
PROGRAM 2:
PROGRAM:- 3. Write a Simple Linear Regression program for external datasets
print(head (data))
print(relation)
print(summary(relation))
Output
With Python:
1] PROGRAM:- 1. Write a Simple Linear Regression program for user define
dataset Code:
import numpy as np
import pandas as pd
X = np.array([1, 2, 3, 4]).reshape(-1, 1)
Y = np.array([3, 4, 5, 7])
plt.scatter(X, Y)
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
model = LinearRegression()
model.fit(X, Y)
print(f'Coefficients: {model.coef_}')
print(f'Intercept: {model.intercept_}')
a = pd.DataFrame({'X': [170]})
result = model.predict(a)
Output:
2]Program 2: Write a Simple Linear Regression program for external datasets
Code:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
plt.scatter(data['TV'], data['Sales'])
plt.xlabel('TV Advertising Budget')
plt.ylabel('Sales')
plt.title('TV Advertising Budget vs Sales')
plt.show()
X = data['TV'].values.reshape(-1, 1)
y = data['Sales'].values
model = LinearRegression()
model.fit(X, y)
print("Intercept:", model.intercept_)
print("Slope:", model.coef_[0])
y_pred = model.predict(X)
print("Mean Squared Error:", mean_squared_error(y, y_pred))
print("R^2 Score:", r2_score(y, y_pred))
Output:
Conclusion:
1. Function used for linear regression in R is ‘lm(formula, data)’ (Function_name (Parameters)).