Skip to content

Commit 8186d2e

Browse files
authored
Merge branch 'main' into main
2 parents bc54697 + 4dcdc32 commit 8186d2e

16 files changed

+1014
-3
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
## Working with Dates and Times in Python
2+
Handling dates and times is an essential aspect of many programming tasks.
3+
Python provides robust modules to work with dates and times, making it easier to perform operations like formatting, parsing, and arithmetic.
4+
This guide provides an overview of these modules and their key functionalities.
5+
6+
## 1. 'datetime' Module
7+
The datetime module supplies classes for manipulating dates and times. The main classes in the datetime module are:
8+
9+
* date: Represents a date (year, month, day).
10+
* time: Represents a time (hour, minute, second, microsecond).
11+
* datetime: Combines date and time information.
12+
* timedelta: Represents the difference between two dates or times.
13+
* tzinfo: Provides time zone information objects.
14+
15+
**Key Concepts:**
16+
17+
* Naive vs. Aware: Naive datetime objects do not contain time zone information, while aware datetime objects do.
18+
* Immutability: date and time objects are immutable; once created, they cannot be changed.
19+
20+
Example:
21+
```bash
22+
import datetime
23+
# Get the current date and time
24+
now = datetime.datetime.now()
25+
print("Current date and time:", now)
26+
```
27+
28+
## 2. Formatting Dates and Times
29+
Formatting involves converting datetime objects into human-readable strings. This is achieved using the strftime method, which stands for "string format time."
30+
You can specify various format codes to dictate how the output string should be structured.
31+
32+
**Common Format Codes:**
33+
34+
* %Y: Year with century (e.g., 2024)
35+
* %m: Month as a zero-padded decimal number (e.g., 01)
36+
* %d: Day of the month as a zero-padded decimal number (e.g., 15)
37+
* %H: Hour (24-hour clock) as a zero-padded decimal number (e.g., 13)
38+
* %M: Minute as a zero-padded decimal number (e.g., 45)
39+
* %S: Second as a zero-padded decimal number (e.g., 30)
40+
41+
Example:
42+
```bash
43+
import datetime
44+
45+
now = datetime.datetime.now()
46+
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
47+
print("Formatted current date and time:", formatted_now)
48+
```
49+
50+
## 3. Parsing Dates and Times
51+
Parsing is the process of converting strings representing dates and times into datetime objects. The strptime method, which stands for "string parse time,"
52+
allows you to specify the format of the input string.
53+
54+
Example:
55+
```bash
56+
import datetime
57+
58+
date_string = "2024-05-15 13:45:30"
59+
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
60+
print("Parsed date and time:", date_object)
61+
```
62+
63+
## 4. Working with Time Differences
64+
The timedelta class is used to represent the difference between two datetime objects. This is useful for calculations involving durations, such as finding the
65+
number of days between two dates or adding a certain period to a date.
66+
67+
Example:
68+
```bash
69+
import datetime
70+
71+
date1 = datetime.datetime(2024, 5, 15, 12, 0, 0)
72+
date2 = datetime.datetime(2024, 5, 20, 14, 30, 0)
73+
74+
difference = date2 - date1
75+
print("Difference:", difference)
76+
print("Days:", difference.days)
77+
print("Total seconds:", difference.total_seconds())
78+
```
79+
80+
## 5. Time Zones
81+
Time zone handling in Python is facilitated by the pytz library. It allows you to convert naive datetime objects into timezone-aware objects and perform
82+
operations across different time zones.
83+
84+
**Key Concepts:**
85+
86+
* Timezone-aware: A datetime object that includes timezone information.
87+
* Localization: The process of associating a naive datetime with a time zone.
88+
89+
Example:
90+
```bash
91+
import datetime
92+
import pytz
93+
94+
# Define a timezone
95+
tz = pytz.timezone('Asia/Kolkata')
96+
97+
# Get the current time in a specific timezone
98+
now = datetime.datetime.now(tz)
99+
print("Current time in Asia/Kolkata:", now)
100+
```
101+
102+
## 6. Date Arithmetic
103+
Date arithmetic involves performing operations like addition or subtraction on date or datetime objects using timedelta. This is useful for calculating future
104+
or past dates based on a given date.
105+
106+
Example:
107+
```bash
108+
import datetime
109+
110+
today = datetime.date.today()
111+
future_date = today + datetime.timedelta(days=10)
112+
print("Date after 10 days:", future_date)
113+
```
114+
115+
## Summary
116+
Python’s datetime module and the pytz library provide comprehensive tools for working with dates, times, and time zones. They enable you to perform a wide range
117+
of operations, from basic date manipulations to complex time zone conversions.

