diff --git a/Mallela.Bhavya b/Mallela.Bhavya new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Mallela.Bhavya @@ -0,0 +1 @@ + diff --git a/Mallela_Bhavya/Task10/TASK-10.py b/Mallela_Bhavya/Task10/TASK-10.py new file mode 100644 index 0000000..2fee7c7 --- /dev/null +++ b/Mallela_Bhavya/Task10/TASK-10.py @@ -0,0 +1,43 @@ +import seaborn as sns +import pandas as pd +import matplotlib.pyplot as plt + +# Load the Iris dataset from Seaborn +iris = sns.load_dataset("iris") +numeric_iris = iris.drop(columns='species') + +# Display the first few rows of the dataset +print("First few rows of the dataset:") +print(iris.head()) + +# Summary statistics +print("\nSummary statistics:") +print(iris.describe()) + +# Checking for missing values +print("\nMissing values:") +print(iris.isnull().sum()) + +# Visualizations +# Pairplot +sns.pairplot(iris, hue="species") +plt.title("Pairplot of Iris Dataset") +plt.show() + +# Boxplot +plt.figure(figsize=(10, 6)) +sns.boxplot(data=iris, orient="h") +plt.title("Boxplot of Iris Dataset") +plt.show() + +# Histograms +plt.figure(figsize=(10, 6)) +iris.hist() +plt.suptitle("Histograms of Iris Dataset") +plt.show() + +# Correlation heatmap +plt.figure(figsize=(8, 6)) +sns.heatmap(numeric_iris.corr(), annot=True, cmap="coolwarm") +plt.title("Correlation Heatmap of Iris Dataset") +plt.show() diff --git a/Mallela_Bhavya/Task11/TASK-11.py b/Mallela_Bhavya/Task11/TASK-11.py new file mode 100644 index 0000000..85bc4e1 --- /dev/null +++ b/Mallela_Bhavya/Task11/TASK-11.py @@ -0,0 +1,40 @@ +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +from sklearn.linear_model import LinearRegression +from sklearn.metrics import mean_squared_error + +# Fetch the Boston housing dataset from the original source +data_url = "http://lib.stat.cmu.edu/datasets/boston" +raw_df = pd.read_csv(data_url, sep=r"\s+", skiprows=22, header=None) +data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]]) +target = raw_df.values[1::2, 2] + +# Split the dataset into training and testing sets +X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42) + +# Create and train the linear regression model +model = LinearRegression() +model.fit(X_train, y_train) + +# Make predictions on the training and testing sets +y_train_pred = model.predict(X_train) +y_test_pred = model.predict(X_test) + +# Calculate the mean squared error for training and testing sets +train_mse = mean_squared_error(y_train, y_train_pred) +test_mse = mean_squared_error(y_test, y_test_pred) + +print("Train MSE:", train_mse) +print("Test MSE:", test_mse) + +# Plot residuals +plt.scatter(y_train_pred, y_train_pred - y_train, c='blue', marker='o', label='Training data') +plt.scatter(y_test_pred, y_test_pred - y_test, c='green', marker='s', label='Test data') +plt.xlabel('Predicted values') +plt.ylabel('Residuals') +plt.legend(loc='upper left') +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') +plt.title('Residuals plot') +plt.show() diff --git a/Mallela_Bhavya/Task12/TASK-12.py b/Mallela_Bhavya/Task12/TASK-12.py new file mode 100644 index 0000000..98c044f --- /dev/null +++ b/Mallela_Bhavya/Task12/TASK-12.py @@ -0,0 +1,66 @@ +from PIL import Image +import os + +def get_size_format(b, factor=1024, suffix="B"): + """ + Scale bytes to its proper byte format. + e.g: 1253656 => '1.20MB', 1253656678 => '1.17GB' + """ + for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: + if b < factor: + return f"{b:.2f}{unit}{suffix}" + b /= factor + return f"{b:.2f}Y{suffix}" + +def compress_img(image_name, new_size_ratio=0.9, quality=90, width=None, height=None, to_jpg=True): + try: + # Load the image into memory + img = Image.open(image_name) + + # Print the original image shape + print("[*] Image shape:", img.size) + + # Get the original image size in bytes + image_size = os.path.getsize(image_name) + print("[*] Size before compression:", get_size_format(image_size)) + + if width and height: + # If width and height are set, resize with them instead + img = img.resize((width, height), Image.LANCZOS) + elif new_size_ratio < 1.0: + # If resizing ratio is below 1.0, multiply width & height with this ratio to reduce image size + img = img.resize((int(img.size[0] * new_size_ratio), int(img.size[1] * new_size_ratio)), Image.LANCZOS) + + # Split the filename and extension + filename, ext = os.path.splitext(image_name) + + # Make a new filename appending "_compressed" to the original file name + if to_jpg: + # Change the extension to JPEG + new_filename = f"{filename}_compressed.jpg" + # Ensure image is in RGB mode for JPEG + if img.mode in ("RGBA", "LA"): + img = img.convert("RGB") + else: + # Retain the same extension of the original image + new_filename = f"{filename}_compressed{ext}" + + # Save the compressed image + img.save(new_filename, optimize=True, quality=quality) + + # Print the new image shape + print("[+] New Image shape:", img.size) + + # Get the new image size in bytes + new_image_size = os.path.getsize(new_filename) + print("[*] Size after compression:", get_size_format(new_image_size)) + print(f"[*] Compressed image saved as: {new_filename}") + + except FileNotFoundError: + print("Error: The file was not found.") + except OSError as e: + print(f"Error: {e}") + +# Example usage: +input_image = input("Enter the path to the image: ") +compress_img(input_image, new_size_ratio=0.8, quality=80, width=800, height=600) diff --git a/Mallela_Bhavya/Task9/TASK-9.py b/Mallela_Bhavya/Task9/TASK-9.py new file mode 100644 index 0000000..fcd4fc3 --- /dev/null +++ b/Mallela_Bhavya/Task9/TASK-9.py @@ -0,0 +1,37 @@ +from PIL import Image +import os + +def convert_image(input_path, output_path, output_format): + try: + # Open the image + with Image.open(input_path) as img: + # Check if the image has an alpha channel and convert it to RGB if necessary + if output_format == 'JPEG' and img.mode == 'RGBA': + img = img.convert('RGB') + + # Convert and save the image to the desired format + img.save(output_path, format=output_format) + print(f"Image converted successfully to {output_format} format.") + except Exception as e: + print(f"An error occurred: {e}") + +def main(): + input_path = input("Enter the path to the input image: ") + output_format = input("Enter the desired output format (e.g., JPEG, PNG, BMP, GIF): ").upper() + + # Validate output format + if output_format not in ['JPEG', 'PNG', 'BMP', 'GIF']: + print("Invalid output format. Please choose from JPEG, PNG, BMP, or GIF.") + return + + # Extract the file name and extension + file_name, file_extension = os.path.splitext(input_path) + + # Set the output path + output_path = f"{file_name}_converted.{output_format.lower()}" + + # Convert the image + convert_image(input_path, output_path, output_format) + +if __name__ == "__main__": + main() diff --git a/TASK-10.py b/TASK-10.py new file mode 100644 index 0000000..365c14e --- /dev/null +++ b/TASK-10.py @@ -0,0 +1,43 @@ +import seaborn as sns +import pandas as pd +import matplotlib.pyplot as plt + +# Load the Iris dataset from Seaborn +iris = sns.load_dataset("iris") +numeric_iris = iris.drop(columns='species') + +# Display the first few rows of the dataset +print("First few rows of the dataset:") +print(iris.head()) + +# Summary statistics +print("\nSummary statistics:") +print(iris.describe()) + +# Checking for missing values +print("\nMissing values:") +print(iris.isnull().sum()) + +# Visualizations +# Pairplot +sns.pairplot(iris, hue="species") +plt.title("Pairplot of Iris Dataset") +plt.show() + +# Boxplot +plt.figure(figsize=(10, 6)) +sns.boxplot(data=iris, orient="h") +plt.title("Boxplot of Iris Dataset") +plt.show() + +# Histograms +plt.figure(figsize=(10, 6)) +iris.hist() +plt.suptitle("Histograms of Iris Dataset") +plt.show() + +# Correlation heatmap +plt.figure(figsize=(8, 6)) +sns.heatmap(numeric_iris.corr(), annot=True, cmap="coolwarm") +plt.title("Correlation Heatmap of Iris Dataset") +plt.show() diff --git a/TASK-11.py b/TASK-11.py new file mode 100644 index 0000000..195849c --- /dev/null +++ b/TASK-11.py @@ -0,0 +1,40 @@ +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +from sklearn.linear_model import LinearRegression +from sklearn.metrics import mean_squared_error + +# Fetch the Boston housing dataset from the original source +data_url = "http://lib.stat.cmu.edu/datasets/boston" +raw_df = pd.read_csv(data_url, sep=r"\s+", skiprows=22, header=None) +data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]]) +target = raw_df.values[1::2, 2] + +# Split the dataset into training and testing sets +X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42) + +# Create and train the linear regression model +model = LinearRegression() +model.fit(X_train, y_train) + +# Make predictions on the training and testing sets +y_train_pred = model.predict(X_train) +y_test_pred = model.predict(X_test) + +# Calculate the mean squared error for training and testing sets +train_mse = mean_squared_error(y_train, y_train_pred) +test_mse = mean_squared_error(y_test, y_test_pred) + +print("Train MSE:", train_mse) +print("Test MSE:", test_mse) + +# Plot residuals +plt.scatter(y_train_pred, y_train_pred - y_train, c='blue', marker='o', label='Training data') +plt.scatter(y_test_pred, y_test_pred - y_test, c='green', marker='s', label='Test data') +plt.xlabel('Predicted values') +plt.ylabel('Residuals') +plt.legend(loc='upper left') +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') +plt.title('Residuals plot') +plt.show() diff --git a/TASK-12.py b/TASK-12.py new file mode 100644 index 0000000..72eed63 --- /dev/null +++ b/TASK-12.py @@ -0,0 +1,66 @@ +from PIL import Image +import os + +def get_size_format(b, factor=1024, suffix="B"): + """ + Scale bytes to its proper byte format. + e.g: 1253656 => '1.20MB', 1253656678 => '1.17GB' + """ + for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: + if b < factor: + return f"{b:.2f}{unit}{suffix}" + b /= factor + return f"{b:.2f}Y{suffix}" + +def compress_img(image_name, new_size_ratio=0.9, quality=90, width=None, height=None, to_jpg=True): + try: + # Load the image into memory + img = Image.open(image_name) + + # Print the original image shape + print("[*] Image shape:", img.size) + + # Get the original image size in bytes + image_size = os.path.getsize(image_name) + print("[*] Size before compression:", get_size_format(image_size)) + + if width and height: + # If width and height are set, resize with them instead + img = img.resize((width, height), Image.LANCZOS) + elif new_size_ratio < 1.0: + # If resizing ratio is below 1.0, multiply width & height with this ratio to reduce image size + img = img.resize((int(img.size[0] * new_size_ratio), int(img.size[1] * new_size_ratio)), Image.LANCZOS) + + # Split the filename and extension + filename, ext = os.path.splitext(image_name) + + # Make a new filename appending "_compressed" to the original file name + if to_jpg: + # Change the extension to JPEG + new_filename = f"{filename}_compressed.jpg" + # Ensure image is in RGB mode for JPEG + if img.mode in ("RGBA", "LA"): + img = img.convert("RGB") + else: + # Retain the same extension of the original image + new_filename = f"{filename}_compressed{ext}" + + # Save the compressed image + img.save(new_filename, optimize=True, quality=quality) + + # Print the new image shape + print("[+] New Image shape:", img.size) + + # Get the new image size in bytes + new_image_size = os.path.getsize(new_filename) + print("[*] Size after compression:", get_size_format(new_image_size)) + print(f"[*] Compressed image saved as: {new_filename}") + + except FileNotFoundError: + print("Error: The file was not found.") + except OSError as e: + print(f"Error: {e}") + +# Example usage: +input_image = input("Enter the path to the image: ") +compress_img(input_image, new_size_ratio=0.8, quality=80, width=800, height=600) diff --git a/TASK-9.py b/TASK-9.py new file mode 100644 index 0000000..4ae7d87 --- /dev/null +++ b/TASK-9.py @@ -0,0 +1,37 @@ +from PIL import Image +import os + +def convert_image(input_path, output_path, output_format): + try: + # Open the image + with Image.open(input_path) as img: + # Check if the image has an alpha channel and convert it to RGB if necessary + if output_format == 'JPEG' and img.mode == 'RGBA': + img = img.convert('RGB') + + # Convert and save the image to the desired format + img.save(output_path, format=output_format) + print(f"Image converted successfully to {output_format} format.") + except Exception as e: + print(f"An error occurred: {e}") + +def main(): + input_path = input("Enter the path to the input image: ") + output_format = input("Enter the desired output format (e.g., JPEG, PNG, BMP, GIF): ").upper() + + # Validate output format + if output_format not in ['JPEG', 'PNG', 'BMP', 'GIF']: + print("Invalid output format. Please choose from JPEG, PNG, BMP, or GIF.") + return + + # Extract the file name and extension + file_name, file_extension = os.path.splitext(input_path) + + # Set the output path + output_path = f"{file_name}_converted.{output_format.lower()}" + + # Convert the image + convert_image(input_path, output_path, output_format) + +if __name__ == "__main__": + main() diff --git a/bhavya b/bhavya new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bhavya @@ -0,0 +1 @@ +