⚡ TechVani: AI, Technology, Apps, Coding & Digital World
TechVaniAI • Technology • Apps • Coding • Digital World
HomeAI & TechAppsCodingFree AI ToolsStudent TechSecurityAboutContactPrivacy
TECHVANI // LEARN. BUILD. TEST.

Learn the tech. Build the idea.

Clear study notes, tested lab files and practical guides for coding, AI and digital safety.

Explore Latest →
šŸ¤– AI & TechAI news, tools & guides šŸ“± Apps & ToolsUseful apps & websites šŸ’» CodingProgramming & web development šŸŽ“ Student TechStudy & career technology šŸ” Cyber SecuritySafety & awareness

Latest Posts

Circuit Notebook theme

Exam Notes

šŸ“š BTech CSE Exam Notes

Find Semester 1-8 subjects in one place. Choose a semester and open the notes you need. This is a general study guide, not an official syllabus.

Open Exam Notes →🧪 Open Lab Files →

Exam Numericals & Study Series

Practice CPU scheduling and explore OS and DBMS topics in separate, easy-to-follow parts. New topics will appear in the hub as they are published.

Open Numericals Hub →

Start here and stay in touch

New to TechVani? Start with our free AI tools guide for students. It covers which tools to try and what to check before relying on an answer.

For step-by-step videos, visit SiteSudhar on YouTube.

Join TechVani on WhatsApp

Get new AI tools and coding guides in your WhatsApp Updates tab.

Browse Topics

Popular Posts

TechVani

Artificial Intelligence | Semester 6 Complete Core Notes

Semester 6 - Page 1: Artificial Intelligence. 27 numbered topics, highlighted rules, worked reasoning/search examples, answered exam questions, diagrams, comparison tables and five complete Python demos. General common-core guide, not an official syllabus or a validated decision system.

Run each Python block separately: Python 3, standard library only. These offline finite examples check search, backtracking, minimax, exact Bayes arithmetic and expected reward. They do not establish real-world model accuracy or safety. The A* example uses a consistent admissible heuristic; the expected-reward comparison has no risk constraint.

Topic map

  1. AI, agents and rationality
  2. PEAS and environment properties
  3. Agent architectures and state
  4. Search problem formulation
  5. BFS, DFS and iterative deepening
  6. Uniform-cost search and best costs
  7. Heuristics, greedy search and A*
  8. Local search and optimization
  9. Constraint satisfaction and backtracking
  10. Constraint propagation and consistency
  11. Minimax and adversarial assumptions
  12. Alpha-beta and expectimax
  13. Propositional logic and entailment
  14. First-order logic and quantifiers
  15. Inference, unification and knowledge bases
  16. Planning and action models
  17. Probability, conditioning and independence
  18. Bayes rule and base rates
  19. Bayesian networks and temporal models
  20. MDPs, rewards and Bellman reasoning
  21. Reinforcement learning and exploration
  22. Supervised learning and evaluation
  23. Unsupervised learning and representation
  24. Neural networks and gradient learning
  25. NLP, perception and application limits
  26. Responsible AI and uncertainty
  27. Exam and implementation checklist

1. AI, agents and rationality

AI studies agents selecting actions from observations to meet a performance measure. Rational choice concerns expected outcomes given available information, not imitation of a person.

Worked example: A route agent uses location/traffic and chooses actions under time/fuel goals; poor observations can still defeat a well-designed rule.
Exam question: Does a rational agent always achieve the best actual outcome?
Answer: No. Uncertainty and unavailable information limit guarantees.

2. PEAS and environment properties

PEAS names performance, environment, actuators and sensors. Classify observability, determinism, episodic/sequential structure, dynamics and action/state discreteness.

Worked example: A driving task is partly observable and sequential; sensors do not provide perfect knowledge of every road actor.
Exam question: Why classify the environment?
Answer: It exposes assumptions that determine which agent/search model fits.

3. Agent architectures and state

Reflex, model-based, goal-based, utility-based and learning architectures organize different decision needs. Internal state can summarize history when observations are incomplete.

