Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jun 29, 2024. It is now read-only.

Commit 6e86268

Browse files
Merge remote-tracking branch 'origin/main'
2 parents 5b72b07 + 39ee561 commit 6e86268

File tree

5 files changed

+187
-0
lines changed

5 files changed

+187
-0
lines changed

‎TASK-10.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import seaborn as sns
2+
import pandas as pd
3+
import matplotlib.pyplot as plt
4+
5+
# Load the Iris dataset from Seaborn
6+
iris = sns.load_dataset("iris")
7+
numeric_iris = iris.drop(columns='species')
8+
9+
# Display the first few rows of the dataset
10+
print("First few rows of the dataset:")
11+
print(iris.head())
12+
13+
# Summary statistics
14+
print("\nSummary statistics:")
15+
print(iris.describe())
16+
17+
# Checking for missing values
18+
print("\nMissing values:")
19+
print(iris.isnull().sum())
20+
21+
# Visualizations
22+
# Pairplot
23+
sns.pairplot(iris, hue="species")
24+
plt.title("Pairplot of Iris Dataset")
25+
plt.show()
26+
27+
# Boxplot
28+
plt.figure(figsize=(10, 6))
29+
sns.boxplot(data=iris, orient="h")
30+
plt.title("Boxplot of Iris Dataset")
31+
plt.show()
32+
33+
# Histograms
34+
plt.figure(figsize=(10, 6))
35+
iris.hist()
36+
plt.suptitle("Histograms of Iris Dataset")
37+
plt.show()
38+
39+
# Correlation heatmap
40+
plt.figure(figsize=(8, 6))
41+
sns.heatmap(numeric_iris.corr(), annot=True, cmap="coolwarm")
42+
plt.title("Correlation Heatmap of Iris Dataset")
43+
plt.show()

‎TASK-11.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import pandas as pd
2+
import numpy as np
3+
import matplotlib.pyplot as plt
4+
from sklearn.model_selection import train_test_split
5+
from sklearn.linear_model import LinearRegression
6+
from sklearn.metrics import mean_squared_error
7+
8+
# Fetch the Boston housing dataset from the original source
9+
data_url = "http://lib.stat.cmu.edu/datasets/boston"
10+
raw_df = pd.read_csv(data_url, sep=r"\s+", skiprows=22, header=None)
11+
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
12+
target = raw_df.values[1::2, 2]
13+
14+
# Split the dataset into training and testing sets
15+
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42)
16+
17+
# Create and train the linear regression model
18+
model = LinearRegression()
19+
model.fit(X_train, y_train)
20+
21+
# Make predictions on the training and testing sets
22+
y_train_pred = model.predict(X_train)
23+
y_test_pred = model.predict(X_test)
24+
25+
# Calculate the mean squared error for training and testing sets
26+
train_mse = mean_squared_error(y_train, y_train_pred)
27+
test_mse = mean_squared_error(y_test, y_test_pred)
28+
29+
print("Train MSE:", train_mse)
30+
print("Test MSE:", test_mse)
31+
32+
# Plot residuals
33+
plt.scatter(y_train_pred, y_train_pred - y_train, c='blue', marker='o', label='Training data')
34+
plt.scatter(y_test_pred, y_test_pred - y_test, c='green', marker='s', label='Test data')
35+
plt.xlabel('Predicted values')
36+
plt.ylabel('Residuals')
37+
plt.legend(loc='upper left')
38+
plt.hlines(y=0, xmin=min(y_train_pred.min(), y_test_pred.min()), xmax=max(y_train_pred.max(), y_test_pred.max()), color='red')
39+
plt.title('Residuals plot')
40+
plt.show()

‎TASK-12.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
from PIL import Image
2+
import os
3+
4+
def get_size_format(b, factor=1024, suffix="B"):
5+
"""
6+
Scale bytes to its proper byte format.
7+
e.g: 1253656 => '1.20MB', 1253656678 => '1.17GB'
8+
"""
9+
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
10+
if b < factor:
11+
return f"{b:.2f}{unit}{suffix}"
12+
b /= factor
13+
return f"{b:.2f}Y{suffix}"
14+
15+
def compress_img(image_name, new_size_ratio=0.9, quality=90, width=None, height=None, to_jpg=True):
16+
try:
17+
# Load the image into memory
18+
img = Image.open(image_name)
19+
20+
# Print the original image shape
21+
print("[*] Image shape:", img.size)
22+
23+
# Get the original image size in bytes
24+
image_size = os.path.getsize(image_name)
25+
print("[*] Size before compression:", get_size_format(image_size))
26+
27+
if width and height:
28+
# If width and height are set, resize with them instead
29+
img = img.resize((width, height), Image.LANCZOS)
30+
elif new_size_ratio < 1.0:
31+
# If resizing ratio is below 1.0, multiply width & height with this ratio to reduce image size
32+
img = img.resize((int(img.size[0] * new_size_ratio), int(img.size[1] * new_size_ratio)), Image.LANCZOS)
33+
34+
# Split the filename and extension
35+
filename, ext = os.path.splitext(image_name)
36+
37+
# Make a new filename appending "_compressed" to the original file name
38+
if to_jpg:
39+
# Change the extension to JPEG
40+
new_filename = f"{filename}_compressed.jpg"
41+
# Ensure image is in RGB mode for JPEG
42+
if img.mode in ("RGBA", "LA"):
43+
img = img.convert("RGB")
44+
else:
45+
# Retain the same extension of the original image
46+
new_filename = f"{filename}_compressed{ext}"
47+
48+
# Save the compressed image
49+
img.save(new_filename, optimize=True, quality=quality)
50+
51+
# Print the new image shape
52+
print("[+] New Image shape:", img.size)
53+
54+
# Get the new image size in bytes
55+
new_image_size = os.path.getsize(new_filename)
56+
print("[*] Size after compression:", get_size_format(new_image_size))
57+
print(f"[*] Compressed image saved as: {new_filename}")
58+
59+
except FileNotFoundError:
60+
print("Error: The file was not found.")
61+
except OSError as e:
62+
print(f"Error: {e}")
63+
64+
# Example usage:
65+
input_image = input("Enter the path to the image: ")
66+
compress_img(input_image, new_size_ratio=0.8, quality=80, width=800, height=600)

‎TASK-9.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from PIL import Image
2+
import os
3+
4+
def convert_image(input_path, output_path, output_format):
5+
try:
6+
# Open the image
7+
with Image.open(input_path) as img:
8+
# Check if the image has an alpha channel and convert it to RGB if necessary
9+
if output_format == 'JPEG' and img.mode == 'RGBA':
10+
img = img.convert('RGB')
11+
12+
# Convert and save the image to the desired format
13+
img.save(output_path, format=output_format)
14+
print(f"Image converted successfully to {output_format} format.")
15+
except Exception as e:
16+
print(f"An error occurred: {e}")
17+
18+
def main():
19+
input_path = input("Enter the path to the input image: ")
20+
output_format = input("Enter the desired output format (e.g., JPEG, PNG, BMP, GIF): ").upper()
21+
22+
# Validate output format
23+
if output_format not in ['JPEG', 'PNG', 'BMP', 'GIF']:
24+
print("Invalid output format. Please choose from JPEG, PNG, BMP, or GIF.")
25+
return
26+
27+
# Extract the file name and extension
28+
file_name, file_extension = os.path.splitext(input_path)
29+
30+
# Set the output path
31+
output_path = f"{file_name}_converted.{output_format.lower()}"
32+
33+
# Convert the image
34+
convert_image(input_path, output_path, output_format)
35+
36+
if __name__ == "__main__":
37+
main()

‎bhavya‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /