<jupyter_start><jupyter_text>Practical 1 Perform elementary mathematical operations in Octave/MATLAB/R like addition, multiplication, division and exponentiation.<jupyter_code>A = 2
B = 2
A + B
A - B
A * B
A / B
A ** B<jupyter_output><empty_output><jupyter_text>Practical 2 Perform elementary logical operations in Octave/MATLAB/R (like OR, AND, Checking for Equality, NOT, XOR).<jupyter_code>True or False
True and False
1 == 2
not(True)
True ^ False
False ^ False<jupyter_output><empty_output><jupyter_text>Practical 3 Create, initialize and display simple variables and simple strings and use simple formatting for variable.<jupyter_code>str1 = 'This is python.'
str2 = 'This is colab.'
print('Python: {}'.format(str1))
print('Notebook: {}'.format(str2))<jupyter_output>Python: This is python.
Notebook: This is colab.<jupyter_text>Practical 4 Create/Define single dimension / multi-dimension arrays, and arrays with specific values like array of all ones, all zeros, array with random values within a range, or a diagonal matrix.<jupyter_code>np.ones(4, int)
np.ones((4, 4), int)
np.zeros(4, int)
np.zeros((4, 4), int)
np.random.default_rng(12345).integers(low=0, high=10, size=4).reshape(4)
np.random.default_rng(12345).integers(low=0, high=10, size=16).reshape(4, 4)
from scipy.linalg import block_diag
block_diag(1, 2, 3, 4)<jupyter_output><empty_output><jupyter_text>Practical 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.<jupyter_code>A = np.matrix([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]).reshape(4, 4)
A
A.size
A.shape
np.savetxt('matrix.txt', A, delimiter = ',')
np.loadtxt(open("matrix.txt", "rb"), delimiter=",", skiprows=0)
print(dir())
print(dir(A))<jupyter_output>['A', 'A1', 'H', 'I', 'T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_function__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_ufunc__', '__array_wrap__', '__bool__', '__class__', '__complex__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__lshift__', '__lt__', '__matmul__', '__mod__', '__module__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_[...]<jupyter_text>Practical 6 Perform basic operations on matrices (like addition, subtraction, multiplication) and display specific rows or columns of the matrix.<jupyter_code>import numpy as np
A = np.array([1, 2, 3, 4]).reshape(2, 2)
A
B = (A.reshape(1,-1)[0][::-1]).reshape(2,2)
B
A + B
A - B
A * B<jupyter_output><empty_output><jupyter_text>Practical 7 Perform other matrix operations like converting matrix data to absolute values, taking the negative of matrix values, editing/removing rows/columns from a matrix, finding the maximum or minimum values in a matrix or in a row/column, and finding the sum of some/all elements in a matrix.<jupyter_code>import numpy as np
A = np.matrix( [[1, -2, 3, 4],
                [1, 2, -3, 4],
                [-1, -2, 3, 4],
                [1, 2, 3, -4]] ).reshape(4, 4)
A
absolute_A = np.absolute(A)
absolute_A
negative_A = np.negative(A)
negative_A
added_row = np.append(A, [[4, 3, 2, 1]], axis=0)
added_row
deleted_row = np.delete(added_row, 4, axis=0)
deleted_row
added_column = np.insert(A, 4, 5, axis=1)
added_column
deleted_column = np.delete(added_column, 4, axis=1)
deleted_column
matrix_max = np.max(A)
matrix_max
matrix_min = np.min(A)
matrix_min
row_max = np.max(A, axis=0)
row_max
column_max = np.max(A, axis=1)
column_max
matrix_sum = np.sum(A)
matrix_sum
row_sum = np.sum(A, axis=0)
row_sum
column_sum = np.sum(A, axis=1)
column_sum<jupyter_output><empty_output><jupyter_text>Practical 8 Create various types of plots/charts like histograms, and plots based on sine/cosine function based on data from a matrix. Further label different axes in a plot and data in a plot.<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb

%matplotlib inline
pokemon = pd.read_csv('https://raw.githubusercontent.com/jarvis-1805/Python-for-Data-Science-/master/Day%2011/pokemon.csv')
print(pokemon.shape)
pokemon.head()
# BAR Chart
sb.countplot(data = pokemon, x = 'generation_id')
plt.title('Bar Chart')
# Histogram
plt.style.use('ggplot')
plt.hist(data = pokemon, align='mid', x = 'speed', edgecolor='black', linewidth=1.2)
plt.xlabel('Speed')
plt.ylabel('Count')
plt.title('Histogram')
# PIE Chart
sorted_counts = pokemon['generation_id'].value_counts()
plt.pie(sorted_counts, labels = sorted_counts.index, startangle = 90, counterclock = False)
plt.axis('square')
plt.title('Generation ID')
x = pokemon['weight'][:50]
y = pokemon['height'][:50]

plt.scatter(x, y)
plt.ylabel('height')
plt.xlabel('weight')
plt.title('Scatter Plot')
plt.show()
x = np.arange(0, 4*np.pi, 0.1)   # start,stop,step
y = np.sin(x)
plt.plot(x, y)
plt.title('sin(x)')
plt.ylabel('Value')
plt.xlabel('Degree')
plt.show()
x = np.arange(0, 4*np.pi, 0.1)   # start,stop,step
y = np.cos(x)
plt.plot(x, y)
plt.title('cos(x)')
plt.ylabel('Value')
plt.xlabel('Degree')
plt.show()<jupyter_output><empty_output><jupyter_text>Practical 9 Generate different subplots from a given plot and color plot data.<jupyter_code>import matplotlib.pyplot as plt

%matplotlib inline

fig = plt.figure()
x = pokemon['generation_id']

plt.subplot(2, 2, 1)
y = pokemon['attack']
plt.plot(x, y)

plt.subplot(2, 2, 2)
y = pokemon['defense']
plt.plot(x, y)

plt.subplot(2, 2, 3)
y = pokemon['special-attack']
plt.plot(x, y)

plt.subplot(2, 2, 4)
y = pokemon['special-defense']
plt.plot(x, y)

plt.show()<jupyter_output><empty_output><jupyter_text>Practical 10 Use conditional statements and different type of loops based on simple example/s.<jupyter_code>a, b, c = 3, 5, 1

if a < b and a < c :
  print('a has the smallest value :', a)
elif b < a and b < c :
  print('b has the smallest value :', b)
else :
  print('c has the smallest value :', c)
for i in range(5) :
  print(i)
i = 0
while i != 5 :
  print(i)
  i += 1<jupyter_output>0
1
2
3
4<jupyter_text>Practical 11 Perform vectorized implementation of simple matrix operation like finding the transpose of a matrix, adding, subtracting or multiplying two matrices.<jupyter_code>mat_A = np.array([1, 2, 3, 4]).reshape(2, 2)
mat_A
mat_B = (mat_A.reshape(1,-1)[0][::-1]).reshape(2,2)
mat_B
np.add(mat_A, mat_B)
np.subtract(mat_A, mat_B)
np.multiply(mat_A, mat_B)
np.divide(mat_A, mat_B)
np.power(mat_A, mat_B)
np.transpose(mat_A)
np.transpose(mat_B)<jupyter_output><empty_output><jupyter_text>Practical 12 Implement Linear Regression problem. For example, based on a dataset comprising of existing set of prices and area/size of the houses, predict the estimated price of a given house.<jupyter_code>import pandas as pd
import numpy as np
from sklearn import linear_model
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style='darkgrid')
df = pd.read_csv('https://raw.githubusercontent.com/codebasics/py/master/ML/1_linear_reg/homeprices.csv')
df
%matplotlib inline
plt.xlabel('area')
plt.ylabel('price')
plt.scatter(df.area, df.price, color='red', marker='+')
new_df = df.drop('price', axis='columns')
new_df
price = df.price
price
# Creating linear regression object
reg = linear_model.LinearRegression()
reg.fit(new_df.values, price.values)
# Predict price of a home with area = 3300 sq. ft.
reg.predict([[3300]])
# value for m (slope)
reg.coef_
# value for y intercept
reg.intercept_
# Y = m * X + b (m is coefficient and b is intercept)
3300*135.78767123 + 180616.43835616432
# Predict price of a home with area = 5000 sqr ft
reg.predict([[5000]])
# List of home price predictions
area_df = pd.read_csv('https://raw.githubusercontent.com/codebasics/py/master/ML/1_linear_reg/areas.csv')
area_df.head(3)
p = reg.predict(area_df.values)
p
area_df['prices'] = p
area_df<jupyter_output><empty_output><jupyter_text>Practical 13 Based on multiple features/variables perform Linear Regression.<jupyter_code>import pandas as pd
import numpy as np
from word2number import w2n
dataset = pd.read_csv("https://raw.githubusercontent.com/codebasics/py/master/ML/2_linear_reg_multivariate/Exercise/hiring.csv")
dataset
dataset.info()
dataset.experience = dataset.experience.fillna("zero")
dataset
dataset.experience = dataset.experience.apply(w2n.word_to_num)
dataset
import math
median_test_score = math.floor(dataset['test_score(out of 10)'].mean())
median_test_score
dataset['test_score(out of 10)'] = dataset['test_score(out of 10)'].fillna(median_test_score)
dataset
# Model Building
from sklearn import linear_model
model = linear_model.LinearRegression()
model.fit(dataset[['experience','test_score(out of 10)','interview_score(out of 10)']].values, dataset['salary($)'].values)
model.coef_, model.intercept_
# Prediction