Worked example: A thermostat-like reflex differs from a route planner comparing future outcomes; a utility function can express tradeoffs.
Exam question: Is internal state necessarily the complete true world state?
Answer: No. It can be an estimate or partial summary.

4. Search problem formulation

Specify initial state, actions, transition, goal and path cost. A search state describes a configuration; a search node also records path/cost/parent information.

Worked example: S-A-G costs 8 and S-B-G costs 6 despite both having two edges. Choose cost-aware search if travel cost matters.
Exam question: Does shortest edge count imply cheapest weighted path?
Answer: No. Equal step costs are needed for that equivalence.
S --2--> A --6--> G
 \--5--> B --1--> G
S-A-G = 8; S-B-G = 6
Equal edge counts do not imply equal weighted path costs.

5. BFS, DFS and iterative deepening

BFS uses a queue and finds minimum edge depth under standard finite-branching assumptions. DFS uses a depth-first frontier and is not generally shortest/complete on infinite paths. Iterative deepening repeats depth limits.

Worked example: Graph cycle handling avoids repeated paths; iterative deepening trades repeated shallow work for lower frontier memory.
Exam question: Does DFS always require constant memory?
Answer: No. Stack/path and graph visited-state storage still consume space.

6. Uniform-cost search and best costs

UCS prioritizes accumulated cost and updates better paths. Nonnegative costs and suitable termination/finite conditions matter; accept a goal when selected correctly from the frontier, not merely first generated.

Worked example: A costly direct goal can be generated before a cheaper indirect route is settled. The executable search demo rejects negative edge costs.
Exam question: Can UCS use a simple visited-at-generation rule for arbitrary weighted edges?
Answer: Not safely. Better-cost paths must be handled correctly.

7. Heuristics, greedy search and A*

Greedy ranks h alone; A* ranks g+h. Admissibility means no overestimate; consistency bounds each edge estimate. Graph-search duplicate/reopening rules affect optimality.

Worked example: h(A)=4, h(B)=1 gives tied f values in the four-node demo; actual costs settle the goal at 6.
Exam question: Does an admissible heuristic excuse incorrect graph-search implementation?
Answer: No. Cost updates, reopenings and goal termination rules also matter.

Uniform-cost and A* with best-cost updates

from heapq import heappush, heappop
from itertools import count

graph = {"S": [("A", 2), ("B", 5)], "A": [("G", 6)], "B": [("G", 1)], "G": []}
def search(heuristic):
    serial = count()
    queue = [(heuristic["S"], next(serial), 0, "S", ["S"])]
    best = {"S": 0}
    while queue:
        _, _, cost, node, path = heappop(queue)
        if cost != best[node]: continue
        if node == "G": return cost, path
        for child, weight in graph[node]:
            if weight < 0: raise ValueError("nonnegative costs required")
            new = cost + weight
            if new < best.get(child, float("inf")):
                best[child] = new
                heappush(queue, (new+heuristic[child], next(serial), new, child, path+[child]))
    return None
for name, h in [("UCS", dict.fromkeys(graph, 0)), ("A*", {"S": 6, "A": 4, "B": 1, "G": 0})]:
    print(name, search(h))

Checked output:

UCS (6, ['S', 'B', 'G'])
A* (6, ['S', 'B', 'G'])

8. Local search and optimization

Hill climbing follows local improvement and can get stuck on plateaus/local optima. Simulated annealing allows some worse moves under a schedule; random restarts explore alternatives.

Worked example: A scheduling score can be improved locally without storing a full path; local improvement need not find a global optimum.
Exam question: Does local search always solve pathfinding with a returned route?
Answer: No. Many formulations seek a final configuration rather than a path.

9. Constraint satisfaction and backtracking

A CSP specifies variables, domains and constraints. Backtracking assigns compatible values; MRV, degree and least-constraining-value heuristics influence search order.

Worked example: Color a triangle with three colors so adjacent vertices differ; two colors cannot satisfy all three edges.
Exam question: Are constraints the same as a heuristic estimate?
Answer: No. Constraints define allowed solutions; heuristics guide search order.

