Machine
Machine
3. Create, initialize and display simple variables and simple strings and use
9: Generate different subplots from a given plot and color plot data.
10: Use conditional statements and different type of loops based on simple
example/s.
16: Use some function for neural networks, like Stochastic Gradient Descent
or backpropagation - algorithm to predict the value of a variable based on
the dataset of problem 14.
1: Perform elementary mathematical operations in
Octave/MATLAB/Python like addition, multiplication, division and
exponentiation.
# Addition
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
sum = a + b
print("Sum:", sum)
# Multiplication
product = a * b
print("Product:", product)
# Division
division = a / b
print("Division:", division)
# Exponentiation
exponent = a ** b
print("Exponentiation:", exponent)
OUTPUT:
2: Perform elementary logical operations in Python (like OR, AND,
# OR operation
x = input("Enter the value of x (True or False): ").lower() == 'true'
y = input("Enter the value of y (True or False): ").lower() == 'true'
result_or = x or y
print("OR:", result_or)
# AND operation
result_and = x and y
print("AND:", result_and)
# NOT operation
result_not_x = not x
print("NOT x:", result_not_x)
# XOR operation
result_xor = x ^ y
print("XOR:", result_xor)
OUTPUT:
3. Create, initialize and display simple variables and simple strings and use
# Display variables
print("Name:", name)
print("Age:", age)
print("Place of Birth:", place_of_birth)
import numpy as np
print(single_array)
# Multi-dimension array
print("\nMulti-Dimension Array:")
print(multi_array)
print(ones_array)
print(zeros_array)
print(random_array)
# Diagonal matrix
print("\nDiagonal Matrix:")
print(diagonal_matrix)
OUTPUT:
5: Use command to compute the size of a matrix, size/length of a
particular row/column, load data from a text file, store matrix
data to a text file, finding out variables and their features in the
current scope.
import numpy as np
matrix_size = matrix.shape
np.savetxt("matrix_data.txt", matrix)
print(matrix)
data_from_file = np.loadtxt("matrix_data.txt")
print(data_from_file)
# Finding out variables and their features in the current scope
current_scope_variables = dir()
print(var)
OUTPUT
import numpy as np
# Addition of matrices
print("Matrix Addition:")
print(matrix_addition)
# Subtraction of matrices
print("\nMatrix Subtraction:")
print(matrix_subtraction)
print(matrix_multiplication_elementwise)
print(matrix_multiplication_dot)
# Display specific rows or columns of the matrix
import numpy as np
# Create a matrix for demonstration
matrix = np.array([[10, -20, 30], [-40, 50, -60], [70, -80, 90]])
abs_matrix = np.abs(matrix)
print(abs_matrix)
neg_matrix = -matrix
print(neg_matrix)
print(matrix_with_new_row)
print(matrix_with_new_col)
print(matrix_without_col)
max_value = np.max(matrix)
min_value = np.min(matrix)
sum_matrix = np.sum(matrix)
# Plot a histogram
plt.figure(figsize=(8, 6))
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.grid(True)
plt.show()
y1 = np.sin(x)
y2 = np.cos(x)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.legend()
plt.grid(True)
plt.show()
9: Generate different subplots from a given plot and color plot
data.
import numpy as np
y1 = np.sin(x)
y2 = np.cos(x)
axs[0, 0].set_xlabel('x-axis')
axs[0, 0].set_ylabel('y-axis')
axs[0, 1].set_xlabel('x-axis')
axs[0, 1].set_ylabel('y-axis')
axs[1, 0].set_xlabel('Value')
axs[1, 0].set_ylabel('Frequency')
axs[1, 1].set_xlabel('x-axis')
axs[1, 1].set_ylabel('y-axis')
plt.tight_layout()
plt.show()
if num > 0:
else:
print(i)
i = 1
while i <= 5:
print(i)
i += 1
# Example 4: Looping through a list with conditional statements
if num % 2 == 0:
print(num)
# Define the number for which you want to print the multiplication table
number = 5
if number > 0:
i = 1
i += 1
else:
import numpy as np
transpose_matrix1 = np.transpose(matrix1)
print("Transpose of matrix1:")
print(transpose_matrix1)
print(addition_result)
print(subtraction_result)
print(multiplication_result)
12: Implement Linear Regression Problem.
Using the given dataset, implement least-squares
approximation in Python. The first column is the input
feature(x) and second column is the response variable(y).
Also, make a prediction for x=15.67
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# Example dataset: Area of houses (in square meters) and their corresponding
prices (in thousands of dollars)
areas = np.array([60, 80, 100, 120, 150]).reshape(-1, 1) # Reshape to make it
a 2D array
prices = np.array([200, 250, 300, 350, 400])
Output:
Predicted price of a house with an area of 90 sqm: 275.0
import numpy as np
model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Coefficients:", model.coef_)
print("Intercept:", model.intercept_)
predicted_price = model.predict(new_house_features)
OUTPUT:
Intercept: 60.0
Predicted price of the new house: 370.0
# Calculate accuracy
accuracy = accuracy_score(y_test, predictions)
print("Accuracy:", accuracy)
OUTPUT:
Accuracy: 1.0
15. Use some function for regularization of dataset based on
problem 14
import numpy as np
# Load the dataset (replace this with your dataset loading code)
# For example, you can load a dataset containing email features and labels
(spam or not spam)
# X, y = load_email_dataset()
iris = load_iris()
X = iris.data
model.fit(X_train, y_train)
predictions = model.predict(X_test)
# Calculate accuracy
print("Accuracy:", accuracy)
cm = confusion_matrix(y_test, predictions)
plt.colorbar()
plt.title('Confusion Matrix')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
16: Use some function for neural networks, like Stochastic
Gradient Descent or backpropagation - algorithm to predict
the value of a variable based on the dataset of problem 14.
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix
# Load the dataset (replace this with your dataset loading code)
# For example, you can load a dataset containing email features and labels (spam or
not spam)
# X, y = load_email_dataset()
# Make predictions
predictions = model.predict(X_test)
predicted_classes = np.argmax(predictions, axis=1)
# Calculate accuracy
accuracy = accuracy_score(y_test, predicted_classes)
print("Accuracy:", accuracy)