contrib/advanced-python/index.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# List of sections
22

33
- [Decorators/\*args/**kwargs](decorator-kwargs-args.md)
4+
- [Working with Dates & Times in Python](dates_and_times.md)
5+
- [Regular Expressions in Python](regular_expressions.md)
46
- [JSON module](json-module.md)
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
## Regular Expressions in Python
2+
Regular expressions (regex) are a powerful tool for pattern matching and text manipulation.
3+
Python's re module provides comprehensive support for regular expressions, enabling efficient text processing and validation.
4+
5+
## 1. Introduction to Regular Expressions
6+
A regular expression is a sequence of characters defining a search pattern. Common use cases include validating input, searching within text, and extracting
7+
specific patterns.
8+
9+
## 2. Basic Syntax
10+
Literal Characters: Match exact characters (e.g., abc matches "abc").
11+
Metacharacters: Special characters like ., *, ?, +, ^, $, [ ], and | used to build patterns.
12+
13+
**Common Metacharacters:**
14+
15+
* .: Any character except newline.
16+
* ^: Start of the string.
17+
* $: End of the string.
18+
* *: 0 or more repetitions.
19+
* +: 1 or more repetitions.
20+
* ?: 0 or 1 repetition.
21+
* []: Any one character inside brackets (e.g., [a-z]).
22+
* |: Either the pattern before or after.
23+
24+
## 3. Using the re Module
25+
26+
**Key functions in the re module:**
27+
28+
* re.match(): Checks for a match at the beginning of the string.
29+
* re.search(): Searches for a match anywhere in the string.
30+
* re.findall(): Returns a list of all matches.
31+
* re.sub(): Replaces matches with a specified string.
32+
33+
Examples:
34+
```bash
35+
import re
36+
37+
# Match at the beginning
38+
print(re.match(r'\d+', '123abc').group()) # Output: 123
39+
40+
# Search anywhere
41+
print(re.search(r'\d+', 'abc123').group()) # Output: 123
42+
43+
# Find all matches
44+
print(re.findall(r'\d+', 'abc123def456')) # Output: ['123', '456']
45+
46+
# Substitute matches
47+
print(re.sub(r'\d+', '#', 'abc123def456')) # Output: abc#def#
48+
```
49+
50+
## 4. Compiling Regular Expressions
51+
Compiling regular expressions improves performance for repeated use.
52+
53+
Example:
54+
```bash
55+
import re
56+
57+
pattern = re.compile(r'\d+')
58+
print(pattern.match('123abc').group()) # Output: 123
59+
print(pattern.search('abc123').group()) # Output: 123
60+
print(pattern.findall('abc123def456')) # Output: ['123', '456']
61+
```
62+
63+
## 5. Groups and Capturing
64+
Parentheses () group and capture parts of the match.
65+
66+
Example:
67+
```bash
68+
import re
69+
70+
match = re.match(r'(\d{3})-(\d{2})-(\d{4})', '123-45-6789')
71+
if match:
72+
print(match.group()) # Output: 123-45-6789
73+
print(match.group(1)) # Output: 123
74+
print(match.group(2)) # Output: 45
75+
print(match.group(3)) # Output: 6789
76+
```
77+
78+
## 6. Special Sequences
79+
Special sequences are shortcuts for common patterns:
80+
81+
* \d: Any digit.
82+
* \D: Any non-digit.
83+
* \w: Any alphanumeric character.
84+
* \W: Any non-alphanumeric character.
85+
* \s: Any whitespace character.
86+
* \S: Any non-whitespace character.
87+
Example:
88+
```bash
89+
import re
90+
91+
print(re.search(r'\w+@\w+\.\w+', 'Contact: support@example.com').group()) # Output: support@example.com
92+
```
93+
94+
## Summary
95+
Regular expressions are a versatile tool for text processing in Python. The re module offers powerful functions and metacharacters for pattern matching,
96+
searching, and manipulation, making it an essential skill for handling complex text processing tasks.
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
# Understanding the Neural Network
2+
3+
## Table of Contents
4+
<details>
5+
<summary>Click to expand</summary>
6+
7+
- [Introduciton](#introduction)
8+
- [Neuron to Perceptron](#neuron-to-perceptron)
9+
- [Key concepts](#key-concepts)
10+
- [Layers](#layers)
11+
- [Weights and Biases](#weights-and-biases)
12+
- [Activation Function](#activation-functions)
13+
- [Forward and Backward Pass](#forward-and-backward-propagation)
14+
- [Implementation](#building-from-scratch)
15+
16+
</details>
17+
18+
19+
## Introduction
20+
21+
This guide will walk you through a fundamental neural network implementation in Python. We'll build a `Neural Network` from scratch, allowing you to grasp the core concepts of how neural networks learn and make predictions.
22+
23+
### Let's start by Understanding the Basic Architecture of Neural Nets
24+
25+
## Neuron to Perceptron
26+
27+
| `Neuron` cells forming the humand nervous system | `Perceptron` inspired from human brain |
28+
| :----------------------------------------------- | -------------------------------------: |
29+
| Neurons are nerve cells that send messages all over your body to allow you to do everything from breathing to talking, eating, walking, and thinking. | The perceptron is a mathematical model of a biological neuron. Performing heavy computations to think like humans. |
30+
| Neuron collects signals from dendrites. | The first layer is knownn as Input Layer, acting like dendritres to receive the input signal. |
31+
| Synapses are the connections between neurons where signals are transmitted. | Weights represent synapses. |
32+
The axon terminal releases neurotransmitters to transmit the signal to other neurons. | The output is the final result – between 1 & 0, representing classification or prediction. |
33+
---
34+
> Human brain has a Network of Neurons, about 86 billion neurons and more than a 100 trillion synapses connections!
35+
36+
37+
## **Key Concepts**
38+
39+
Artificial neurons are the fundamental processing units in an ANN. They receive inputs, multiply them by weights (representing the strength of connections), sum those weighted inputs, and then apply an activation function to produce an output.
40+
41+
### Layers
42+
Neurons in ANNs are organized into layers:
43+
* **Input Layer:** Receives the raw data.
44+
* **(n) Hidden Layers:** (Optional) Intermediate layers where complex transformations occur. They learn to detect patterns and features in the data.
45+
* **Output Layer:** Produces the final result (prediction or classification).
46+
47+
### Weights and Biases
48+
- For each input $(x_i)$, a weight $(w_i)$ is associated with it. Weights, multiplied with input units $(w_i \cdot x_i)$, determine the influence of one neuron's output on another.
49+
- A bias $(b_i)$ is added to help influence the end product, giving the equation as $(w_i \cdot x_i + b_i)$.
50+
- During training, the network adjusts these weights and biases to minimize errors and improve its predictions.
51+
52+
### Activation Functions
53+
- An activation function is applied to the result to introduce non-linearity in the model, allowing ANNs to learn more complex relationships from the data.
54+
- The resulting equation: $y = f(g(x))$, determines whether the neuron will "fire" or not, i.e., if its output will be used as input for the next neuron.
55+
- Common activation functions include the sigmoid function, tanh (hyperbolic tangent), and ReLU (Rectified Linear Unit).
56+
57+
### Forward and Backward Propagation
58+
- **Flow of Information:** All the above steps are part of Forward Propagation. It gives the output equation as $y = f\left(\sum_{i=1}^n w_i x_i + b_i\right)$
59+
- **Error Correction:** Backpropagation is the algorithm used to train ANNs by calculating the gradient of error at the output layer and then propagating this error backward through the network. This allows the network to adjust its weights and biases in the direction that reduces the error.
60+
- The chain rule of calculus is the foundational concept to compute the gradient of the error:
61+
$
62+
\delta_{ij}(E) = \frac{\partial E}{\partial w_{ij}} = \frac{\partial E}{\partial \hat{y}_j} \cdot \frac{\partial \hat{y}_j}{\partial \theta_j} \cdot \frac{\partial \theta_j}{\partial w_{ij}}
63+
$
64+
where $E$ is the error, $\hat{y}_j$ is the predicted output, $\theta_j$ is the input to the activation function of the $j^{th}$ neuron, and $w_{ij}$ is the weight from neuron $i$ to neuron $j$.
65+
66+
67+
## Building From Scratch
68+
69+
```python
70+
# Import required libraries
71+
import numpy as np
72+
import matplotlib.pyplot as plt
73+
74+
class SimpleNeuralNetwork:
75+
def __init__(self, input_size, hidden_size, output_size):
76+
self.input_size = input_size
77+
self.hidden_size = hidden_size
78+
self.output_size = output_size
79+
80+
# Initialize weights and biases
81+
self.weights_input_hidden = np.random.randn(input_size, hidden_size)
82+
self.bias_hidden = np.random.randn(hidden_size)
83+
self.weights_hidden_output = np.random.randn(hidden_size, output_size)
84+
self.bias_output = np.random.randn(output_size)
85+
86+
def sigmoid(self, x):
87+
return 1 / (1 + np.exp(-x))
88+
89+
def sigmoid_derivative(self, x):
90+
return x * (1 - x)
91+
92+
def forward(self, X):
93+
self.hidden_layer_input = np.dot(X, self.weights_input_hidden) + self.bias_hidden
94+
self.hidden_layer_output = self.sigmoid(self.hidden_layer_input)
95+
96+
self.output_layer_input = np.dot(self.hidden_layer_output, self.weights_hidden_output) + self.bias_output
97+
self.output = self.sigmoid(self.output_layer_input)
98+
99+
return self.output
100+
101+
def backward(self, X, y, learning_rate):
102+
output_error = y - self.output
103+
output_delta = output_error * self.sigmoid_derivative(self.output)
104+
105+
hidden_error = output_delta.dot(self.weights_hidden_output.T)
106+
hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_layer_output)
107+
108+
self.weights_hidden_output += self.hidden_layer_output.T.dot(output_delta) * learning_rate
109+
self.bias_output += np.sum(output_delta, axis=0) * learning_rate
110+
self.weights_input_hidden += X.T.dot(hidden_delta) * learning_rate
111+
self.bias_hidden += np.sum(hidden_delta, axis=0) * learning_rate
112+
113+
def train(self, X, y, epochs, learning_rate):
114+
self.losses = []
115+
for epoch in range(epochs):
116+
self.forward(X)
117+
self.backward(X, y, learning_rate)
118+
loss = np.mean(np.square(y - self.output))
119+
self.losses.append(loss)
120+
if epoch % 1000 == 0:
121+
print(f"Epoch {epoch}, Loss: {loss}")
122+
123+
def plot_loss(self):
124+
plt.plot(self.losses)
125+
plt.xlabel('Epochs')
126+
plt.ylabel('Loss')
127+
plt.title('Training Loss Over Epochs')
128+
plt.show()
129+
```
130+
131+
### Creating the Input & Output Array
132+
Let's create a dummy input and outpu dataset. Here, the first two columns will be useful, while the rest might be noise.
133+
```python
134+
X = np.array([[0,0], [0,1], [1,0], [1,1]])
135+
y = np.array([[0], [1], [1], [1]])
136+
```
137+
138+
### Defining the Neural Network
139+
With our input and output data ready, we'll define a simple neural network with one hidden layer containing three neurons.
140+
```python
141+
# neural network architecture
142+
input_size = 2
143+
hidden_layers = 1
144+
hidden_neurons = [2]
145+
output_size = 1
146+
```
147+
148+
### Visualizing the Training Loss
149+
To understand how well our model is learning, let's visualize the training loss over epochs.
150+
```python
151+
model = NeuralNetwork(input_size, hidden_layers, hidden_neurons, output_size)
152+
model.train(X, y, 100)
153+
```

0 commit comments

Comments
 (0)