Triangle coloring by backtracking

vertices = ["A", "B", "C"]
edges = {frozenset(pair) for pair in [("A","B"), ("B","C"), ("A","C")]}
def solve(colors):
    assigned = {}
    def visit(index):
        if index == len(vertices): return dict(assigned)
        vertex = vertices[index]
        for color in colors:
            if any(frozenset((vertex,other)) in edges and value == color for other,value in assigned.items()):
                continue
            assigned[vertex] = color
            answer = visit(index+1)
            if answer is not None: return answer
            del assigned[vertex]
        return None
    return visit(0)
print("two colors:", solve(["red", "blue"]))
print("three colors:", solve(["red", "blue", "green"]))

Checked output:

two colors: None
three colors: {'A': 'red', 'B': 'blue', 'C': 'green'}

10. Constraint propagation and consistency

Forward checking removes incompatible future values; arc consistency ensures every retained value has support across each relevant binary constraint. Propagation can prune without solving all global constraints.

Worked example: A forced color removes that color from neighboring domains; an empty domain reveals failure immediately.
Exam question: Does arc consistency guarantee a complete solution for every CSP?
Answer: No. Local consistency does not resolve every global interaction.

11. Minimax and adversarial assumptions

Minimax evaluates MAX/MIN choices for suitable deterministic two-player zero-sum games under its model. Depth cutoffs rely on evaluation quality.

Worked example: MIN leaves(3, 5) give 3 and(2, 9) give 2; MAX chooses the first branch with value 3, not the largest leaf 9.
Exam question: Why not pick the best leaf anywhere?
Answer: The opponent controls the MIN response.
           MAX
       /          \
   MIN A          MIN B
   3   5          2   9
    -> 3           -> 2
MAX chooses A with value 3
The opponent controls the MIN choice, so selecting the largest leaf is wrong.

12. Alpha-beta and expectimax

Alpha-beta prunes branches unable to change minimax's result; move order affects work saved. Expectimax uses probabilities at chance nodes and different risk assumptions.

Worked example: Alpha-beta and full minimax should agree on the same finite tree; stochastic outcomes require an appropriate probability model.
Exam question: Can minimax pruning rules be copied blindly into expectation nodes?
Answer: No. Chance-value bounds and assumptions differ.

Minimax and alpha-beta on the same finite tree

tree = [[3, 5], [2, 9]]
def minimax(node, maximizing):
    if isinstance(node, int): return node
    values = [minimax(child, not maximizing) for child in node]
    return max(values) if maximizing else min(values)
def alphabeta(node, maximizing, alpha=float("-inf"), beta=float("inf")):
    if isinstance(node, int): return node
    value = float("-inf") if maximizing else float("inf")
    for child in node:
        score = alphabeta(child, not maximizing, alpha, beta)
        if maximizing:
            value = max(value, score); alpha = max(alpha, value)
        else:
            value = min(value, score); beta = min(beta, value)
        if alpha >= beta: break
    return value
print("minimax:", minimax(tree, True))
print("alpha-beta:", alphabeta(tree, True))
assert minimax(tree, True) == alphabeta(tree, True) == 3
print("agreement check passed")

Checked output:

minimax: 3
alpha-beta: 3
agreement check passed

13. Propositional logic and entailment

Propositions, connectives and truth assignments express statements. Entailment means every model satisfying premises also satisfies the conclusion; implication is false only for true antecedent/false consequent.

Worked example: P and P implies Q entail Q. Q alone does not entail P.
Exam question: Can implication be reversed without another premise?
Answer: No. Affirming the consequent is invalid.

14. First-order logic and quantifiers

First-order logic adds objects, predicates, variables and quantifiers. Quantifier order matters; existential and universal claims are different.

Worked example: Every student has some ID does not necessarily mean one single ID belongs to every student.
Exam question: Does a universal rule establish that its antecedent holds for a named object?
Answer: No. The object's premise must be provided separately.

