exam-sub 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # exam-sub
2
+
3
+ A simple CLI tool for accessing college subject study materials directly from the terminal.
4
+
5
+ ## Features
6
+
7
+ - AIOP study material
8
+ - DIV - Data Interface & Visualization
9
+ - Big Data & Hadoop
10
+ - MLF - Machine Learning Fundamentals
11
+ - Interactive subject selection
12
+ - Direct subject commands
13
+
14
+ ## Installation
15
+
16
+ Install globally using npm:
17
+
18
+ ```bash
19
+ npm install -g exam-sub
package/bin/cli.js ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { select } = require("@inquirer/prompts");
6
+
7
+ const dataPath = path.join(__dirname, "..", "data");
8
+
9
+ const subjects = {
10
+ aiop: {
11
+ name: "AIOP",
12
+ file: "aiop.txt"
13
+ },
14
+
15
+ div: {
16
+ name: "DIV - Data Interface & Visualization",
17
+ file: "div.txt"
18
+ },
19
+
20
+ bdh: {
21
+ name: "Big Data & Hadoop",
22
+ file: "bdh.txt"
23
+ },
24
+
25
+ mlf: {
26
+ name: "MLF - Machine Learning Fundamentals",
27
+ file: "mlf.txt"
28
+ }
29
+ };
30
+
31
+
32
+ // Show subject data
33
+ function showSubject(subjectKey) {
34
+ const subject = subjects[subjectKey];
35
+
36
+ if (!subject) {
37
+ console.log("Subject not found.");
38
+ return;
39
+ }
40
+
41
+ const filePath = path.join(dataPath, subject.file);
42
+
43
+ console.clear();
44
+
45
+ console.log("========================================");
46
+ console.log(` ${subject.name}`);
47
+ console.log("========================================");
48
+ console.log("");
49
+
50
+ if (!fs.existsSync(filePath)) {
51
+ console.log("Data file not found:");
52
+ console.log(filePath);
53
+ return;
54
+ }
55
+
56
+ const data = fs.readFileSync(filePath, "utf8");
57
+
58
+ console.log(data);
59
+
60
+ console.log("");
61
+ console.log("========================================");
62
+ console.log(" END OF DATA");
63
+ console.log("========================================");
64
+ }
65
+
66
+
67
+ // Main menu
68
+ async function main() {
69
+ console.clear();
70
+
71
+ console.log("========================================");
72
+ console.log(" EXAM SUBJECTS CLI");
73
+ console.log("========================================");
74
+ console.log("");
75
+
76
+ const selectedSubject = await select({
77
+ message: "Select a subject:",
78
+ choices: [
79
+ {
80
+ name: "AIOP",
81
+ value: "aiop"
82
+ },
83
+ {
84
+ name: "DIV - Data Interface & Visualization",
85
+ value: "div"
86
+ },
87
+ {
88
+ name: "Big Data & Hadoop",
89
+ value: "bdh"
90
+ },
91
+ {
92
+ name: "MLF - Machine Learning Fundamentals",
93
+ value: "mlf"
94
+ }
95
+ ]
96
+ });
97
+
98
+ showSubject(selectedSubject);
99
+ }
100
+
101
+
102
+ // Direct command support
103
+ const command = process.argv[2];
104
+
105
+ if (command) {
106
+ const commandName = command.toLowerCase();
107
+
108
+ if (subjects[commandName]) {
109
+ showSubject(commandName);
110
+ } else {
111
+ console.log(`Unknown subject: ${command}`);
112
+ console.log("");
113
+ console.log("Available subjects:");
114
+ console.log(" aiop");
115
+ console.log(" div");
116
+ console.log(" bdh");
117
+ console.log(" mlf");
118
+ }
119
+ } else {
120
+ main();
121
+ }
package/data/aiop.txt ADDED
@@ -0,0 +1,162 @@
1
+ Q1. Implement AI Problem-Solving Techniques using Python
2
+ Aim: To implement a simple AI problem-solving technique using Breadth First Search (BFS).
3
+ Python Program:
4
+ from collections import deque
5
+ graph = {
6
+ 'A': ['B', 'C'],
7
+ 'B': ['D', 'E'],
8
+ 'C': ['F'],
9
+ 'D': [],
10
+ 'E': ['F'],
11
+ 'F': []
12
+ }
13
+ def bfs(start, goal):
14
+ queue = deque([[start]])
15
+ visited = set()
16
+ while queue:
17
+ path = queue.popleft()
18
+ node = path[-1]
19
+ if node == goal:
20
+ return path
21
+ if node not in visited:
22
+ visited.add(node)
23
+ for neighbour in graph[node]:
24
+ new_path = path + [neighbour]
25
+ queue.append(new_path)
26
+ print("Path:", bfs('A', 'F'))
27
+ Example Output:
28
+ Path: ['A', 'C', 'F']
29
+ Explanation: - BFS searches level by level.
30
+ - It starts from node A.
31
+ - It checks neighbouring nodes.
32
+ - It finds the path from A to F.
33
+
34
+ Q3. Develop a Context-Aware Rule-Based Chatbot using Python
35
+ Aim: To create a chatbot that responds according to the context of the conversation.
36
+ Python Program:
37
+ context = ""
38
+ while True:
39
+ user = input("You: ").lower()
40
+ if user == "bye":
41
+ print("Bot: Goodbye!")
42
+ break
43
+ if "hello" in user or "hi" in user:
44
+ print("Bot: Hello! How can I help you?")
45
+ elif "my name is" in user:
46
+ context = user.split("my name is")[-1].strip()
47
+ print("Bot: Nice to meet you, " + context)
48
+ elif "what is my name" in user:
49
+ if context:
50
+ print("Bot: Your name is " + context)
51
+ else:
52
+ print("Bot: I don't know your name yet.")
53
+ elif "course" in user:
54
+ print("Bot: Which course are you studying?")
55
+ else:
56
+ print("Bot: Please tell me more.")
57
+ Example Output:
58
+ You: hi
59
+ Bot: Hello! How can I help you?
60
+ You: my name is Sunny
61
+ Bot: Nice to meet you, sunny
62
+ You: what is my name
63
+ Bot: Your name is sunny
64
+ Explanation: The chatbot stores information in the context variable and uses it in later conversations.
65
+
66
+ Q4. Implement an Intent-Based Chatbot using Rule Matching and Pattern
67
+ Processing
68
+ Aim: To identify the user's intent using simple keyword/pattern matching.
69
+ Python Program:
70
+ import re
71
+ patterns = {
72
+ "greeting": r"\b(hi|hello|hey)\b",
73
+ "courses": r"\b(course|courses|subjects)\b",
74
+ "fees": r"\b(fees|fee|payment)\b",
75
+ "bye": r"\b(bye|goodbye)\b"
76
+ }
77
+ def get_intent(message):
78
+ for intent, pattern in patterns.items():
79
+ if re.search(pattern, message.lower()):
80
+ return intent
81
+ return "unknown"
82
+ while True:
83
+ user = input("You: ")
84
+ intent = get_intent(user)
85
+ if intent == "greeting":
86
+ print("Bot: Hello! How can I help you?")
87
+ elif intent == "courses":
88
+ print("Bot: We offer Computer Science and IT courses.")
89
+ elif intent == "fees":
90
+ print("Bot: Please contact the college office for fee details.")
91
+ elif intent == "bye":
92
+ print("Bot: Goodbye!")
93
+ break
94
+ else:
95
+ print("Bot: Sorry, I don't understand.")
96
+ Example Output:
97
+ You: Hello
98
+ Bot: Hello! How can I help you?
99
+ You: Tell me about courses
100
+ Bot: We offer Computer Science and IT courses.
101
+ You: What are the fees?
102
+ Bot: Please contact the college office for fee details.
103
+ Explanation: - Intent means what the user wants.
104
+ - Regular expressions (re) identify patterns.
105
+ - The chatbot gives a response according to the detected intent.
106
+
107
+ Q5. Implement a Rule-Based Recommendation Chatbot using Forward
108
+ Chaining
109
+ Aim: To recommend a course using rules and forward chaining.
110
+ Python Program:
111
+ facts = set()
112
+ print("Answer with yes or no.")
113
+ python = input("Do you like Python? ").lower()
114
+ web = input("Do you like Web Development? ").lower()
115
+ data = input("Do you like Data Analysis? ").lower()
116
+ if python == "yes":
117
+ facts.add("python")
118
+ if web == "yes":
119
+ facts.add("web")
120
+ if data == "yes":
121
+ facts.add("data")
122
+ # Forward chaining rules
123
+ if "python" in facts and "data" in facts:
124
+ print("Recommendation: Machine Learning / Data Science")
125
+ elif "web" in facts and "python" in facts:
126
+ print("Recommendation: Python Full Stack Development")
127
+ elif "web" in facts:
128
+ print("Recommendation: Web Development")
129
+ elif "python" in facts:
130
+ print("Recommendation: Python Programming")
131
+ else:
132
+ print("Recommendation: Explore basic computer courses.")
133
+ Example Output:
134
+ Do you like Python? yes
135
+ Do you like Web Development? no
136
+ Do you like Data Analysis? yes
137
+ Recommendation: Machine Learning / Data Science
138
+ Explanation: Forward chaining starts with known facts and applies rules to reach a conclusion.
139
+ Python + Data Analysis → Machine Learning
140
+
141
+ Q6. Develop an Intelligent Academic-Assistance Chatbot using Python
142
+ Aim: To create a chatbot that helps students with common academic queries.
143
+ Python Program:
144
+ while True:
145
+ user = input("Student: ").lower()
146
+ if "hello" in user or "hi" in user:
147
+ print("Bot: Hello! How can I help you?")
148
+ elif "exam" in user:
149
+ print("Bot: Prepare important topics and practice previous papers.")
150
+ elif "assignment" in user:
151
+ print("Bot: Complete your assignment before the submission date.")
152
+ elif "attendance" in user:
153
+ print("Bot: Please check your attendance with the college portal.")
154
+ elif "study" in user or "study plan" in user:
155
+ print("Bot: Study 2-3 hours daily and revise important topics.")
156
+ elif "python" in user:
157
+ print("Bot: Practice Python basics, functions, lists and OOP.")
158
+ elif "bye" in user:
159
+ print("Bot: Good luck with your studies!")
160
+ break
161
+ else:
162
+ print("Bot: Sorry, I don't have information about that.")
package/data/bdh.txt ADDED
@@ -0,0 +1,157 @@
1
+ University and Hospital database questions using TEXTFILE storage format.
2
+ Question 9 – University Database
3
+ -- ==========================================
4
+ -- Q9: UNIVERSITY
5
+ -- ==========================================
6
+ -- Create Database
7
+ CREATE DATABASE university_db;
8
+ -- Select Database
9
+ USE university_db;
10
+ -- Create Table
11
+ CREATE TABLE students (
12
+ student_id INT,
13
+ name STRING,
14
+ course STRING,
15
+ marks FLOAT
16
+ )
17
+ STORED AS TEXTFILE;
18
+ -- Insert Sample Values
19
+ INSERT INTO students VALUES
20
+ (101, 'John', 'Computer Science', 85),
21
+ (102, 'Alice', 'Mathematics', 72),
22
+ (103, 'Bob', 'Physics', 45),
23
+ (104, 'Charlie', 'Mathematics', 65);
24
+ -- 1. Retrieve Computer Science students
25
+ SELECT *
26
+ FROM students
27
+ WHERE course = 'Computer Science';
28
+ -- 2. Delete students whose marks are below 50
29
+ DELETE FROM students
30
+ WHERE marks < 50;
31
+ -- 3. Add 10 bonus marks to Mathematics students
32
+ UPDATE students
33
+ SET marks = marks + 10
34
+ WHERE course = 'Mathematics';
35
+ -- 4. Delete student whose student_id is 102
36
+ DELETE FROM students
37
+ WHERE student_id = 102;
38
+ Question 11 – Hospital Database
39
+ -- ==========================================
40
+ -- Q11: HOSPITAL
41
+ -- ==========================================
42
+ -- Create Database
43
+ CREATE DATABASE hospital_db;
44
+ -- Select Database
45
+ USE hospital_db;
46
+ -- Create Table
47
+ CREATE TABLE patients (
48
+ patient_id INT,
49
+ patient_name STRING,
50
+ age INT,
51
+ disease STRING
52
+ )
53
+ STORED AS TEXTFILE;
54
+ -- Insert Sample Values
55
+ INSERT INTO patients VALUES
56
+ (1, 'Rahul', 45, 'Diabetes'),
57
+ (2, 'Amit', 30, 'Hypertension'),
58
+ (3, 'Priya', 16, 'Fever'),
59
+ (4, 'Neha', 55, 'Diabetes'),
60
+ (8, 'Raj', 40, 'Hypertension');
61
+ -- 1. Retrieve patients with Diabetes
62
+ SELECT *
63
+ FROM patients
64
+ WHERE disease = 'Diabetes';
65
+ -- 2. Delete patients whose age is below 18
66
+ DELETE FROM patients
67
+ WHERE age < 18;
68
+ -- 3. Change Hypertension to Chronic Hypertension
69
+ UPDATE patients
70
+ SET disease = 'Chronic Hypertension'
71
+ WHERE disease = 'Hypertension';
72
+ -- 4. Delete patient whose patient_id is 8
73
+ DELETE FROM patients
74
+ WHERE patient_id = 8;
75
+
76
+
77
+ Complete Hive code for the University (Q9) and Hospital (Q11) database questions, including database creation,
78
+ table creation, sample data, SELECT, DELETE and UPDATE operations.
79
+ Question 9 – University Database
80
+ -- ==========================================
81
+ -- Q9: UNIVERSITY
82
+ -- ==========================================
83
+ -- Create Database
84
+ CREATE DATABASE university_db;
85
+ -- Select Database
86
+ USE university_db;
87
+ -- Create Table
88
+ CREATE TABLE students (
89
+ student_id INT,
90
+ name STRING,
91
+ course STRING,
92
+ marks FLOAT
93
+ )
94
+ STORED AS ORC
95
+ TBLPROPERTIES ('transactional'='true');
96
+ -- Insert Sample Values
97
+ INSERT INTO students VALUES
98
+ (101, 'John', 'Computer Science', 85),
99
+ (102, 'Alice', 'Mathematics', 72),
100
+ (103, 'Bob', 'Physics', 45),
101
+ (104, 'Charlie', 'Mathematics', 65);
102
+ -- 1. Retrieve Computer Science students
103
+ SELECT *
104
+ FROM students
105
+ WHERE course = 'Computer Science';
106
+ -- 2. Delete students whose marks are below 50
107
+ DELETE FROM students
108
+ WHERE marks < 50;
109
+ -- 3. Add 10 bonus marks to Mathematics students
110
+ UPDATE students
111
+ SET marks = marks + 10
112
+ WHERE course = 'Mathematics';
113
+ -- 4. Delete student whose student_id is 102
114
+ DELETE FROM students
115
+ WHERE student_id = 102;
116
+ Question 11 – Hospital Database
117
+ -- ==========================================
118
+ -- Q11: HOSPITAL
119
+ -- ==========================================
120
+ -- Create Database
121
+ CREATE DATABASE hospital_db;
122
+ -- Select Database
123
+ USE hospital_db;
124
+ -- Create Table
125
+ CREATE TABLE patients (
126
+ patient_id INT,
127
+ patient_name STRING,
128
+ age INT,
129
+ disease STRING
130
+ )
131
+ STORED AS ORC
132
+ TBLPROPERTIES ('transactional'='true');
133
+ -- Insert Sample Values
134
+ INSERT INTO patients VALUES
135
+ (1, 'Rahul', 45, 'Diabetes'),
136
+ (2, 'Amit', 30, 'Hypertension'),
137
+ (3, 'Priya', 16, 'Fever'),
138
+ (4, 'Neha', 55, 'Diabetes'),
139
+ (8, 'Raj', 40, 'Hypertension');
140
+ -- 1. Retrieve patients with Diabetes
141
+ SELECT *
142
+ FROM patients
143
+ WHERE disease = 'Diabetes';
144
+ -- 2. Delete patients whose age is below 18
145
+ DELETE FROM patients
146
+ WHERE age < 18;
147
+ -- 3. Change Hypertension to Chronic Hypertension
148
+ UPDATE patients
149
+ SET disease = 'Chronic Hypertension'
150
+ WHERE disease = 'Hypertension';
151
+ -- 4. Delete patient whose patient_id is 8
152
+ DELETE FROM patients
153
+ WHERE patient_id = 8;
154
+ Note: These examples use ORC transactional tables so that Hive UPDATE and DELETE operations can be
155
+ performed. If your college specifically requires TEXTFILE syntax, replace the storage clause as instructed by your
156
+ lab/teacher.
157
+  
package/data/div.txt ADDED
@@ -0,0 +1,83 @@
1
+ MongoDB CRUD Operations – CollegeDB
2
+ Complete practical code for Questions 1–3 using one MongoDB database with separate collections: employees,
3
+ students, and books.
4
+ Complete Code
5
+ // Create / Select Database
6
+ use collegeDB
7
+ // ==========================================
8
+ // Q1: EMPLOYEES
9
+ // ==========================================
10
+ // Create Collection
11
+ db.createCollection("employees")
12
+ // Insert Values
13
+ db.employees.insertMany([
14
+ {name:"Alice", position:"Manager", salary:70000},
15
+ {name:"Bob", position:"Developer", salary:55000},
16
+ {name:"Charlie", position:"HR", salary:45000}
17
+ ])
18
+ // Read - Salary greater than 50000
19
+ db.employees.find({salary:{$gt:50000}})
20
+ // Update - Increase Developer salary by 10%
21
+ db.employees.updateMany(
22
+ {position:"Developer"},
23
+ {$mul:{salary:1.10}}
24
+ )
25
+ // Delete - Remove Charlie
26
+ db.employees.deleteOne({name:"Charlie"})
27
+ // ==========================================
28
+ // Q2: STUDENTS
29
+ // ==========================================
30
+ // Create Collection
31
+ db.createCollection("students")
32
+ // Insert Values
33
+ db.students.insertOne({
34
+ name:"John Doe",
35
+ age:22,
36
+ course:"Computer Science"
37
+ })
38
+ // Read - Age greater than 20
39
+ db.students.find({age:{$gt:20}})
40
+ // Update - Change course
41
+ db.students.updateOne(
42
+ {name:"John Doe"},
43
+ {$set:{course:"Data Science"}}
44
+ )
45
+ // Delete - Age less than 21
46
+ db.students.deleteMany({age:{$lt:21}})
47
+ // ==========================================
48
+ // Q3: BOOKS
49
+ // ==========================================
50
+ // Create Collection
51
+ db.createCollection("books")
52
+ // Insert Values
53
+ db.books.insertOne({
54
+ title:"The Alchemist",
55
+ author:"Paulo Coelho",
56
+ publishedYear:1988,
57
+ copiesSold:65000000
58
+ })
59
+ // Read - Books published before 2000
60
+ db.books.find({publishedYear:{$lt:2000}})
61
+ // Update - Add rating
62
+ db.books.updateOne(
63
+ {title:"The Alchemist"},
64
+ {$set:{rating:4.8}}
65
+ )
66
+ // Delete - Books with copies sold less than 1 million
67
+ db.books.deleteMany({copiesSold:{$lt:1000000}})
68
+ Fresh Run / Reset Database Collections
69
+ If you run the practical multiple times, existing collections and data may cause duplicate records or collection-exists
70
+ errors. Use the following commands first when you want a clean run.
71
+ use collegeDB
72
+ db.employees.drop()
73
+ db.students.drop()
74
+ db.books.drop()
75
+ Important MongoDB Note
76
+ MongoDB does not use tables like MySQL. MongoDB stores data in collections. For this practical, employees,
77
+ students, and books are collections inside the same collegeDB database.
78
+ CRUD Summary
79
+ Create: createCollection(), insertOne(), insertMany()
80
+ Read: find()
81
+ Update: updateOne(), updateMany()
82
+ Delete: deleteOne(), deleteMany()
83
+  
package/data/mlf.txt ADDED
@@ -0,0 +1,347 @@
1
+ Q1 to Q6: Short, Simple and Easy-to-Understand Solutions
2
+ Question 1: Sales Data EDA
3
+ Aim: Perform Exploratory Data Analysis on sales data to understand patterns, missing values and unusual transactions.
4
+ 1. Import libraries and load data
5
+ import pandas as pd
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ import seaborn as sns
9
+ df = pd.read_csv("sales_data.csv")
10
+ print(df.head())
11
+ print(df.shape)
12
+ print(df.info())
13
+
14
+ 2. Convert Date
15
+ df['Date'] = pd.to_datetime(df['Date'])
16
+ print(df['Date'].dtype)
17
+
18
+ 3. Identify variable types
19
+ print(df.dtypes)
20
+ Typical types: Order_ID – integer/object; Date – DateTime; Product, Category, Region, Customer_Type – categorical;
21
+ Quantity, Unit_Price, Discount, Sales – numerical.
22
+
23
+ 4. Check and 5. Handle missing values
24
+ print(df.isnull().sum())
25
+ df['Quantity'] = df['Quantity'].fillna(df['Quantity'].median())
26
+ df['Unit_Price'] = df['Unit_Price'].fillna(df['Unit_Price'].median())
27
+ df['Discount'] = df['Discount'].fillna(df['Discount'].median())
28
+ df['Sales'] = df['Sales'].fillna(df['Sales'].median())
29
+ df['Region'] = df['Region'].fillna(df['Region'].mode()[0])
30
+ df['Category'] = df['Category'].fillna(df['Category'].mode()[0])
31
+
32
+ 6. Univariate analysis
33
+ sns.histplot(df['Sales'], kde=True)
34
+ plt.title("Sales Distribution")
35
+ plt.show()
36
+ sns.histplot(df['Quantity'], kde=True)
37
+ plt.title("Quantity Distribution")
38
+ plt.show()
39
+
40
+ 7. Bivariate analysis
41
+ # Quantity vs Sales
42
+ sns.scatterplot(x='Quantity', y='Sales', data=df)
43
+ plt.show()
44
+ # Discount vs Sales
45
+ sns.scatterplot(x='Discount', y='Sales', data=df)
46
+ plt.show()
47
+ # Region vs Sales
48
+ sns.boxplot(x='Region', y='Sales', data=df)
49
+ plt.show()
50
+
51
+ 8. Multivariate analysis
52
+ sns.pairplot(df[['Quantity', 'Unit_Price', 'Discount', 'Sales']])
53
+ plt.show()
54
+
55
+ 9. Detect sales outliers using IQR
56
+
57
+ Q1 = df['Sales'].quantile(0.25)
58
+ Q3 = df['Sales'].quantile(0.75)
59
+ IQR = Q3 - Q1
60
+ lower = Q1 - 1.5 * IQR
61
+ upper = Q3 + 1.5 * IQR
62
+ outliers = df[(df['Sales'] < lower) | (df['Sales'] > upper)]
63
+ print("Number of outliers:", len(outliers))
64
+ print(outliers)
65
+
66
+ 10. Handle outliers and 11. plot final distribution
67
+ df_clean = df[(df['Sales'] >= lower) & (df['Sales'] <= upper)]
68
+ sns.histplot(df_clean['Sales'], kde=True)
69
+ plt.title("Sales Distribution After Outlier Removal")
70
+ plt.show()
71
+ Conclusion: EDA helps understand sales distribution, relationships, regional patterns, missing values and unusual
72
+ transactions. IQR is used to detect sales outliers.
73
+ Question 2: Automated EDA and Statistical Relationship Analysis
74
+ Aim: Analyze student academic performance and relationships between study habits, attendance, assignments and
75
+ marks.
76
+ A. Data Loading and Basic Analysis
77
+ import pandas as pd
78
+ import numpy as np
79
+ import matplotlib.pyplot as plt
80
+ import seaborn as sns
81
+ df = pd.read_csv("student_performance.csv")
82
+ print(df.head())
83
+ print(df.tail())
84
+ print("Shape:", df.shape)
85
+ print("Columns:", df.columns)
86
+ print("Data Types:")
87
+ print(df.dtypes)
88
+ print("Statistical Summary:")
89
+ print(df.describe())
90
+ print("Missing values:")
91
+ print(df.isnull().sum())
92
+ print("Duplicates:", df.duplicated().sum())
93
+ print("Unique values:")
94
+ print(df.nunique())
95
+ Handle missing and duplicate values:
96
+ df = df.fillna(df.median(numeric_only=True))
97
+ df = df.drop_duplicates()
98
+ B1. D-Tale
99
+ # Install once in terminal:
100
+ # pip install dtale
101
+ import dtale
102
+ dtale.show(df)
103
+ D-Tale provides an interactive overview, column statistics, missing values, correlations, histograms, scatter plots and
104
+ outlier information.
105
+ B2. YData Profiling / Pandas Profiling
106
+ # Install once:
107
+ # pip install ydata-profiling
108
+ from ydata_profiling import ProfileReport
109
+ profile = ProfileReport(df, title="Student Performance Report")
110
+ profile.to_file("student_profile.html")
111
+ The HTML report contains dataset overview, variable statistics, missing values, correlations, distributions, duplicates and
112
+ warnings.
113
+ B3. Sweetviz
114
+ # Install once:
115
+ # pip install sweetviz
116
+ import sweetviz as sv
117
+ report = sv.analyze(df)
118
+ report.show_html("sweetviz_report.html")
119
+ Sweetviz automatically shows distributions, associations, correlations, missing values and summary statistics.
120
+ B4. AutoViz
121
+ # Install once:
122
+ # pip install autoviz
123
+ from autoviz.AutoViz_Class import AutoViz_Class
124
+ AV = AutoViz_Class()
125
+ AV.AutoViz("student_performance.csv")
126
+ AutoViz automatically creates visualizations and helps identify important relationships.
127
+ C. Covariance and Correlation
128
+ num_cols = [
129
+ 'Study_Hours',
130
+ 'Attendance',
131
+ 'Assignment_Marks',
132
+ 'Internal_Marks',
133
+ 'Final_Marks'
134
+ ]
135
+ covariance = df[num_cols].cov()
136
+ print(covariance)
137
+ correlation = df[num_cols].corr()
138
+ print(correlation)
139
+ plt.figure(figsize=(8, 6))
140
+ sns.heatmap(correlation, annot=True, cmap='coolwarm')
141
+ plt.title("Correlation Matrix")
142
+ plt.show()
143
+ Correlation ranges from -1 to +1. +1 means strong positive relationship, 0 means no linear relationship, and -1 means
144
+ strong negative relationship. The strongest positive correlation with Final_Marks is the variable whose correlation value
145
+ with Final_Marks is closest to +1. Weak variables have correlation values close to 0. Highly correlated independent
146
+ variables have values close to +1 or -1.
147
+ Conclusion: Automated EDA makes analysis faster by generating statistics, graphs, correlations, missing-value
148
+ information and warnings.
149
+ Question 3: Student Performance Prediction
150
+ Aim: Predict Final_Marks using Linear Regression.
151
+ Task 1. Load and preprocess
152
+ import pandas as pd
153
+ import numpy as np
154
+ df = pd.read_csv("student_performance.csv")
155
+ print(df.head())
156
+ print(df.shape)
157
+ print(df.dtypes)
158
+ print(df.describe())
159
+ print(df.isnull().sum())
160
+ df = df.fillna(df.median(numeric_only=True))
161
+ df = df.drop_duplicates()
162
+ Task 2. Apply Linear Regression
163
+ from sklearn.model_selection import train_test_split
164
+ from sklearn.linear_model import LinearRegression
165
+ X = df[
166
+ [
167
+ 'Study_Hours',
168
+ 'Attendance',
169
+ 'Assignment_Score',
170
+ 'Internal_Marks',
171
+ 'Previous_Sem_Marks'
172
+ ]
173
+ ]
174
+ y = df['Final_Marks']
175
+ X_train, X_test, y_train, y_test = train_test_split(
176
+ X, y, test_size=0.20, random_state=42
177
+ )
178
+ model = LinearRegression()
179
+ model.fit(X_train, y_train)
180
+ print("Intercept:", model.intercept_)
181
+ for col, coef in zip(X.columns, model.coef_):
182
+ print(col, ":", coef)
183
+ y_pred = model.predict(X_test)
184
+ print("Predicted Final Marks:")
185
+ print(y_pred)
186
+ Task 3. Evaluate Linear Regression
187
+ from sklearn.metrics import r2_score, mean_squared_error
188
+ r2 = r2_score(y_test, y_pred)
189
+ mse = mean_squared_error(y_test, y_pred)
190
+ rmse = np.sqrt(mse)
191
+ residuals = y_test - y_pred
192
+ RSS = np.sum(residuals ** 2)
193
+ print("R2:", r2)
194
+ print("MSE:", mse)
195
+ print("RMSE:", rmse)
196
+ print("Residuals:")
197
+ print(residuals)
198
+ print("RSS:", RSS)
199
+ plt.scatter(y_test, y_pred)
200
+ plt.xlabel("Actual Final Marks")
201
+ plt.ylabel("Predicted Final Marks")
202
+ plt.title("Actual vs Predicted Final Marks")
203
+ plt.show()
204
+ Interpretation: Higher R² generally means the model explains more variation in Final_Marks. Lower MSE and RMSE mean
205
+ smaller prediction errors. Residual = Actual − Predicted.
206
+ Question 4: Sales Data Analysis Using Python
207
+ Aim: Load, clean, transform, analyze and visualize sales data.
208
+ 1. Load and inspect
209
+ import pandas as pd
210
+ import numpy as np
211
+ import matplotlib.pyplot as plt
212
+ import seaborn as sns
213
+ df = pd.read_csv("sales_data.csv")
214
+ print(df.head())
215
+ print(df.columns)
216
+ print(df.dtypes)
217
+ print(df.isnull().sum())
218
+ 2. Fill missing Price using average Price of its Product Category
219
+ df['Price'] = df.groupby('Category')['Price'].transform(
220
+ lambda x: x.fillna(x.mean())
221
+ )
222
+ print(df['Price'].isnull().sum())
223
+ 3. Create TotalAmount
224
+ df['TotalAmount'] = df['Quantity'] * df['Price']
225
+ print(df.head())
226
+ 4. Data analysis
227
+ # Highest total sales region
228
+ region_sales = df.groupby('Region')['TotalAmount'].sum()
229
+ print(region_sales)
230
+ print("Highest Sales Region:", region_sales.idxmax())
231
+ # Total Electronics revenue
232
+ electronics_sales = df[
233
+ df['Category'] == 'Electronics'
234
+ ]['TotalAmount'].sum()
235
+ print("Electronics Revenue:", electronics_sales)
236
+ # Highest quantity in a single invoice
237
+ highest = df.loc[df['Quantity'].idxmax()]
238
+ print(highest)
239
+
240
+ 5. Data visualization
241
+ # Bar chart: sales by region
242
+ region_sales.plot(kind='bar')
243
+ plt.title("Total Sales by Region")
244
+ plt.xlabel("Region")
245
+ plt.ylabel("Sales")
246
+ plt.show()
247
+ # Pie chart: sales by category
248
+ category_sales = df.groupby('Category')['TotalAmount'].sum()
249
+ category_sales.plot(kind='pie', autopct='%1.1f%%')
250
+ plt.title("Sales Distribution by Category")
251
+ plt.ylabel("")
252
+ plt.show()
253
+ # Line chart: monthly sales
254
+ df['Date'] = pd.to_datetime(df['Date'])
255
+ monthly_sales = df.groupby(
256
+ df['Date'].dt.to_period('M')
257
+ )['TotalAmount'].sum()
258
+ monthly_sales.plot(kind='line', marker='o')
259
+ plt.title("Monthly Sales")
260
+ plt.xlabel("Month")
261
+ plt.ylabel("Sales")
262
+ plt.show()
263
+ Conclusion: The dataset was loaded, cleaned and transformed. Regional sales, electronics revenue and highest quantity
264
+ were calculated, followed by bar, pie and line charts.
265
+ Question 5: Employee Promotion Prediction Using Logistic Regression
266
+ Aim: Predict promotion probability from years of work experience.
267
+ import numpy as np
268
+ import pandas as pd
269
+ import matplotlib.pyplot as plt
270
+ from sklearn.linear_model import LogisticRegression
271
+ experience = np.array([1,2,3,4,5,6,7,8,9,10])
272
+ promotion = np.array([0,0,0,0,0,1,1,1,1,1])
273
+ df = pd.DataFrame({
274
+ 'Experience': experience,
275
+ 'Promotion': promotion
276
+ })
277
+ X = experience.reshape(-1, 1)
278
+ y = promotion
279
+ model = LogisticRegression()
280
+ model.fit(X, y)
281
+ # Predicted probability
282
+ probability = model.predict_proba(X)[:, 1]
283
+ # Threshold 0.5
284
+ predicted = (probability >= 0.5).astype(int)
285
+ result = pd.DataFrame({
286
+ 'Experience': experience,
287
+ 'Actual': promotion,
288
+ 'Probability': probability,
289
+ 'Predicted': predicted
290
+ })
291
+ print(result)
292
+ # Sigmoid curve
293
+ x_curve = np.linspace(1, 10, 100).reshape(-1, 1)
294
+ y_curve = model.predict_proba(x_curve)[:, 1]
295
+ plt.scatter(experience, promotion)
296
+ plt.plot(x_curve, y_curve)
297
+ plt.axhline(0.5, linestyle='--')
298
+ plt.xlabel("Years of Experience")
299
+ plt.ylabel("Probability of Promotion")
300
+ plt.title("Logistic Regression - Promotion")
301
+ plt.show()
302
+ Interpretation: Logistic Regression gives a probability between 0 and 1. If probability ≥ 0.5, the employee is classified as
303
+ Promoted (1); otherwise Not Promoted (0). As experience increases, the predicted promotion probability generally
304
+ increases for this dataset.
305
+ Question 6: Loan Approval Prediction Using Logistic Regression
306
+ Aim: Predict loan approval probability from monthly income.
307
+ import numpy as np
308
+ import pandas as pd
309
+ import matplotlib.pyplot as plt
310
+ from sklearn.linear_model import LogisticRegression
311
+ income = np.array([15,18,20,22,25,28,30,35,40,45])
312
+ loan_approved = np.array([0,0,0,0,1,1,1,1,1,1])
313
+ df = pd.DataFrame({
314
+ 'Income': income,
315
+ 'Loan_Approved': loan_approved
316
+ })
317
+ X = income.reshape(-1, 1)
318
+ y = loan_approved
319
+ model = LogisticRegression()
320
+ model.fit(X, y)
321
+ # Predicted probability
322
+ probability = model.predict_proba(X)[:, 1]
323
+ # Threshold 0.5
324
+ prediction = (probability >= 0.5).astype(int)
325
+ result = pd.DataFrame({
326
+ 'Income': income,
327
+ 'Actual': loan_approved,
328
+ 'Probability': probability,
329
+ 'Prediction': prediction
330
+ })
331
+ print(result)
332
+ # Logistic curve
333
+ x_curve = np.linspace(15, 45, 100).reshape(-1, 1)
334
+ y_curve = model.predict_proba(x_curve)[:, 1]
335
+ plt.scatter(income, loan_approved)
336
+ plt.plot(x_curve, y_curve)
337
+ plt.axhline(0.5, linestyle='--')
338
+ plt.xlabel("Monthly Income")
339
+ plt.ylabel("Probability of Loan Approval")
340
+ plt.title("Logistic Regression - Loan Approval")
341
+ plt.show()
342
+ # Decision boundary
343
+ boundary = -model.intercept_[0] / model.coef_[0][0]
344
+ print("Decision Boundary:", boundary)
345
+ Interpretation: The model converts income into a probability of loan approval. Probability ≥ 0.5 is classified as Loan
346
+ Approved (1), while probability < 0.5 is classified as Loan Rejected (0).
347
+ Quick Revision for Viva
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "exam-sub",
3
+ "version": "1.0.0",
4
+ "description": "A CLI for accessing college subject study materials from the terminal.",
5
+ "bin": {
6
+ "exam-sub": "bin/cli.js"
7
+ },
8
+ "files": [
9
+ "bin",
10
+ "data",
11
+ "README.md"
12
+ ],
13
+ "keywords": [
14
+ "college",
15
+ "study",
16
+ "cli",
17
+ "div",
18
+ "aiop",
19
+ "big-data",
20
+ "hadoop",
21
+ "mlf"
22
+ ],
23
+ "author": "wizard",
24
+ "license": "MIT",
25
+ "dependencies": {
26
+ "@inquirer/prompts": "^8.7.2"
27
+ }
28
+ }