Skip to content

Commit 79a26e4

Browse files
authored
Add files via upload
1 parent 662ab8f commit 79a26e4

File tree

2 files changed

+146
-0
lines changed

2 files changed

+146
-0
lines changed

Image_classification_on_CIFAR_10.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# Image classification on CIFAR 10
2+
3+
import keras
4+
from keras.datasets import cifar10
5+
from keras.models import Sequential
6+
from keras.preprocessing.image import ImageDataGenerator
7+
from keras.layers import Dense, Flatten, Dropout, MaxPooling2D, Conv2D, Convolution2D, BatchNormalization, Activation
8+
import matplotlib.pyplot as plt
9+
from keras.utils import to_categorical
10+
11+
import warnings
12+
warnings.filterwarnings('ignore')
13+
14+
#loading data
15+
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
16+
17+
#priting features shape
18+
print('x_train shape:', len(x_train))
19+
print('x_test shape:', x_test.shape)
20+
print('x_test shape:', len(x_test))
21+
22+
#priting labels shape
23+
print('y_train shape:', y_train.shape)
24+
print('y_train shape:', len(y_train))
25+
print('y_test shape:', y_test.shape)
26+
print('y_test shape:', len(y_test))
27+
28+
#all classes images
29+
for i in range(10):
30+
plt.imshow(x_train[i])
31+
plt.show()
32+
33+
34+
#one hot encoding on y column
35+
y_train = to_categorical(y_train)
36+
y_test = to_categorical(y_test)
37+
38+
y_train = y_train/255
39+
y_test = y_test/255
40+
41+
#changing datatype fo columns
42+
y_train = y_train.astype('float32')
43+
y_test = y_test.astype('float32')
44+
45+
#building a model
46+
classifier = Sequential()
47+
48+
#Convolution Layers with regularization
49+
classifier.add(Convolution2D(32, (3,3), input_shape=(32, 32, 3)))
50+
classifier.add(Activation('relu'))
51+
classifier.add(BatchNormalization())
52+
classifier.add(Convolution2D(32, (3,3), input_shape=(32, 32, 3)))
53+
classifier.add(Activation('relu'))
54+
classifier.add(BatchNormalization())
55+
classifier.add(MaxPooling2D(pool_size=(3,3)))
56+
classifier.add(Dropout(0.4))
57+
58+
classifier.add(Convolution2D(64, (3,3)))
59+
classifier.add(Activation('relu'))
60+
classifier.add(BatchNormalization())
61+
classifier.add(Convolution2D(64, (3,3)))
62+
classifier.add(Activation('relu'))
63+
classifier.add(BatchNormalization())
64+
classifier.add(MaxPooling2D(pool_size=(3,3)))
65+
classifier.add(Dropout(0.5))
66+
67+
#Adding Dense Layers
68+
classifier.add(Flatten())
69+
classifier.add(Dense(units=1024))
70+
classifier.add(BatchNormalization())
71+
classifier.add(Activation('relu'))
72+
classifier.add(Dropout(0.5))
73+
classifier.add(Dense(units=10))
74+
classifier.add(Activation('softmax'))
75+
76+
#Compiling model
77+
classifier.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
78+
79+
datagen = ImageDataGenerator(
80+
featurewise_center=False, # set input mean to 0 over the dataset
81+
samplewise_center=False, # set each sample mean to 0
82+
featurewise_std_normalization=False, # divide inputs by std of the dataset
83+
samplewise_std_normalization=False, # divide each input by its std
84+
zca_whitening=False, # apply ZCA whitening
85+
zca_epsilon=1e-06, # epsilon for ZCA whitening
86+
rotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)
87+
# randomly shift images horizontally (fraction of total width)
88+
width_shift_range=0.1,
89+
# randomly shift images vertically (fraction of total height)
90+
height_shift_range=0.1,
91+
shear_range=0., # set range for random shear
92+
zoom_range=0., # set range for random zoom
93+
channel_shift_range=0., # set range for random channel shifts
94+
# set mode for filling points outside the input boundaries
95+
fill_mode='nearest',
96+
cval=0., # value used for fill_mode = "constant"
97+
horizontal_flip=True, # randomly flip images
98+
vertical_flip=True, # randomly flip images
99+
# set rescaling factor (applied before any other transformation)
100+
rescale=None,
101+
# set function that will be applied on each input
102+
preprocessing_function=None,
103+
# image data format, either "channels_first" or "channels_last"
104+
data_format=None,
105+
# fraction of images reserved for validation (strictly between 0 and 1)
106+
validation_split=0.0)
107+
108+
datagen.fit(x_train)
109+
110+
classifier.fit_generator(datagen.flow(x_train, y_train, batch_size=64),
111+
epochs=128, validation_data=(x_test, y_test), steps_per_epoch=len(x_train) / 32)
112+
113+
#saving sn object
114+
classifier.save('Object_classification_model.h5')
115+
116+
# Score trained model.
117+
scores = classifier.evaluate(x_test, y_test, verbose=1)
118+
print('Test loss:', scores[0])
119+
print('Test accuracy:', scores[1])

SVM_IRIS.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# We will use the breast cancer dataset as an example
2+
# The dataset is a binary classification dataset
3+
# Importing the dataset
4+
import matplotlib.pyplot as plt
5+
import numpy as np
6+
import pandas as pd
7+
from sklearn.datasets import load_breast_cancer
8+
from mpl_toolkits.mplot3d import Axes3D
9+
from matplotlib.ticker import LinearLocator, FormatStrFormatter
10+
data = load_breast_cancer()
11+
X = pd.DataFrame(data=data.data, columns=data.feature_names) # Features
12+
y = data.target # Target variable
13+
# Importing PCA function
14+
from sklearn.decomposition import PCA
15+
pca = PCA(n_components=2) # n_components = number of principal components to generate
16+
# Generating pca components from the data
17+
pca_result = pca.fit_transform(X)
18+
print("Explained variance ratio : \n",pca.explained_variance_ratio_)
19+
# Creating a figure
20+
fig = plt.figure(1, figsize=(16, 10))
21+
# Enabling 3-dimensional projection
22+
ax = fig.gca(projection='3d')
23+
for i, name in enumerate(data.target_names):
24+
ax.text3D(np.std(pca_result[:, 0][y==i])-i*500 ,np.std(pca_result[:, 1][y==i]),0,s=name, horizontalalignment='center', bbox=dict(alpha=.5, edgecolor='w', facecolor='w'))
25+
# Plotting the PCA components
26+
ax.scatter(pca_result[:,0], pca_result[:, 1], c=y, cmap = plt.cm.Spectral,s=20, label=data.target_names)
27+
plt.show()

0 commit comments

Comments
 (0)