15. Inference, unification and knowledge bases

Inference derives supported conclusions; unification finds substitutions matching logical expressions under its rules. Knowledge bases need consistent representation and explicit unknowns.

Worked example: Student(Riya) plus all students have IDs supports HasID(Riya), but no student conclusion follows merely from HasID(Riya).
Exam question: Is absence from a knowledge base always falsity?
Answer: No. Open/closed-world assumptions must be stated.

16. Planning and action models

Planning uses states/actions with preconditions and effects to reach goals. Ordering, resources and uncertainty affect execution beyond a symbolic plan.

Worked example: A deliver action requires a package and location; actions can fail in the real world even when the symbolic model permits them.
Exam question: Does a plan guarantee success without sensing during execution?
Answer: No. Validate assumptions and respond to changed state.

17. Probability, conditioning and independence

Probability distributions quantify uncertainty under a model. Conditional probability changes with evidence; independence is a claim requiring support, not a default for convenient arithmetic.

Worked example: P(H given E) differs from P(E given H); the prior and total evidence probability connect them.
Exam question: Can correlated observations be multiplied as if independent?
Answer: Not without a justified independence model.

18. Bayes rule and base rates

Bayes relates posterior, likelihood and prior through evidence normalization. Rare conditions can yield a low positive predictive value despite high sensitivity.

Worked example: Prior.01, sensitivity.9, false-positive rate.1 gives posterior 1/12=0.083333 in exact-fraction code.
Exam question: Does 90 percent true-positive rate mean 90 percent of flagged cases are positive?
Answer: No. Base rate and false positives affect the posterior.

Bayes posterior using exact rational arithmetic

from fractions import Fraction
prior, sensitivity, false_positive = Fraction(1,100), Fraction(9,10), Fraction(1,10)
true_flag = prior*sensitivity
false_flag = (1-prior)*false_positive
posterior = true_flag/(true_flag+false_flag)
print("posterior exact:", posterior)
print("posterior decimal:", format(float(posterior), ".6f"))
print("flagged spam per 1000:", true_flag*1000)
print("flagged nonspam per 1000:", false_flag*1000)

Checked output:

posterior exact: 1/12
posterior decimal: 0.083333
flagged spam per 1000: 9
flagged nonspam per 1000: 99

19. Bayesian networks and temporal models

Bayesian networks factor a joint distribution using directed dependencies and local conditional probabilities. Temporal models describe hidden/state evolution and observations under stated assumptions.

Worked example: A hidden-state model separates latent condition from noisy sensor evidence; inference is not direct observation of truth.
Exam question: Does an edge automatically prove causation?
Answer: No. A probabilistic graph and a causal claim need different supporting assumptions.

20. MDPs, rewards and Bellman reasoning

An MDP specifies states, actions, transition probabilities and rewards with a horizon/discount. A policy selects actions; Bellman reasoning compares immediate and future expected return.

Worked example: For a one-step action, expected reward sums probability times outcome reward; our demo compares a risky 2.4 expectation to a safe 2.0.
Exam question: Does the highest expected reward eliminate harmful possible outcomes?
Answer: No. Risk constraints and reward design remain separate choices.
State -> policy action
      -> probabilistic transition
      -> reward + next state
      -> future decision
Expected reward and safe outcomes are different objectives.

One-step expected-reward comparison

actions = {"safe": [(1.0, 2.0)], "risky": [(0.6, 5.0), (0.4, -1.5)]}
values = {}
for action, outcomes in actions.items():
    assert abs(sum(p for p, reward in outcomes)-1.0) < 1e-12
    values[action] = sum(p*reward for p,reward in outcomes)
    print(action + ":", format(values[action], ".2f"))
print("expected-reward choice:", max(values, key=values.get))
print("This comparison has no risk constraint and is not a safety guarantee.")

Checked output:

safe: 2.00
risky: 2.40
expected-reward choice: risky
This comparison has no risk constraint and is not a safety guarantee.

21. Reinforcement learning and exploration

