Aiml Lab
Aiml Lab
With formula
In [6]: from collections import Counter
In [4]: # Median
sorted_data = sorted(data)
n = len(data)
if n % 2 == 0:
median = (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2
else:
median = sorted_data[n // 2]
In [7]: # Mode
data_counts = Counter(data)
mode = data_counts.most_common(1)[0][0]
Data: [1, 2, 2, 3, 4, 4, 4, 5, 6]
In [10]: # Variance
mean_diff_squared = []
for x in data:
mean_diff_squared.append((x - mean) ** 2)
variance = sum(mean_diff_squared) / len(data)
Measures of Variability:
Range: 5
Variance: 2.246913580246914
Standard Deviation: 1.4989708403591158
Without Formula
In [15]: import numpy as np
from scipy import stats
In [18]: # Median
median = np.median(data)
In [24]: # Mode
mode = stats.mode(data)
Data: [1, 2, 2, 3, 4, 4, 4, 5, 6]
In [27]: # Variance
variance = np.var(data)
Measures of Variability:
Range: 5
Variance: 2.2469135802469133
Standard Deviation: 1.4989708403591155
In [ ]:
In [ ]:
for _ in range(iterations):
# Step 2: Assign points to the nearest centroid
distances = np.linalg.norm(X[:, np.newaxis] - centroids, axis=2)
labels = np.argmin(distances, axis=1)
# Step 3: Update centroids as the mean of assigned points
new_centroids = np.array([X[labels == i].mean(axis=0) for i in range(k)
# Break if centroids do not change
if np.all(centroids == new_centroids):
break
centroids = new_centroids
return centroids, labels
# Example usage
if __name__ == "__main__":
# Sample dataset
X = np.array([
[1, 2], [1, 4], [1, 0],
[10, 2], [10, 4], [10, 0]
])
# Apply K-Means
k = 2
centroids, labels = k_means(X, k)
# Plotting the clusters
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', s=100, label='Data
plt.scatter(centroids[:, 0], centroids[:, 1], color='red', marker='x', s=20
plt.title('K-Means Clustering')
plt.xlabel('X1')
plt.ylabel('X2')
plt.legend()
plt.grid(True)
plt.show()
print("Centroids:\n", centroids)
print("Labels:\n", labels)
Centroids:
[[5.5 1. ]
[5.5 4. ]]
Labels:
[0 1 0 0 1 0]
Centroids:
[[ 1. 2.]
[10. 2.]]
Labels:
[0 0 0 1 1 1]
In [ ]:
In [ ]:
In [ ]:
Training Predictions:
11.864
16.242
13.284
11.761
8.571
14.419
Testing Predictions:
8.938
20.888
22.780
7.513
Training Error (MSE): 0.515
Testing Error (MSE): 7.637
In [ ]:
1. Logical Operator
In [1]:
In [2]:
In [3]:
if x > 0 or y > 0:
print("The numbers are greater than 0")
In [4]:
# Logical not operator work with the single boolean value. If the boolean value is True i
x = 10
if not x:
print("Boolean value of a is True")
10 is divisible by either 3 or 5
In [6]:
si = (p * t * r)/100
# Driver code
P=int(input("Enter Principal Amount : "))
T=int(input("Enter Time period : "))
R=int(input("Enter Interest rate : "))
print('\n')
SI(P,T,R)
Out[6]:
16000.0
In [7]:
In [8]:
In [9]:
# checking condition
if num % 2 != 0:
print(num, end=" ")
In [10]:
s = "malayalam"
x = s[::-1] # Reverse of string (Spliting a string)
if s==x:
print("Yes ",s,' is Palindrom')
else:
print("No",s,' is not Palindrom')
In [11]:
In [12]:
# OR
x=10
y=20
x=x+y
y=x-y
x=x-y
print('x : ',x)
print('y : ',y)
num1 : 20
num2 : 10
x : 20
y : 10
In [13]:
# Fibonacci Series
n = int(input('Enter number : '))
num1 = 0
num2 = 1
print(num1)
print(num2)
next_number = num2
count = 1
Enter number : 10
0
1
1
2
3
5
8
13
21
34
55
89
In [ ]:
Out[5]: KNeighborsClassifier(n_neighbors=7)
[1 0 2 1 1 0 1 2 2 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0]
0.9666666666666667
plt.legend()
plt.xlabel('n_neighbors')
plt.ylabel('Accuracy')
plt.show()
In [ ]:
Code :
# Step 1: Generate some data points
x = [1, 2, 3, 4, 5] # Independent variable
y = [2, 4, 5, 4, 5] # Dependent variable
2. Gradient Descent
Steps:
Formula:
X* = X – learning-rate f’(x)
Gradient descent updates the parameters m and b by moving in the direction of the
negative gradient of the cost function. The updates for each iteration are given by:
Code :
import numpy as np
3. Logistic Regression
Logistic regression is used for binary classification problems where the output is
categorical (usually 0 or 1). Instead of modeling the output directly, logistic
regression models the probability that the output belongs to a particular class using
the logistic function:
Code :
import math
def sigmoid(z):
return 1 / (1 + math.exp(-z))
learning_rate = 0.01
num_iterations = 1000
for _ in range(num_iterations):
b -= learning_rate * b_grad
Output :
Optimized Slope (m): 1.2693567720287338
Optimized Intercept (b): -4.177149454816769
Predicted class probabilities: [0.05176968460638721, 0.16267800083744785, 0.40
876355284120997, 0.7110065530114915, 0.8974893359190727]
Predicted classes: [0, 0, 0, 1, 1]
08/09/2023, 15:54 Week 1 & 2 - Jupyter Notebook
print("Hello World!")
Hello World!
In [2]:
x='Hello World!'
print(x)
Hello World!
In [3]:
In [5]:
import datetime
In [6]:
import datetime
# for timezone()
import pytz
# using now() to get current time. To get the date and time for a particular timezone now
# takes timezone as input to give timezone-oriented output time.
current_time = datetime.datetime.now(pytz.timezone('Asia/Kolkata'))
In [7]:
print("UTC Time: ", datetime.utcnow()) # UTC Stands for Coordinated Universal Time,
# These times are useful when you are dealing with Applications that have a global user f
In [8]:
x = dt.now().isoformat() #isoformat() method is used to get the current date and time in
#It starts with the year, followed by the month, the day, the hour, the minutes, seco
print('Current ISO:', x)
In [9]:
# Here, we are getting the current time using the time module.
import time
In [10]:
import time
nano_seconds = time.time_ns()
In [11]:
import time
# current GMT Time Green Mean Time, which is also known as GMT can be used by using time.
# just need to pass the time in seconds to this method to get the GMT
gmt_time = time.gmtime(time.time())
In [12]:
import time
print("Epoch Time is : ", int(time.time())) #We can get the Epoch current time by convert
num1=100
num2=50
sum=num1+num2
print("Addition of two no. : ",sum)
In [14]:
In [15]:
sum=0
num=int(input("Enter the NUmber : "))
for i in range(num+1):
sum+=i
print("Addition of given Number : ", sum)
In [16]:
# Importing numpy
import numpy as np
The matrix is :
[[1 2 3]
[4 5 6]
[7 8 9]]
int32
In [17]:
The matrix is :
[['100' 'Itika' '89']
['Aditi' '96' '82']
['Harry' '91' '81']
['Andrew' '87' '91']
['Peter' '72' '79']]
<U11
In [18]:
# Python program to show how to create a matrix using the matrix method
# importing numpy
import numpy as np
# Creating a matrix
matrix = np.matrix('3,4,5;5,6,7;8,9,10')
print(matrix)
[[ 3 4 5]
[ 5 6 7]
[ 8 9 10]]
In [19]:
# initializing matrices
x = numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
In [21]:
student = {
"RollNo" : 1232,
"Name" : 'XYZ',
"maths Mark" : 65,
"physics Mark" : 55,
"chemistry Mark" : 87
}
print("Print Student Details : ",student)
print("Student Details are : ")
for x,y in student.items():
print(x,' : ',y)
Print Student Details : {'RollNo': 1232, 'Name': 'XYZ', 'maths Mark': 65,
'physics Mark': 55, 'chemistry Mark': 87}
Student Details are :
RollNo : 1232
Name : XYZ
maths Mark : 65
physics Mark : 55
chemistry Mark : 87
In [22]:
# Tuples are used to store multiple items in a single variable. A tuple is a collection w
In [23]:
for i in thistuple:
print(i)
In [24]:
# Lists are used to store multiple items in a single variable. List items are ordered, ch
In [25]: