Skip to content

Commit 807d0f3

Browse files
authored
Merge branch 'main' into main
2 parents 90e238e + d1d5698 commit 807d0f3

File tree

5 files changed

+267
-2
lines changed

5 files changed

+267
-2
lines changed

CONTRIBUTING.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ The list of topics for which we are looking for content are provided below along
2424
- Web Scrapping - [Link](https://github.com/animator/learn-python/tree/main/contrib/web-scrapping)
2525
- API Development - [Link](https://github.com/animator/learn-python/tree/main/contrib/api-development)
2626
- Data Structures & Algorithms - [Link](https://github.com/animator/learn-python/tree/main/contrib/ds-algorithms)
27-
- Python Mini Projects - [Link](https://github.com/animator/learn-python/tree/main/contrib/mini-projects)
28-
- Python Question Bank - [Link](https://github.com/animator/learn-python/tree/main/contrib/question-bank)
27+
- Python Mini Projects - [Link](https://github.com/animator/learn-python/tree/main/contrib/mini-projects) **(Not accepting)**
28+
- Python Question Bank - [Link](https://github.com/animator/learn-python/tree/main/contrib/question-bank) **(Not accepting)**
2929

3030
You can check out some content ideas below.
3131

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
# Exception Handling in Python
2+
3+
Exception Handling is a way of managing the errors that may occur during a program execution. Python's exception handling mechanism has been designed to avoid the unexpected termination of the program, and offer to either regain control after an error or display a meaningful message to the user.
4+
5+
- **Error** - An error is a mistake or an incorrect result produced by a program. It can be a syntax error, a logical error, or a runtime error. Errors are typically fatal, meaning they prevent the program from continuing to execute.
6+
- **Exception** - An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions are typically unexpected and can be handled by the program to prevent it from crashing or terminating abnormally. It can be runtime, input/output or system exceptions. Exceptions are designed to be handled by the program, allowing it to recover from the error and continue executing.
7+
8+
## Python Built-in Exceptions
9+
10+
There are plenty of built-in exceptions in Python that are raised when a corresponding error occur.
11+
We can view all the built-in exceptions using the built-in `local()` function as follows:
12+
13+
```python
14+
print(dir(locals()['__builtins__']))
15+
```
16+
17+
|**S.No**|**Exception**|**Description**|
18+
|---|---|---|
19+
|1|SyntaxError|A syntax error occurs when the code we write violates the grammatical rules such as misspelled keywords, missing colon, mismatched parentheses etc.|
20+
|2|TypeError|A type error occurs when we try to perform an operation or use a function with objects that are of incompatible data types.|
21+
|3|NameError|A name error occurs when we try to use a variable, function, module or string without quotes that hasn't been defined or isn't used in a valid way.|
22+
|4|IndexError|A index error occurs when we try to access an element in a sequence (like a list, tuple or string) using an index that's outside the valid range of indices for that sequence.|
23+
|5|KeyError|A key error occurs when we try to access a key that doesn't exist in a dictionary. Attempting to retrieve a value using a non-existent key results this error.|
24+
|6|ValueError|A value error occurs when we provide an argument or value that's inappropriate for a specific operation or function such as doing mathematical operations with incompatible types (e.g., dividing a string by an integer.)|
25+
|7|AttributeError|An attribute error occurs when we try to access an attribute (like a variable or method) on an object that doesn't possess that attribute.|
26+
|8|IOError|An IO (Input/Output) error occurs when an operation involving file or device interaction fails. It signifies that there's an issue during communication between your program and the external system.|
27+
|9|ZeroDivisionError|A ZeroDivisionError occurs when we attempt to divide a number by zero. This operation is mathematically undefined, and Python raises this error to prevent nonsensical results.|
28+
|10|ImportError|An import error occurs when we try to use a module or library that Python can't find or import succesfully.|
29+
30+
## Try and Except Statement - Catching Exception
31+
32+
The `try-except` statement allows us to anticipate potential errors during program execution and define what actions to take when those errors occur. This prevents the program from crashing unexpectedly and makes it more robust.
33+
34+
Here's an example to explain this:
35+
36+
```python
37+
try:
38+
# Code that might raise an exception
39+
result = 10 / 0
40+
except:
41+
print("An error occured!")
42+
```
43+
44+
Output
45+
46+
```markdown
47+
An error occured!
48+
```
49+
50+
In this example, the `try` block contains the code that you suspect might raise an exception. Python attempts to execute the code within this block. If an exception occurs, Python jumps to the `except` block and executes the code within it.
51+
52+
## Specific Exception Handling
53+
54+
You can specify the type of expection you want to catch using the `except` keyword followed by the exception class name. You can also have multiple `except` blocks to handle different exception types.
55+
56+
Here's an example:
57+
58+
```python
59+
try:
60+
# Code that might raise ZeroDivisionError or NameError
61+
result = 10 / 0
62+
name = undefined_variable
63+
except ZeroDivisionError:
64+
print("Oops! You tried to divide by zero.")
65+
except NameError:
66+
print("There's a variable named 'undefined_variable' that hasn't been defined yet.")
67+
```
68+
69+
Output
70+
71+
```markdown
72+
Oops! You tried to divide by zero.
73+
```
74+
75+
If you comment on the line `result = 10 / 0`, then the output will be:
76+
77+
```markdown
78+
There's a variable named 'undefined_variable' that hasn't been defined yet.
79+
```
80+
81+
## Important Note
82+
83+
In this code, the `except` block are specific to each type of expection. If you want to catch both exceptions with a single `except` block, you can use of tuple of exceptions, like this:
84+
85+
```python
86+
try:
87+
# Code that might raise ZeroDivisionError or NameError
88+
result = 10 / 0
89+
name = undefined_variable
90+
except (ZeroDivisionError, NameError):
91+
print("An error occured!")
92+
```
93+
94+
Output
95+
96+
```markdown
97+
An error occured!
98+
```
99+
100+
## Try with Else Clause
101+
102+
The `else` clause in a Python `try-except` block provides a way to execute code only when the `try` block succeeds without raising any exceptions. It's like having a section of code that runs exclusively under the condition that no errors occur during the main operation in the `try` block.
103+
104+
Here's an example to understand this:
105+
106+
```python
107+
def calculate_average(numbers):
108+
if len(numbers) == 0: # Handle empty list case seperately (optional)
109+
return None
110+
try:
111+
total = sum(numbers)
112+
average = total / len(numbers)
113+
except ZeroDivisionError:
114+
print("Cannot calculate average for a list containing zero.")
115+
else:
116+
print("The average is:", average)
117+
return average #Optionally return the average here
118+
119+
# Example usage
120+
numbers = [10, 20, 30]
121+
result = calculate_average(numbers)
122+
123+
if result is not None: # Check if result is available (handles empty list case)
124+
print("Calculation succesfull!")
125+
```
126+
127+
Output
128+
129+
```markdown
130+
The average is: 20.0
131+
```
132+
133+
## Finally Keyword in Python
134+
135+
The `finally` keyword in Python is used within `try-except` statements to execute a block of code **always**, regardless of whether an exception occurs in the `try` block or not.
136+
137+
To understand this, let us take an example:
138+
139+
```python
140+
try:
141+
a = 10 // 0
142+
print(a)
143+
except ZeroDivisionError:
144+
print("Cannot be divided by zero.")
145+
finally:
146+
print("Program executed!")
147+
```
148+
149+
Output
150+
151+
```markdown
152+
Cannot be divided by zero.
153+
Program executed!
154+
```
155+
156+
## Raise Keyword in Python
157+
158+
In Python, raising an exception allows you to signal that an error condition has occured during your program's execution. The `raise` keyword is used to explicity raise an exception.
159+
160+
Let us take an example:
161+
162+
```python
163+
def divide(x, y):
164+
if y == 0:
165+
raise ZeroDivisionError("Can't divide by zero!") # Raise an exception with a message
166+
result = x / y
167+
return result
168+
169+
try:
170+
division_result = divide(10, 0)
171+
print("Result:", division_result)
172+
except ZeroDivisionError as e:
173+
print("An error occured:", e) # Handle the exception and print the message
174+
```
175+
176+
Output
177+
178+
```markdown
179+
An error occured: Can't divide by zero!
180+
```
181+
182+
## Advantages of Exception Handling
183+
184+
- **Improved Error Handling** - It allows you to gracefully handle unexpected situations that arise during program execution. Instead of crashing abruptly, you can define specific actions to take when exceptions occur, providing a smoother experience.
185+
- **Code Robustness** - Exception Handling helps you to write more resilient programs by anticipating potential issues and providing approriate responses.
186+
- **Enhanced Code Readability** - By seperating error handling logic from the core program flow, your code becomes more readable and easier to understand. The `try-except` blocks clearly indicate where potential errors might occur and how they'll be addressed.
187+
188+
## Disadvantages of Exception Handling
189+
190+
- **Hiding Logic Errors** - Relying solely on exception handling might mask underlying logic error in your code. It's essential to write clear and well-tested logic to minimize the need for excessive exception handling.
191+
- **Performance Overhead** - In some cases, using `try-except` blocks can introduce a slight performance overhead compared to code without exception handling. Howerer, this is usually negligible for most applications.
192+
- **Overuse of Exceptions** - Overusing exceptions for common errors or control flow can make code less readable and harder to maintain. It's important to use exceptions judiciously for unexpected situations.

contrib/advanced-python/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@
77
- [Regular Expressions in Python](regular_expressions.md)
88
- [JSON module](json-module.md)
99
- [Map Function](map-function.md)
10+
- [Exception Handling in Python](exception-handling.md)
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Grid Search
2+
3+
Grid Search is a hyperparameter tuning technique in Machine Learning that helps to find the best combination of hyperparameters for a given model. It works by defining a grid of hyperparameters and then training the model with all the possible combinations of hyperparameters to find the best performing set.
4+
5+
The Grid Search Method considers some hyperparameter combinations and selects the one returning a lower error score. This method is specifically useful when there are only some hyperparameters in order to optimize. However, it is outperformed by other weighted-random search methods when the Machine Learning model grows in complexity.
6+
7+
## Implementation
8+
9+
Before applying Grid Searching on any algorithm, data is divided into training and validation set, a validation set is used to validate the models. A model with all possible combinations of hyperparameters is tested on the validation set to choose the best combination.
10+
11+
Grid Searching can be applied to any hyperparameters algorithm whose performance can be improved by tuning hyperparameter. For example, we can apply grid searching on K-Nearest Neighbors by validating its performance on a set of values of K in it. Same thing we can do with Logistic Regression by using a set of values of learning rate to find the best learning rate at which Logistic Regression achieves the best accuracy.
12+
13+
Let us consider that the model accepts the below three parameters in the form of input:
14+
1. Number of hidden layers `[2, 4]`
15+
2. Number of neurons in every layer `[5, 10]`
16+
3. Number of epochs `[10, 50]`
17+
18+
If we want to try out two options for every parameter input (as specified in square brackets above), it estimates different combinations. For instance, one possible combination can be `[2, 5, 10]`. Finding such combinations manually would be a headache.
19+
20+
Now, suppose that we had ten different parameters as input, and we would like to try out five possible values for each and every parameter. It would need manual input from the programmer's end every time we like to alter the value of a parameter, re-execute the code, and keep a record of the outputs for every combination of the parameters.
21+
22+
Grid Search automates that process, as it accepts the possible value for every parameter and executes the code in order to try out each and every possible combination outputs the result for the combinations and outputs the combination having the best accuracy.
23+
24+
Higher values of C tell the model, the training data resembles real world information, place a greater weight on the training data. While lower values of C do the opposite.
25+
26+
## Explaination of the Code
27+
28+
The code provided performs hyperparameter tuning for a Logistic Regression model using a manual grid search approach. It evaluates the model's performance for different values of the regularization strength hyperparameter C on the Iris dataset.
29+
1. datasets from sklearn is imported to load the Iris dataset.
30+
2. LogisticRegression from sklearn.linear_model is imported to create and fit the logistic regression model.
31+
3. The Iris dataset is loaded, with X containing the features and y containing the target labels.
32+
4. A LogisticRegression model is instantiated with max_iter=10000 to ensure convergence during the fitting process, as the default maximum iterations (100) might not be sufficient.
33+
5. A list of different values for the regularization strength C is defined. The hyperparameter C controls the regularization strength, with smaller values specifying stronger regularization.
34+
6. An empty list scores is initialized to store the model's performance scores for different values of C.
35+
7. A for loop iterates over each value in the C list:
36+
8. logit.set_params(C=choice) sets the C parameter of the logistic regression model to the current value in the loop.
37+
9. logit.fit(X, y) fits the logistic regression model to the entire Iris dataset (this is typically done on training data in a real scenario, not the entire dataset).
38+
10. logit.score(X, y) calculates the accuracy of the fitted model on the dataset and appends this score to the scores list.
39+
11. After the loop, the scores list is printed, showing the accuracy for each value of C.
40+
41+
### Python Code
42+
43+
```python
44+
from sklearn import datasets
45+
from sklearn.linear_model import LogisticRegression
46+
47+
iris = datasets.load_iris()
48+
X = iris['data']
49+
y = iris['target']
50+
51+
logit = LogisticRegression(max_iter = 10000)
52+
53+
C = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2]
54+
55+
scores = []
56+
for choice in C:
57+
logit.set_params(C=choice)
58+
logit.fit(X, y)
59+
scores.append(logit.score(X, y))
60+
print(scores)
61+
```
62+
63+
#### Results
64+
65+
```
66+
[0.9666666666666667, 0.9666666666666667, 0.9733333333333334, 0.9733333333333334, 0.98, 0.98, 0.9866666666666667, 0.9866666666666667]
67+
```
68+
69+
We can see that the lower values of `C` performed worse than the base parameter of `1`. However, as we increased the value of `C` to `1.75` the model experienced increased accuracy.
70+
71+
It seems that increasing `C` beyond this amount does not help increase model accuracy.

contrib/machine-learning/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@
1111
- [Types of optimizers](Types_of_optimizers.md)
1212
- [Logistic Regression](logistic-regression.md)
1313
- [Clustering](clustering.md)
14+
- [Grid Search](grid-search.md)

0 commit comments

Comments
 (0)