RL learns from action/reward experience; model-based and model-free approaches use different information. Exploration trades learning against cost; unsafe actions need limits.

Worked example: Q-learning updates an action-value estimate from reward and a next-state target under assumptions; data from one environment may not transfer.
Exam question: Is reward always identical to the user's real goal?
Answer: No. A poorly chosen reward can encourage unwanted behavior.

22. Supervised learning and evaluation

Supervised models fit labeled examples for classification/regression. Hold out evaluation matching real units/time and fit learned preprocessing on training folds only.

Worked example: An earlier quiz feature is valid only if available before prediction; later quiz score leaks the outcome.
Exam question: Does a final test set belong in threshold tuning?
Answer: No. Freeze choices before final evaluation.

23. Unsupervised learning and representation

Clustering and representation methods seek structure without supplied target labels. Scaling, initialization and objective affect the result; clusters are not automatically meaningful classes.

Worked example: K-means center IDs have no inherent semantic label; PCA variance directions need not be best prediction features.
Exam question: Does unlabeled training remove privacy obligations?
Answer: No. Data access/use still needs permission and safeguards.

24. Neural networks and gradient learning

Layers compose weighted transformations and activations. Backpropagation computes gradients through the chain rule; an optimizer updates parameters under a loss.

Worked example: Specify input, architecture, loss and evaluation rather than calling every approach deep learning.
Exam question: Do more layers guarantee improved generalization?
Answer: No. Capacity, data, optimization and regularization interact.

25. NLP, perception and application limits

Language and vision systems depend on representation, training data and evaluation. Fluent text or a confident recognition score is not grounded truth or authority.

Worked example: A generated answer needs factual checks; a face-like pattern match is not permission to identify a person.
Exam question: Can apparent confidence substitute for evidence?
Answer: No. Measure performance and verify claims appropriate to the stakes.

26. Responsible AI and uncertainty

Assess data permission, fairness, calibration, group performance, human review and harmful consequences. Optimization of one metric can conflict with broader goals.

Worked example: A support recommendation should offer review and useful help, not deny assistance solely from a noisy model.
Exam question: Does removing a sensitive field guarantee fairness?
Answer: No. Proxies and unequal data can preserve harmful effects.

27. Exam and implementation checklist

State model, assumptions, algorithm, trace, complexity where relevant and limitations. Test edge cases and compare independent methods on small examples.

Worked example: Draw search and minimax trees, calculate Bayes with priors, and distinguish expected reward from a safe guaranteed outcome.
Exam question: What makes an AI answer more useful than a definition alone?
Answer: A worked trace/calculation with assumptions, checks and limits.

Search comparison

MethodPriorityKey limitation
BFSEdge depth/FIFOLeast edges, not arbitrary weighted cost
DFSDepth-first/LIFONot generally shortest; cycles/infinite paths
UCSAccumulated gNonnegative costs and proper best-cost handling
GreedyEstimated hNot generally optimal
A*g+hHeuristic and graph-search rules matter

Inference and choice distinctions

ConceptUsesDoes not establish
Logical entailmentAll satisfying premise modelsTruth from unsupported premises
Bayes posteriorPrior, likelihood, evidenceCausal explanation or guaranteed outcome
MinimaxWorst modeled adversarial replyProbabilistic expected payoff
ExpectimaxChance probabilitiesWorst-case safety
MDP expected returnTransition/reward policy modelComplete real-world user goal

Worked arithmetic

ExampleCalculationResult
Route via A2+68
Route via B5+16
Bayes flags9 / (9+99)1/12 = 0.083333 rounded
Risky expected reward0.6x5 + 0.4x(-1.5)2.40
Safe reward1x22.00

Revision and exam checklist

Define agent/environment, formulate states and costs, trace search/minimax, distinguish logic from probability, compute base-rate-aware Bayes and state reward/risk assumptions. Compare methods on small examples and explain where guarantees stop.

Resources and sources

Open AI teaching references support the concepts. Examples, diagrams and all demos here are original; exact program output is shown rather than claimed accuracy on a real dataset.

Comments