Week6_Bai
Week6_Bai
Week 6 Assignment
Baidehi Basnet
December 2, 2024
Classification
display(iris_df.head())
X = iris_df[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)'
y = iris_df['species'] # Target (species: 0=setosa, 1=versicolor, 2=virginica)
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) species
Out[18]: ▾ GaussianNB i ?
GaussianNB()
Make Prediction
In [19]: # Make prediction
y_pred = gnb.predict(X_test)
Accuracy: 1.0
Classification Report:
accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30
Clustering
Clustering is the process of arranging a group of objects in such a manner that the
objects in the same group (which is referred as a cluster) are more similar to each other
than to the objects in any other group
Initialize Cluster Centers: Randomly select k points from the data as initial cluster centers
(also called centroids).
Assign Data Points to Clusters: Each data point is assigned to the cluster whose centroid
is closest (measured by distance, usually Euclidean).
Update Centroids: For each cluster, compute the new centroid as the average of all
points assigned to that cluster.
Repeat: Reassign points to clusters based on the updated centroids and recompute the
centroids. This process is repeated until the centroids stop changing significantly or a
maximum number of iterations is reached.
Finally The algorithm returns the final clusters and their centroids, after n number of
iteration (max_iter)
plt.figure(figsize=(10,5))
sns.scatterplot(data = home_data, x = 'longitude', y = 'latitude', hue = 'median_ho
plt.show()
X_train_norm = preprocessing.normalize(X_train)
X_test_norm = preprocessing.normalize(X_test)
Fit the data to the K-Means Model and plot the clusters into
scattered Plot
In [24]: from sklearn.cluster import KMeans
plt.figure(figsize=(10,5))
sns.scatterplot(data = X_train, x = 'longitude', y = 'latitude', hue = Kmeans.label
plt.show()
0.7499371920703546
Deep Learning
Deep learning is basically repeting the process until the output value reaches close to
your actual number.
Deep Learning
In [26]: import numpy as np
import matplotlib.pyplot as plt
class Neuralnetwork:
def __init__(self, input_neurons, hidden_neurons, output_neurons, learning_rate
# initialize network parameters
self.input_neurons = input_neurons
self.hidden_neurons = hidden_neurons
self.output_neurons = output_neurons
self.learning_rate = learning_rate
return self.output
def compute_loss(self, y_pred, y_true):
return np.mean ((y_pred - y_true) ** 2)
error_hidden = d_output.dot(self.w2.T)
d_hidden = error_hidden *self.sigmoid_derivative(self.a1)
## compute loss
loss = self.compute_loss(y_pred, y)
In [27]: # create some synthetic data for house sizes and corresponding prices
np.random.seed(42)
X = np.array([[500], [1000], [1500], [2000], [2500], [3000]])
y = X * 150 + (np.random.randn(*X.shape) *10000) # Random noise
predictions = nn.predict(X)
#Plotting the data
plt.scatter(X, y, color='blue', label='Actual prices') # Actual prices
plt.plot(X, predictions, color='red', label='Predicted prices') # Predicted prices
plt.xlabel('House Size (sq ft)')
plt.ylabel('House Price ($)')
plt.title('House Price Prediction')
plt.legend()
plt.show()
predictions=model.predict(X_test)
print(f'Prediction for first test image: m{np.argmax(predictions[0])}')
Epoch 1/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 8s 4ms/step - accuracy: 0.8973 - loss: 0.3433
Epoch 2/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 7s 4ms/step - accuracy: 0.9556 - loss: 0.1557
Epoch 3/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 8s 4ms/step - accuracy: 0.9620 - loss: 0.1340
Epoch 4/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 6s 3ms/step - accuracy: 0.9663 - loss: 0.1257
Epoch 5/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 7s 4ms/step - accuracy: 0.9685 - loss: 0.1149
313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 3ms/step - accuracy: 0.9577 - loss: 0.1862
Test accuracy: 0.9638000130653381
313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 3ms/step
Prediction for first test image: m7
Save Model
In [ ]: model.save('handwritten-digit-model.keras')
model = Sequential([
Flatten(input_shape = (28, 28)),
Dense(128, activation = 'relu'),
Dense(10, activation = 'softmax')
])
restore_best_weights = True
)
predictions = model.predict(X_test)
c:\Users\Asus\anaconda3\Anaconda3\Lib\site-packages\keras\src\layers\reshaping\flatt
en.py:37: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer.
When using Sequential models, prefer using an `Input(shape)` object as the first lay
er in the model instead.
super().__init__(**kwargs)
Epoch 1/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 8s 4ms/step - accuracy: 0.8980 - loss: 0.3363
Epoch 2/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 6s 3ms/step - accuracy: 0.9565 - loss: 0.1530
Epoch 3/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 6s 3ms/step - accuracy: 0.9611 - loss: 0.1370
Epoch 4/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 7s 4ms/step - accuracy: 0.9683 - loss: 0.1130
Epoch 5/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 7s 3ms/step - accuracy: 0.9689 - loss: 0.1158
313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 3ms/step - accuracy: 0.9568 - loss: 0.2054
Test accuracy: 0.9620000123977661
313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 3ms/step
prediction for first test image: 7
File I/O allows reading data from the files and writing data to files.
Python provides the open() function to work with File I/O
filename: Name of the file with full path that we want to open
r Read-only mode.
w Write mode. Creates/truncates the file.
x Exclusive creation. Fails if the file exists.
a Append mode. Writes data at the end.
b Binary mode. Used with rb, wb.
t Text mode (default).
+-- Update mode (read and write).
Baidehi Basnet
Read text file Line and assign the content to a Python Variable
In [9]: # read text content line by line using (nextline()) and while loop
Baidehi Basnet
Baidehi Basnet
line = text_file.readline()
while line:
print(line, end='')
line = text_file.readline()
Baidehi Basnet
Baidehi Basnet
['Baidehi Basnet\n']
Function Description
Function Description
In [32]: import os
# Create a New Directories
if os.path.isdir('test-dir'):
print("It's a directory.")
else:
print("It's not a directory.")
Directory exists.
It's a directory.
car.data.csv
handwritten-digit-model.keras
housing.csv
marketing-sales.csv
nep-india-china-gdp.csv
nepal-economy.csv
nepal-economy.xlsx
nepal-population-ethinic-group.json
new-text-file-1.txt
new-text-file.txt
product-data.csv
student-admission.csv
student.csv
student.json
student.xlsx
student2.csv
test.json
test.txt
user_data.csv
user_data.json
user_data.xlsx
Extra Question
# Example usage
file_path = "Ball.jpg" # Replace with the correct file path
display_image(file_path)