# 2 yr experience, 9 test score, 6 interview score
model.predict([[2, 9, 6]])
# 12 yr experience, 10 test score, 10 interview score
model.predict([[12, 10, 10]])<jupyter_output><empty_output><jupyter_text>Practical 14 Implement a classification/ logistic regression problem.<jupyter_code>import numpy as np
from sklearn.datasets import load_digits
import matplotlib.pyplot as plt
import seaborn as sb

%matplotlib inline
digits = load_digits()
dir(digits)
digits.data
digits.target
plt.figure(figsize=(10, 4))
plt.gray()
label = digits.target[:5]
for i in range(0, 5):
  plt.subplot(1, 5, i+1)
  plt.imshow(digits.images[i])
  plt.title(f'Label:{label[i]}\n')
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
model = LogisticRegression(max_iter=1e9)
X_train, X_test, Y_train, Y_test = train_test_split(digits.data, digits.target, test_size=0.2)
model.fit(X_train, Y_train)
plt.figure(figsize=(15, 4))
plt.gray()
label = Y_test[:5]
image = X_test[:5]
for i in range(0, 5):
  plt.subplot(1, 5, i+1)
  plt.imshow(np.reshape(image[i], (8,8)))
  plt.title(f'Label:{label[i]}\n')
model.score(X_test, Y_test)
model.predict(X_test[0:5])
y_predict = model.predict(X_test)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(Y_test, y_predict)
plt.figure(figsize=(9, 9))
sb.heatmap(cm, annot=True, square=True, fmt='.2f')
plt.show()<jupyter_output><empty_output><jupyter_text>Practical 15 Use some function for regularization of dataset based on problem 14.<jupyter_code>model.score(X_test, Y_test)
model.score(X_train, Y_train)
# Using Ridge (L2 Regularized) Regression Model
from sklearn.linear_model import RidgeClassifier
ridge_reg = RidgeClassifier(alpha=0.1)
ridge_reg.fit(X_train, Y_train)
ridge_reg.score(X_test, Y_test)
ridge_reg.score(X_train, Y_train)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14355512125788397, 'fraction_numerical': 0.027094252465132806, 'mean_word_length': 6.107323232323233, 'pattern_counts': {'":': 0, '<': 62, '<?xml version=': 0, '>': 58, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '479347', 'license': 'MIT', 'n_tokens_mistral': 4465, 'n_tokens_neox': 4172, 'n_words': 1080, 'path': 'YearIII/SemesterVI/MachineLearning/Practicals/ML_Practicals.ipynb', 'repo_name': 'jarvis-1805/myappsample', 'size': '11257'}