) : (
)}
);
}
================================================
FILE: components/footer.tsx
================================================
import Image from "next/image";
import {
SiDiscord,
SiGithub,
SiX,
SiYoutube,
SiInstagram,
SiLinkedin,
// SiDiscourse,
} from "react-icons/si";
import DarkLogo from "@/public/logo-dark.png";
import LightLogo from "@/public/logo-light.png";
const YEAR = new Date().getFullYear();
export const Footer = (): React.ReactElement => {
const socialLinks = [
{ href: "https://twitter.com/aicademyorg", icon: SiX, label: "Twitter" },
{
href: "https://www.youtube.com/@aicademyorg",
icon: SiYoutube,
label: "YouTube",
},
{ href: "https://github.com/aicademyorg", icon: SiGithub, label: "GitHub" },
{
href: "https://discord.com/invite/bxnwugmNZg",
icon: SiDiscord,
label: "Discord",
},
{
href: "https://www.instagram.com/aicademyorg",
icon: SiInstagram,
label: "Instagram",
},
{
href: "https://www.linkedin.com/company/aicademyorg",
icon: SiLinkedin,
label: "LinkedIn",
},
// { href: "#", icon: SiDiscourse, label: "Discourse" },
];
return (
);
};
================================================
FILE: components/mdx/mermaid.tsx
================================================
'use client';
import { useEffect, useId, useRef, useState } from 'react';
import { useTheme } from 'next-themes';
export function Mermaid({ chart }: { chart: string }) {
const id = useId();
const [svg, setSvg] = useState('');
const containerRef = useRef(null);
const currentChartRef = useRef(null);
const { resolvedTheme } = useTheme();
useEffect(() => {
const container = containerRef.current;
if (currentChartRef.current === chart || !container) return;
currentChartRef.current = chart;
async function renderChart() {
const { default: mermaid } = await import('mermaid');
try {
mermaid.initialize({
startOnLoad: false,
securityLevel: 'loose',
fontFamily: 'inherit',
themeCSS: 'margin: 1.5rem auto 0;',
theme: resolvedTheme === 'dark' ? 'dark' : 'default',
});
const { svg, bindFunctions } = await mermaid.render(
id,
chart.replaceAll('\\n', '\n'),
);
bindFunctions?.(container!);
setSvg(svg);
} catch (error) {
console.error('Error while rendering mermaid', error);
}
}
void renderChart();
}, [chart, id, resolvedTheme]);
return ;
}
================================================
FILE: content/docs/math/index.mdx
================================================
---
title: Mathematics
description: Mathematics for Machine Learning
icon: Code
---
================================================
FILE: content/docs/math/meta.json
================================================
{
"title": "Mathematics",
"description": "Maths for Machine Learning",
"root": true,
"icon": "Sigma"
}
================================================
FILE: content/docs/meta.json
================================================
{
"pages": ["python", "math"],
"description": "Welcome to the AIcademy documentation!"
}
================================================
FILE: content/docs/python/index.mdx
================================================
---
title: Welcome
description: Learn Python for Data Science
icon: Album
---
import { Accordion, Accordions } from "fumadocs-ui/components/accordion";
import { SiNumpy, SiPandas, SiPython, SiScikitlearn } from "react-icons/si";
Welcome to the **Python for Data Science** course!
This course will teach you Python and key libraries for data science, from basics to advanced.
This is a hands-on course where you'll learn by solving Python problems. At the end of each module, you'll find exercises to help reinforce and apply what you've learned.
## What you'll learn
You’ll begin with Python basics and then learn key libraries for data science.
} title='Python' href="/docs/python/python">
A powerful and versatile programming language widely used in machine learning.
} title='NumPy' href="/docs/python/numpy">
A library for fast numerical computations and working with arrays.
} title='Pandas' href="/docs/python/pandas">
A tool for data manipulation and analysis using DataFrames.
} title='Matplotlib' href="/docs/python/matplotlib">
A library for creating static, interactive, and animated visualizations.
} title='Scikit Learn' href="/docs/python/scikit-learn">
A library for building and evaluating machine learning models.
By the end, you’ll have a solid foundation to explore, analyze, and work with data.
## Getting Help
If you need help or have questions, feel free to ask on our [Discord](https://discord.com/invite/bxnwugmNZg) server.
## FAQ
Some answers to frequently asked questions.
This course is for anyone curious about AI and programming with Python, from
complete beginners to professionals seeking to boost productivity.
No prior coding experience is required. This course is designed to be
accessible to complete beginners while also providing valuable insights for
those with some coding background.
We recommend taking the courses in the prescribed order for a logical and
consistent learning experience.
You will have access to a community of learners and professionals, as well
as continuous guidance and feedback from your AI companions.
## Let’s go
Let's get started by [setting up](/docs/python/setup) your Python environment.
================================================
FILE: content/docs/python/matplotlib/index.mdx
================================================
---
title: Matplotlib
description: Getting started with Python
icon: Terminal
index: true
---
## Matplotlib
================================================
FILE: content/docs/python/meta.json
================================================
{
"title": "Python",
"description": "Python for Data Science",
"icon": "SiPython",
"root": true,
"pages": [
"---Introduction---",
"index",
"setup",
"---Modules---",
"python",
"numpy",
"pandas",
"matplotlib",
"---Optional---",
"scikit-learn"
]
}
================================================
FILE: content/docs/python/numpy/index.mdx
================================================
---
title: NumPy
description: Getting started with Python
icon: SiNumpy
index: true
---
## NumPy
================================================
FILE: content/docs/python/pandas/index.mdx
================================================
---
title: Pandas
description: Getting started with Python
icon: SiPandas
index: true
---
## Pandas
================================================
FILE: content/docs/python/python/control-flow.mdx
================================================
---
title: Control Flow
description: Direct the logic of your program with conditions and loops.
---
5.1 Conditional Statements
- if, else, elif
Nested if
- 5.2 Loops
- for and while Loops
- range() and enumerate()
- Loop Control: break, continue
- Nested Loops
================================================
FILE: content/docs/python/python/data-structures.mdx
================================================
---
title: Data Structures
description: Store and organize data with Python's built-in collections.
---
6.1 Lists
- Creation, Indexing, Slicing
- List Methods
6.2 Tuples
6.3 Sets
6.4 Dictionaries
- Creating and Accessing Elements
- Dictionary Methods
================================================
FILE: content/docs/python/python/data-types.mdx
================================================
---
title: Data Types
description: Work with and manipulate different types of data.
---
In Python, data types classify the types of values a variable can hold. Every value in Python has a data type. Python is a dynamically typed language, so you don’t need to explicitly declare the type of a variable.
Since everything in Python is an object, data types are actually classes, and the variables are instances (objects) of these classes.
B[Numeric]
A --> C[Dictionary]
A --> D[Boolean]
A --> E[Set]
A --> F[Sequence Type]
B --> B1[Integer]
B --> B2[Float]
B --> B3[Complex Number]
F --> F1[Strings]
F --> F2[List]
F --> F3[Tuple]
`}
/>
## Numeric
The numeric data type in Python represents the data that has a numeric value.
### Integer (`int`)
Whole numbers, positive or negative, without decimal points.
```py
x = 10
print(type(x)) #
```
Python integers can be arbitrarily large (limited by memory).
### Float (`float`)
Real numbers with decimal points. Also supports scientific notation.
```py
x = 10.5
y = 1.5e2
print(type(x), type(y)) #
```
### Complex (`complex`)
Used to represent complex numbers (real + imaginary). Suffix `j` is used for the imaginary part
```py
x = 2 + 3j
print(type(x)) #
```
## Sequence Type
The sequence Data Type in Python is the ordered collection of similar or different Python data types.
### String (`str`)
A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one.
Example:
```py
# String with single quotes
print('Welcome to the Geeks World')
# String with double quotes
print("I'm a Geek")
# String with triple quotes
print('''I'm a Geek and I live in a world of "Geeks"''')
```
Output:
```sh
Welcome to the Geeks World
I'm a Geek
I'm a Geek and I live in a world of "Geeks"
```
#### Accessing elements of string:
| Character | A | I | c | a | d | e | m | y |
| ------------------ | --- | --- | --- | --- | --- | --- | --- | --- |
| **Positive Index** | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| **Negative Index** | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
```py
String1 = "AIcademy"
# Printing First character
print(String1[0])
# Printing Last character
print(String1[-1])
```
output:
```sh
A
y
```
#### Deleting/Updating from a String:
In Python, Updation or deletion of characters from a String is not allowed because Strings are immutable. Only new strings can be reassigned to the same name.
### List
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type.
Lists in Python can be created by just placing the sequence inside the square brackets[].
```py
# Empty list
a = []
# list with int values
a = [1, 2, 3]
print(a)
# list with mixed int and string
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)
```
output:
```sh
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
```
#### Access List Items
Use the index operator [ ] to access an item in a list. In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
```py
List = [1, 2, 3, 4, 5, 6]
# accessing a element
print(List[0])
print(List[2])
# Negative indexing
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
```
output:
```sh
1
3
6
4
```
Adding Elements to a List: Using append(), insert() and extend()
```py
# Creating a List
List = []
# Using append()
List.append(1)
List.append(2)
print(List)
# Using insert()
List.insert(3, 12)
List.insert(0, 'Geeks')
print(List)
# Using extend()
List.extend([8, 'Geeks', 'Always'])
print(List)
```
outuput:
```sh
[1, 2]
['Geeks', 1, 2, 12]
['Geeks', 1, 2, 12, 8, 'Geeks', 'Always']
```
Removing Elements from the List: Using remove() and pop()
```py
# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
# using Remove() method
List.remove(5)
List.remove(6)
print(List)
# using pop()
List.pop()
print(List)
```
output:
```sh
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
[1, 2, 3, 4, 7, 8, 9, 10, 11]
```
### Tuple
Just like a list, a tuple is also an ordered collection of Python objects. The only difference between a tuple and a list is that tuples are immutable. Tuples cannot be modified after it is created.
```py
Tuple1 = ()
print (Tuple1)
# Creating a tuple of strings
print(('Geeks', 'For'))
# Creating a Tuple of list
print(tuple([1, 2, 4, 5, 6]))
# Creating a nested Tuple
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print(Tuple3)
```
output:
```sh
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
((0, 1, 2, 3), ('python', 'geek'))
```
#### Accessing element of a tuple
Use the index operator [ ] to access an item in a tuple.
```py
tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print(tuple1[0])
# Accessing element using Negative
# Indexing
print(tuple1[-1])
```
output:
```sh
1
5
```
### Deleting/updating elements of tuple
Items of a tuple cannot be deleted as tuples are immutable in Python. Only new tuples can be reassigned to the same name.
```py
tuple1 = tuple([1, 2, 3, 4, 5])
# Updating an element
tuple1[0] = -1
# Deleting an element
del tuple1[2]
```
## Boolean
Only two values: `True` and `False`.
```py
x = True
y = False
print(type(x)) #
```
Booleans are often returned from comparison or logical operations.
```py
print(1 == 1) # True
print(1 < 2 and 3 > 1) # True
```
## Set (`set`)
Unordered collection of unique, immutable elements.
```py
s = {1, 2, 3, 2}
print(s) # {1, 2, 3}
```
#### Adding elements: Using add() and update()
```py
set1 = set()
# Adding to the Set using add()
set1.add(8)
set1.add((6, 7))
print(set1)
# Additio to the Set using Update()
set1.update([10, 11])
print(set1)
```
output:
```sh
{8, (6, 7)}
{8, 10, 11, (6, 7)}
```
#### Accessing a Set
```py
# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
# Accessing using for loop
for i in set1:
print(i, end =" ")
```
output:
```sh
Geeks For
```
#### Removing elements from a set: Using remove(), discard(), pop() and clear()
```py
set1 = set([1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12])
# using Remove() method
set1.remove(5)
set1.remove(6)
print(set1)
# using Discard() method
set1.discard(8)
set1.discard(9)
print(set1)
# Set using the pop() method
set1.pop()
print(set1)
# Set using clear() method
set1.clear()
print(set1)
```
output:
```sh
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}
{1, 2, 3, 4, 7, 10, 11, 12}
{2, 3, 4, 7, 10, 11, 12}
set()
```
## Dictionary (`dict`)
Unordered collection of key-value pairs. Keys must be unique and immutable.
```py
person = {
"name": "Alice",
"age": 30
}
print(person["name"]) # Alice
```
output:
```sh
{}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
```
#### Nested Dictionary
V1["Geeks"]
K2["2"] --> V2["For"]
K3["3"] --> NK["Nested Keys"]
%% Nested keys and their values
NK --> NA["A"] --> VA["Welcome"]
NK --> NB["B"] --> VB["To"]
NK --> NC["C"] --> VC["Geeks"]
%% Grouping (optional visual clarity)
subgraph Keys
K1
K2
K3
end
subgraph Value Set 1
V1
V2
end
subgraph Value Set 2
VA
VB
VC
end
`}
/>
```py
# Creating a Nested Dictionary
# as shown in the below image
Dict = {1: 'Geeks', 2: 'For',
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}
print(Dict)
```
output:
```sh
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
```
#### Adding elements to a Dictionary
One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
```py
# Creating an empty Dictionary
Dict = {}
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print(Dict)
```
output:
```sh
{0: 'Geeks', 2: 'For', 3: 1}
{0: 'Geeks', 2: 'Welcome', 3: 1}
```
#### Accessing elements from a Dictionary
In order to access the items of a dictionary refer to its key name or use get() method.
```py
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using key
print(Dict['name'])
# accessing a element using get()
print(Dict.get(3))
```
Output:
```sh
For
Geeks
```
#### Removing Elements from Dictionary
Using pop() and popitem()
```py
# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',
'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},
}
# using pop()
Dict.pop(5)
print(Dict)
# using popitem()
Dict.popitem()
print(Dict)
```
output:
```sh
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 6: 'To', 7: 'Geeks'}
{6: 'To', 7: 'Geeks'}
```
================================================
FILE: content/docs/python/python/error-handling.mdx
================================================
---
title: Error Handling
description: Handle errors gracefully and write reliable code.
---
10.1 Types of Exceptions
10.2 try, except, finally
10.3 Handling Multiple Exceptions
10.4 Raising Custom Exceptions
10.5 Debugging Tips
================================================
FILE: content/docs/python/python/file-handling.mdx
================================================
---
title: File Handling
description: Reading and writing files with Python
---
7.1 Opening Files with open()
7.2 Reading Text Files
7.3 Writing Text Files
7.4 Using with for File Handling
7.5 Working with JSON
- Reading JSON Files
- Writing JSON Files
================================================
FILE: content/docs/python/python/functions.mdx
================================================
---
title: Functions
description: Write modular, reusable code.
---
8.1 Defining Functions with def
8.2 Arguments and Return Values
8.3 Default Arguments, *args, **kwargs
8.4 Built-in vs User-defined Functions
8.5 Lambda (Anonymous) Functions
8.6 Functional Tools: map(), filter(), zip(), sorted()
================================================
FILE: content/docs/python/python/hello-world.mdx
================================================
---
title: Hello, World!
description: Understand the building blocks of a Python program.
---
Hello, World! in python is the first python program which we learn when we start learning any program. It’s a simple program that displays the message “Hello, World!” on the screen.
================================================
FILE: content/docs/python/python/index.mdx
================================================
---
title: Python
description: Getting started with Python
icon: SiPython
index: true
---
Python is a high-level programming language known for its simplicity and flexibility. It supports structured, object-oriented, and functional programming, with syntax inspired by elements of C.
Created in the late 1980s by Guido van Rossum, it was designed to be both powerful and easy to use.
## Why Python
Python is the most popular language for data science because:
- **Easy to learn**: Python’s simple, readable syntax is great for beginners and efficient for experienced developers.
- **Free and open source**: Completely free to use, with a rich ecosystem of libraries at no cost.
- **Powerful libraries**: Libraries like **NumPy**, **pandas**, and **matplotlib** make data analysis and visualization simple. Frameworks like **scikit-learn**, **TensorFlow**, and **PyTorch** let you build and train machine learning models with minimal code.
- **Vast ecosystem**: From web scraping to automation, Python offers libraries for nearly every task.
- **Scalable and versatile**: Python runs on all major platforms and scales from small scripts to large systems.
- **Strong community**: A large and active user base ensures plenty of tutorials, documentation, and support.
Python is also chosen for data science and machine learning for its object-oriented design, clear syntax, and dynamic memory management, making it ideal for a wide range of applications.
## Modules
================================================
FILE: content/docs/python/python/meta.json
================================================
{
"pages": [
"hello-world",
"operators",
"data-types",
"control-flow",
"data-structures",
"file-handling",
"functions",
"oop",
"error-handling"
]
}
================================================
FILE: content/docs/python/python/oop.mdx
================================================
---
title: Object Oriented
description: Model real-world systems using classes and objects.
---
9.1 What is OOP?
9.2 Creating Classes and Objects
9.3 Instance vs Class Attributes
9.4 Encapsulation and Access Modifiers
9.5 self and Class Members
9.6 Static Methods vs Class Methods
9.7 Inheritance
- Single and Multiple Inheritance
- super() and issubclass()
9.8 Polymorphism
9.9 Abstract Classes
================================================
FILE: content/docs/python/python/operators.mdx
================================================
---
title: Operators
description: Calculations and comparisons using operators.
---
Operators are symbols used to perform operations on variables and values, such as arithmetic calculations, comparisons, or logical checks.
Let's explore the most commonly used operators in Python:
## Arithmetic Operators
These are used to do basic math operations like addition, subtraction, multiplication and division.
| Operator | Description | Syntax |
| -------- | ---------------------------- | -------- |
| `+` | Addition | `x + y` |
| `-` | Subtraction | `x - y` |
| `*` | Multiplication | `x * y` |
| `/` | Division (decimal) | `x / y` |
| `//` | Floor Division (rounds down) | `x // y` |
| `%` | Modulus (remainder) | `x % y` |
| `**` | Power (exponent) | `x ** y` |
Example:
```py
a = 7
b = 2
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a // b) # Floor Division
print(a % b) # Modulus
print(a ** b) # Exponent
```
Output:
```sh
9
5
14
3.5
3
1
49
```
## Comparison Operators
These are used to compare two values. The result is either `True` or `False`.
| Operator | Description | Syntax |
| -------- | ------------------------ | -------- |
| `>` | Greater than | `x > y` |
| `<` | Less than | `x < y` |
| `==` | Equal to | `x == y` |
| `!=` | Not equal to | `x != y` |
| `>=` | Greater than or equal to | `x >= y` |
| `<=` | Less than or equal to | `x <= y` |
Example:
```py
x = 8
y = 10
print(x > y) # Greater than
print(x < y) # Less than
print(x == y) # Equal to
print(x != y) # Not equal to
print(x >= y) # Greater than or equal to
print(x <= y) # Less than or equal to
```
Output:
```sh
False
True
False
True
False
True
```
## Logical Operators
These are used to combine multiple conditions.
| Operator | Description | Syntax | Example |
| -------- | -------------------------------- | --------- | ------------------ |
| `and` | True if both conditions are true | `x and y` | `x > 5 and x < 10` |
| `or` | True if at least one is true | `x or y` | `x < 5 or x > 15` |
| `not` | Reverses the condition | `not x` | `not(x > 5)` |
Example:
```py
x = 7
print(x > 5 and x < 10) # True
print(x < 5 or x > 10) # False
print(not(x > 5)) # False
```
Output:
```sh
True
False
False
```
## Bitwise Operators
Bitwise operators work with binary (0s and 1s). These are advanced but useful for certain tasks.
| Operator | Description | Syntax |
| -------- | ------------------- | -------- |
| `&` | Bitwise AND | `x & y` |
| `~` | Bitwise NOT | `~x` |
| `^` | Bitwise XOR | `x ^ y` |
| `>>` | Bitwise right shift | `x >> y` |
| `<<` | Bitwise left shift | `x << y` |
Example:
```py
a = 6
b = 3
print(a & b) # AND
print(~a) # NOT
print(a ^ b) # XOR
print(a >> 1) # Right shift
print(a << 1) # Left shift
```
Output:
```sh
2
-7
5
3
12
```
## Assignment Operators
These are used to assign values to variables, sometimes after performing a calculation.
| Operator | Meaning | Example |
| -------- | ----------------------------- | --------- |
| `=` | Assign value | `x = 5` |
| `+=` | Add and assign | `x += 2` |
| `-=` | Subtract and assign | `x -= 2` |
| `*=` | Multiply and assign | `x *= 2` |
| `/=` | Divide and assign | `x /= 2` |
| `//=` | Floor divide and assign | `x //= 2` |
| `%=` | Modulus and assign | `x %= 2` |
| `**=` | Power and assign | `x **= 2` |
| `:=` | Assign in expression (Walrus) | `x := 5` |
Example:
```py
# = : Assign value
x = 5
print(x) # 5
# += : Add and assign
x += 3 # x = x + 3
print(x) # 8
# -= : Subtract and assign
x -= 2 # x = x - 2
print(x) # 6
# *= : Multiply and assign
x *= 4 # x = x * 4
print(x) # 24
# /= : Divide and assign
x /= 6 # x = x / 6
print(x) # 4.0
# //= : Floor divide and assign
x //= 3 # x = x // 3
print(x) # 1.0
# %= : Modulus and assign
x = 10
x %= 4 # x = x % 4
print(x) # 2
# **= : Power and assign
x **= 3 # x = x ** 3
print(x) # 8
# := : Walrus operator (Python 3.8+)
items = [1, 2, 3, 4]
while (length := len(items)) > 2:
print(length)
items.pop()
```
## Identity Operators
These check whether two variables refer to the same object in memory.
| Operator | Meaning | Example |
| -------- | ---------------------------- | ------------ |
| `is` | True if same memory location | `a is b` |
| `is not` | True if different location | `a is not b` |
Example
```py
a = 10
b = 20
c = a
print(a is not b)
print(a is c)
```
Output:
```
True
True
```
## Membership Operators
These check whether a value exists in a list, string, or other sequence.
| Operator | Meaning | Example |
| -------- | ---------------------------- | --------------- |
| `in` | True if value is present | `x in list` |
| `not in` | True if value is not present | `x not in list` |
Example:
```py
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("mango" not in fruits) # True
```
Output:
```sh
True
True
```
================================================
FILE: content/docs/python/scikit-learn/index.mdx
================================================
---
title: Scikit Learn
description: Getting started with Python
icon: SiScikitlearn
index: true
---
## Scikit Learn
================================================
FILE: content/docs/python/setup.mdx
================================================
---
title: Setup
description: Setting up your Python environment
icon: Settings2
colab: https://colab.research.google.com/drive/1example
---
Let’s set up the tools you’ll use to write and execute your code. There are two main environments for working with Python: **Shell** and **Notebook**. Let’s explore both.
Make sure [Python](https://www.python.org/downloads/) and
[IPython](https://ipython.org/install.html) are installed on your system.
## Shell
The Shell lets you run Python commands interactively in your terminal, line by line.
Start the Python shell by running `python3` in your terminal (`python` on Windows).
```sh title="Python shell"
(base) ➜ ~ python3 # [!code highlight]
Python 3.11.4 (main, Jul 5 2023, 08:54:11) [Clang 14.0.6 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!") # print hello world
Hello, World!
>>> 4 + 9 # add numbers
13
```
### IPython
[IPython](https://ipython.org/) is an enhanced shell with features like syntax highlighting, auto-completion, and better debugging.
To start IPython, run `ipython` in your terminal.
```sh title="IPython shell"
(base) ➜ ~ ipython # [!code highlight]
Python 3.11.4 (main, Jul 5 2023, 08:54:11) [Clang 14.0.6 ]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.12.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: print("Hello, IPython!")
Hello, IPython!
In [2]: 3 + 39
Out[2]: 42
```
Shells are great for quick tests but not ideal for complex projects. That’s where **Notebooks** come in.
## Notebooks
A notebook is a web-based interactive environment built on top of IPython. While working in the shell can be limiting, notebooks simplify the process by bringing code, visualizations, and explanations together in one place.
### Jupyter Notebook
[Jupyter Notebook](https://jupyter.org/) is a local web-based notebook, ideal for development, collaboration, and sharing.
Install it with the command `pip install notebook`, then launch it using `jupyter notebook`.
This will start a local web server, show the server log in your terminal, and automatically open the notebook in your browser at [localhost:8888](http://localhost:8888).

There is also an enhanced version of Jupyter Notebook called [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/), which provides a more flexible and powerful environment.
Install it with the command `pip install jupyterlab`, then launch it using `jupyter lab`.

Learn more about JupyterLab in this [tutorial](https://youtu.be/A5YyoCKxEOU?si=vQJXKYTakXIe-DJC) by the Jupyter team.
### Google Colab
[Google Colab](https://colab.research.google.com/) is a cloud-based notebook that runs in your browser. It comes with machine learning libraries pre-installed and offers free compute resources, such as GPUs and TPUs, for smaller workloads.
Due to its ease of use, flexibility, and access to more compute, most people now prefer Colab over Jupyter.

Learn more about Colab in this [tutorial](https://colab.research.google.com/notebooks/intro.ipynb) by the Colab team.
### Kaggle Notebook
[Kaggle Notebook](https://www.kaggle.com/code) is like Colab but fully connected to Kaggle’s datasets and competitions, making it easy to access data and join competitions right from the notebook.

Learn more about Kaggle Notebooks in this [tutorial](https://www.kaggle.com/docs/notebooks) by the Kaggle team.
## Which one to use?
If you’re unsure which environment to choose, [Colab](#google-colab) is a great option. It’s user-friendly, provides free access to more compute power, and comes with pre-installed machine learning libraries.
For this course, we’ll be using Colab as our primary environment.
You’re all set and ready to get started!
================================================
FILE: lib/cn.ts
================================================
export { twMerge as cn } from 'tailwind-merge';
================================================
FILE: lib/get-llm-text.ts
================================================
import { source } from "@/lib/source";
import type { InferPageType } from "fumadocs-core/source";
export async function getLLMText(page: InferPageType) {
const processed = await page.data.getText("processed");
return `# ${page.data.title}
URL: ${page.url}
Source: https://raw.githubusercontent.com/aicademyorg/AIcademy/refs/heads/main/content/docs/${page.path}
${page.data.description ?? ''}
${processed}`;
}
================================================
FILE: lib/github.ts
================================================
import { App, Octokit } from "octokit";
import type { Feedback } from "@/components/feedback";
export const repo = "AIcademy";
export const owner = "aicademyorg";
export const DocsCategory = "Feedback";
let instance: Octokit | undefined;
async function getOctokit(): Promise {
if (instance) return instance;
const appId = process.env.GITHUB_APP_ID;
const privateKey = process.env.GITHUB_APP_PRIVATE_KEY;
if (!appId || !privateKey) {
throw new Error(
"No GitHub keys provided for Github app, docs feedback feature will not work."
);
}
const app = new App({
appId,
privateKey,
});
const { data } = await app.octokit.request(
"GET /repos/{owner}/{repo}/installation",
{
owner,
repo,
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
}
);
instance = await app.getInstallationOctokit(data.id);
return instance;
}
interface RepositoryInfo {
id: string;
discussionCategories: {
nodes: {
id: string;
name: string;
}[];
};
}
let cachedDestination: RepositoryInfo | undefined;
async function getFeedbackDestination() {
if (cachedDestination) return cachedDestination;
const octokit = await getOctokit();
const {
repository,
}: {
repository: RepositoryInfo;
} = await octokit.graphql(`
query {
repository(owner: "${owner}", name: "${repo}") {
id
discussionCategories(first: 25) {
nodes { id name }
}
}
}
`);
return (cachedDestination = repository);
}
export interface ActionResponse {
githubUrl: string;
}
export async function onRateAction(
url: string,
feedback: Feedback
): Promise {
"use server";
const octokit = await getOctokit();
const destination = await getFeedbackDestination();
if (!octokit || !destination)
throw new Error("GitHub comment integration is not configured.");
const category = destination.discussionCategories.nodes.find(
(category) => category.name === DocsCategory
);
if (!category)
throw new Error(
`Please create a "${DocsCategory}" category in GitHub Discussion`
);
const title = `Feedback for ${url}`;
const body = `[${feedback.opinion}] ${feedback.message}\n\n> Forwarded from user feedback.`;
let discussion: { id: string; url: string } | undefined;
const searchResult = await octokit.graphql(`
query {
search(type: DISCUSSION, query: ${JSON.stringify(
`${title} in:title repo:${owner}/${repo} author:@me`
)}, first: 1) {
nodes {
... on Discussion { id, url }
}
}
}
`);
const nodes: { id: string; url: string }[] = searchResult.search.nodes;
if (nodes && nodes.length > 0 && nodes[0]) {
discussion = nodes[0];
try {
await octokit.graphql(`
mutation {
addDiscussionComment(input: { body: ${JSON.stringify(
body
)}, discussionId: "${discussion.id}" }) {
comment { id }
}
}
`);
} catch (err) {
console.error(
"[onRateAction] Failed to add comment to existing discussion",
{
url,
feedback,
discussionId: discussion.id,
error: err,
}
);
throw new Error("Failed to add comment to existing discussion.");
}
} else {
let result;
try {
result = await octokit.graphql(`
mutation {
createDiscussion(input: { repositoryId: "${
destination.id
}", categoryId: "${category.id}", body: ${JSON.stringify(
body
)}, title: ${JSON.stringify(title)} }) {
discussion { id, url }
}
}
`);
discussion = result?.createDiscussion?.discussion || result?.discussion;
} catch (err) {
console.error("[onRateAction] Error creating discussion", {
url,
feedback,
error: err,
});
}
if (!discussion) {
try {
const retrySearch = await octokit.graphql(`
query {
search(type: DISCUSSION, query: ${JSON.stringify(
`${title} in:title repo:${owner}/${repo} author:@me`
)}, first: 1) {
nodes {
... on Discussion { id, url }
}
}
}
`);
const retryNodes: { id: string; url: string }[] =
retrySearch.search.nodes;
if (retryNodes && retryNodes.length > 0 && retryNodes[0]) {
discussion = retryNodes[0];
}
} catch (err) {
console.error(
"[onRateAction] Error retrying discussion search after creation failure",
{
url,
feedback,
error: err,
}
);
}
}
}
if (!discussion) {
console.error(
"[onRateAction] Final failure: could not find or create discussion",
{
url,
feedback,
title,
}
);
throw new Error(
"Failed to create or find a discussion for feedback. Please ensure the 'Feedback' category exists in your GitHub Discussions and your GitHub App has the correct permissions."
);
}
return {
githubUrl: discussion.url,
};
}
================================================
FILE: lib/i18n.ts
================================================
import { defineI18n } from "fumadocs-core/i18n";
export const i18n = defineI18n({
defaultLanguage: "en",
languages: ["en" /*, "cn", "zh", "ja", "ru", "fr"*/],
hideLocale: "default-locale",
});
export type Language = (typeof i18n.languages)[number];
export function localizeUrl(url: string, lang: Language): string {
return lang === i18n.defaultLanguage ? url : `/${lang}${url}`;
}
interface FeedbackTranslations {
wasHelpful: string;
good: string;
bad: string;
thankYou: string;
submitAgain: string;
placeholder: string;
submit: string;
viewOnGitHub: string;
}
interface UIDictionary {
metadata: {
titleTemplate: string;
defaultTitle: string;
description: string;
};
nav: {
navigation: Array<{
name: string;
href: string;
}>;
};
feedback: FeedbackTranslations;
}
export const uiDictionary: Record = {
en: {
metadata: {
titleTemplate: "%s | AIcademy",
defaultTitle: "AIcademy - Free AI Education for All",
description: "A friendly community offering free AI education",
},
nav: {
navigation: [
{ name: "Courses", href: "/courses" },
{ name: "Blog", href: "/blog" },
{ name: "About", href: "/about" },
],
},
feedback: {
wasHelpful: "Was this page helpful?",
good: "Yes",
bad: "No",
thankYou: "Thank you for your feedback!",
submitAgain: "Submit Again?",
placeholder: "Leave your feedback...",
submit: "Submit",
viewOnGitHub: "View on GitHub",
},
},
/*
zh: {
metadata: {
titleTemplate: "%s | AIcademy",
defaultTitle: "AIcademy - 免费AI教育平台",
description: "一个提供免费AI教育的友好社区",
},
nav: {
navigation: [
{ name: "课程", href: "/cn/courses" },
{ name: "博客", href: "/cn/blog" },
{ name: "关于我们", href: "/cn/about" },
],
},
feedback: {
wasHelpful: "这个页面对您有帮助吗?",
good: "有帮助",
bad: "没帮助",
thankYou: "感谢您的反馈!",
submitAgain: "要再次提交吗?",
placeholder: "欢迎留下您的反馈……",
submit: "提交",
viewOnGitHub: "在 GitHub 查看",
},
},
ja: {
metadata: {
titleTemplate: "%s | AIcademy",
defaultTitle: "AIcademy - 無料で学べるAI教育",
description: "誰でも無料で学べる、フレンドリーなAI教育コミュニティ",
},
nav: {
navigation: [
{ name: "コース", href: "/ja/courses" },
{ name: "ブログ", href: "/ja/blog" },
{ name: "概要", href: "/ja/about" },
],
},
feedback: {
wasHelpful: "このページは役に立ちましたか?",
good: "はい",
bad: "いいえ",
thankYou: "ご意見ありがとうございます!",
submitAgain: "もう一度送信しますか?",
placeholder: "ご意見・ご感想をご記入ください…",
submit: "送信する",
viewOnGitHub: "GitHub で見る",
},
},
ru: {
metadata: {
titleTemplate: "%s | AIcademy",
defaultTitle: "AIcademy — бесплатное образование в сфере ИИ",
description:
"Дружелюбное сообщество, предлагающее бесплатное обучение ИИ",
},
nav: {
navigation: [
{ name: "Курсы", href: "/ru/courses" },
{ name: "Блог", href: "/ru/blog" },
{ name: "О проекте", href: "/ru/about" },
],
},
feedback: {
wasHelpful: "Эта страница была полезной?",
good: "Да",
bad: "Нет",
thankYou: "Спасибо за отзыв!",
submitAgain: "Отправить снова?",
placeholder: "Оставьте свой отзыв...",
submit: "Отправить",
viewOnGitHub: "Посмотреть на GitHub",
},
},
fr: {
metadata: {
titleTemplate: "%s | AIcademy",
defaultTitle: "AIcademy - Éducation gratuite à l'IA",
description:
"Une communauté bienveillante proposant une éducation gratuite à l'IA",
},
nav: {
navigation: [
{ name: "Cours", href: "/fr/courses" },
{ name: "Blog", href: "/fr/blog" },
{ name: "À propos", href: "/fr/about" },
],
},
feedback: {
wasHelpful: "Cette page vous a-t-elle été utile ?",
good: "Oui",
bad: "Non",
thankYou: "Merci pour votre retour !",
submitAgain: "Envoyer un autre retour ?",
placeholder: "Laissez-nous votre avis...",
submit: "Envoyer",
viewOnGitHub: "Voir sur GitHub",
},
},
*/
};
================================================
FILE: lib/metadata.ts
================================================
import type { Metadata } from "next/types";
export function createMetadata(override: Metadata): Metadata {
return {
...override,
openGraph: {
title: override.title ?? undefined,
description: override.description ?? undefined,
url: "https://aicademyorg.netlify.app",
images: "/banner.png",
siteName: "AIcademy",
...override.openGraph,
},
twitter: {
card: "summary_large_image",
creator: "@aicademyorg",
title: override.title ?? undefined,
description: override.description ?? undefined,
images: "/banner.png",
...override.twitter,
},
icons: {
icon: "/favicon.ico",
},
};
}
export const baseUrl =
process.env.NODE_ENV === "development" || !process.env.VERCEL_URL
? new URL("http://localhost:3000")
: new URL(`https://${process.env.VERCEL_URL}`);
================================================
FILE: lib/source.ts
================================================
import { docs } from "@/.source/server";
import { loader } from "fumadocs-core/source";
import { i18n } from "@/lib/i18n";
import { icons } from "lucide-react";
import { createElement } from "react";
import * as SiIcons from "react-icons/si";
// See https://fumadocs.vercel.app/docs/headless/source-api for more info
export const source = loader({
// it assigns a URL to your pages
i18n,
baseUrl: "/docs",
icon(icon) {
if (icon && icon in icons)
return createElement(icons[icon as keyof typeof icons]);
if (icon && icon in SiIcons)
return createElement(SiIcons[icon as keyof typeof SiIcons]);
},
source: docs.toFumadocsSource(),
});
================================================
FILE: mdx-components.tsx
================================================
import defaultMdxComponents from "fumadocs-ui/mdx";
import * as FilesComponents from "fumadocs-ui/components/files";
import * as TabsComponents from "fumadocs-ui/components/tabs";
import type { MDXComponents } from "mdx/types";
import { Accordion, Accordions } from "fumadocs-ui/components/accordion";
import * as icons from "lucide-react";
import { ImageZoom } from "fumadocs-ui/components/image-zoom";
import { Mermaid } from "@/components/mdx/mermaid";
export function getMDXComponents(components?: MDXComponents): MDXComponents {
return {
...(icons as unknown as MDXComponents),
...defaultMdxComponents,
...TabsComponents,
...FilesComponents,
img: (props) => ,
Accordion,
Accordions,
Mermaid,
...components,
};
}
================================================
FILE: next.config.mjs
================================================
import { createMDX } from "fumadocs-mdx/next";
const withMDX = createMDX();
/** @type {import('next').NextConfig} */
const config = {
reactStrictMode: true,
async rewrites() {
return [
{
source: "/:lang/docs/:path*.mdx",
destination: "/:lang/llms.mdx/:path*",
},
];
},
};
export default withMDX(config);
================================================
FILE: package.json
================================================
{
"name": "aicademy",
"version": "0.0.0",
"private": true,
"scripts": {
"build": "next build",
"dev": "next dev --turbo",
"start": "next start",
"postinstall": "fumadocs-mdx"
},
"dependencies": {
"@tailwindcss/postcss": "^4.1.18",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"fumadocs-core": "16.6.3",
"fumadocs-mdx": "14.2.7",
"fumadocs-ui": "16.6.3",
"katex": "^0.16.28",
"lucide-react": "^0.574.0",
"mermaid": "^11.12.3",
"next": "16.1.6",
"next-themes": "^0.4.6",
"octokit": "^5.0.5",
"postcss": "^8.5.6",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-icons": "^5.5.0",
"rehype-katex": "^7.0.1",
"remark": "^15.0.1",
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"remark-mdx": "^3.1.1",
"shiki": "^3.22.0",
"tailwind-merge": "^3.4.1",
"tailwindcss": "^4.1.18",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/mdx": "^2.0.13",
"@types/node": "25.2.3",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"typescript": "^5.9.3"
}
}
================================================
FILE: postcss.config.mjs
================================================
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
================================================
FILE: proxy.ts
================================================
import type { NextRequest, NextFetchEvent } from "next/server";
import { NextResponse } from "next/server";
import { createI18nMiddleware } from "fumadocs-core/i18n/middleware";
import { i18n } from "@/lib/i18n";
const i18nMiddleware = createI18nMiddleware(i18n);
export function proxy(request: NextRequest, event: NextFetchEvent) {
const { pathname } = request.nextUrl;
// Handle .md requests
if (pathname.endsWith(".md")) {
const pathWithoutMd = pathname.slice(0, -3);
const langMatch = pathWithoutMd.match(/^\/([a-z]{2})(\/.*)?$/);
let lang = i18n.defaultLanguage;
let docPath = pathWithoutMd;
if (langMatch && i18n.languages.includes(langMatch[1] as any)) {
lang = langMatch[1] as any;
docPath = langMatch[2] || "";
} else {
docPath = pathWithoutMd;
}
// Remove leading slash from docPath if present
if (docPath.startsWith("/")) {
docPath = docPath.slice(1);
}
// Handle root/index case
if (!docPath || docPath === "") {
docPath = "index";
}
// Remove 'docs' prefix if present (since the source system handles docs structure)
if (docPath.startsWith("docs/")) {
docPath = docPath.slice(5); // Remove 'docs/'
} else if (docPath === "docs") {
docPath = "index";
}
// Construct the llms.mdx route with language and slug
const slugParts = docPath.split("/").filter(Boolean);
const llmsRoute =
slugParts.length > 0
? `/${lang}/llms.mdx/${slugParts.join("/")}`
: `/${lang}/llms.mdx`;
return NextResponse.rewrite(new URL(llmsRoute, request.url));
}
// Continue with i18n middleware for non-.md requests
return i18nMiddleware(request, event);
}
export const config = {
// Matcher ignoring `/_next/` and `/api/` but including .md files
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
================================================
FILE: source.config.ts
================================================
import {
defineConfig,
defineDocs,
frontmatterSchema,
metaSchema,
} from "fumadocs-mdx/config";
import rehypeKatex from "rehype-katex";
import remarkMath from "remark-math";
import { z } from "zod";
export const docs = defineDocs({
dir: "./content/docs",
docs: {
schema: frontmatterSchema.extend({
index: z.boolean().default(false),
colab: z.string().optional(),
}),
postprocess: {
includeProcessedMarkdown: true,
},
},
meta: {
schema: metaSchema,
},
});
export default defineConfig({
mdxOptions: {
remarkPlugins: [remarkMath],
rehypePlugins: (v) => [rehypeKatex, ...v],
},
});
================================================
FILE: tsconfig.json
================================================
{
"compilerOptions": {
"baseUrl": ".",
"target": "ESNext",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"paths": {
"@/.source": [
"./.source/server.ts"
],
"@/*": [
"./*"
]
},
"plugins": [
{
"name": "next"
}
]
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"tailwind.config.js",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}
================================================
FILE: utils/process-markdown-links.ts
================================================
/**
* Processes markdown content to convert relative links to absolute URLs with .md extension
* This is used when copying markdown content for LLMs
*/
export function processMarkdownLinks(
content: string,
baseUrl: string = 'https://aicademyorg.netlify.app/',
): string {
// Process standard markdown links: [text](/path)
content = content.replace(/\[([^\]]+)\]\(\/([^)]+)\)/g, (match, text, path) => {
// Skip if it's already an absolute URL
if (path.startsWith('http://') || path.startsWith('https://')) {
return match;
}
// Remove any trailing slashes
const cleanPath = path.replace(/\/$/, '');
// Don't add .md if it already has an extension or is an anchor
if (cleanPath.includes('.') || cleanPath.includes('#')) {
return `[${text}](${baseUrl}/${cleanPath})`;
}
// Add .md extension for documentation links
return `[${text}](${baseUrl}/${cleanPath}.md)`;
});
// Process HTML links:
content = content.replace(/href="\/([^"]+)"/g, (match, path) => {
// Skip if it's already an absolute URL
if (path.startsWith('http://') || path.startsWith('https://')) {
return match;
}
// Remove any trailing slashes
const cleanPath = path.replace(/\/$/, '');
// Don't add .md if it already has an extension or is an anchor
if (cleanPath.includes('.') || cleanPath.includes('#')) {
return `href="${baseUrl}/${cleanPath}"`;
}
// Add .md extension for documentation links
return `href="${baseUrl}/${cleanPath}.md"`;
});
// Process reference-style links: [text]: /path
content = content.replace(/^\[([^\]]+)\]:\s*\/(.+)$/gm, (match, ref, path) => {
// Skip if it's already an absolute URL
if (path.startsWith('http://') || path.startsWith('https://')) {
return match;
}
// Remove any trailing slashes
const cleanPath = path.replace(/\/$/, '');
// Don't add .md if it already has an extension
if (cleanPath.includes('.') || cleanPath.includes('#')) {
return `[${ref}]: ${baseUrl}/${cleanPath}`;
}
// Add .md extension for documentation links
return `[${ref}]: ${baseUrl}/${cleanPath}.md`;
});
return content;
}