Kaggle competition: Plant Seedlings Classification
<SOS> metric: MeanFScore Kaggle data source: plant-seedlings-classification<define_variables>
scale = 70
seed = 7
features_to_delete_train = []
for col in encoded_categorical_df.columns:
if col not in testing_encoding_categorical.columns:
features_to_delete_train.append(col )<drop_column>
path_to_images = '.. /input/plant-seedlings-classification/train/*/*.png'
images = glob(path_to_images)
 trainingset = []
traininglabels = []
num = len(images)
 count = 1
for i in images:
print(str(count)+'/'+str(num),end='\r')
 trainingset.append(cv2.resize(cv2.imread(i),(scale,scale)))
 traininglabels.append(i.split('/')[-2])
 count=count+1
trainingset = np.asarray(trainingset)
 traininglabels = pd.DataFrame(traininglabels )
encoded_categorical_df.drop(columns=features_to_delete_train,inplace=True )<drop_column>
labels = preprocessing.LabelEncoder()
labels.fit(traininglabels[0])
 print('Classes'+str(labels.classes_))
encodedlabels = labels.transform(traininglabels[0])
 clearalllabels = np_utils.to_categorical(encodedlabels)
 classes = clearalllabels.shape[1]
print(str(classes))
traininglabels[0].value_counts().plot(kind='pie' )
testing_encoding_categorical.drop(columns=features_to_delete_test,inplace=True )<split>
new_train = new_train/255
x_train,x_test,y_train,y_test = train_test_split(new_train,clearalllabels,test_size=0.1,random_state=seed,stratify=clearalllabels )
X_train, X_valid, y_train, y_valid = train_test_split(encoded_categorical_df,y,test_size=0.25 )<compute_train_metric>
generator = ImageDataGenerator(rotation_range = 180,zoom_range = 0.1,width_shift_range = 0.1,height_shift_range = 0.1,horizontal_flip = True,vertical_flip = True)
 generator.fit(x_train )
cbr = CatBoostRegressor(logging_level='Silent')
 cbr.fit(X_train,y_train)
 y_pred = cbr.predict(X_valid)
 print("Mean Squared Error",mean_squared_error(y_valid, y_pred))
print("Mean Absolute Error",mean_absolute_error(y_valid, y_pred))
print("R2 Score",r2_score(y_valid, y_pred))<compute_test_metric>
np.random.seed(seed)
 model = Sequential()
model.add(Conv2D(filters=64, kernel_size=(5, 5), input_shape=(scale, scale, 3), activation='relu'))
model.add(BatchNormalization(axis=3))
model.add(Conv2D(filters=64, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(( 2, 2)))
 model.add(BatchNormalization(axis=3))
model.add(Dropout(0.1))
model.add(Conv2D(filters=128, kernel_size=(5, 5), activation='relu'))
model.add(BatchNormalization(axis=3))
model.add(Conv2D(filters=128, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(( 2, 2)))
 model.add(BatchNormalization(axis=3))
model.add(Dropout(0.1))
model.add(Conv2D(filters=256, kernel_size=(5, 5), activation='relu'))
model.add(BatchNormalization(axis=3))
model.add(Conv2D(filters=256, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(( 2, 2)))
 model.add(BatchNormalization(axis=3))
model.add(Dropout(0.1))
model.add(Flatten())
 model.add(Dense(256, activation='relu'))
model.add(BatchNormalization())
 model.add(Dropout(0.5))
model.add(Dense(256, activation='relu'))
model.add(BatchNormalization())
 model.add(Dropout(0.5))
model.add(Dense(classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
 model.summary()
<save_to_csv>
lrr = ReduceLROnPlateau(monitor='val_acc',
patience=3,
verbose=1,
factor=0.4,
min_lr=0.00001)
 filepath="weights.best.hdf5"
checkpoints = ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=True, mode='max')
 filepath="weights.last_auto4.hdf5"
checkpoints_full = ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=False, mode='max')
 callbacks_list = [checkpoints, lrr, checkpoints_full]
dataset = np.load(".. /input/plantrecomodels/Data.npz")
 data = dict(zip(( "x_train","x_test","y_train", "y_test"),(dataset[k] for k in dataset)))
 trainX = data['x_train']
testX = data['x_test']
trainY = data['y_train']
testY = data['y_test']
hist = model.fit_generator(generator.flow(trainX, trainY, batch_size=75),
epochs=25, validation_data=(testX, testY),
steps_per_epoch=trainX.shape[0], callbacks=callbacks_list)
Id = sample_submission["Id"]
predicted_test = []
for x in cbr.predict(testing_encoding_categorical):
predicted_test.append(x)
 predicted_test_value = pd.DataFrame({ 'Id': Id,
'SalePrice': predicted_test })
 predicted_test_value.to_csv("PredictedTestScore.csv", index=False )<load_from_csv>
model.load_weights("./weights.best.hdf5")
 dataset = np.load(".. /input/plantrecomodels/Data.npz")
 data = dict(zip(( "x_train","x_test","y_train", "y_test"),(dataset[k] for k in dataset)))
 x_train = data['x_train']
x_test = data['x_test']
y_train = data['y_train']
y_test = data['y_test']
print(model.evaluate(x_train, y_train))
print(model.evaluate(x_test, y_test))
a = pd.read_csv("/kaggle/input/titanic/train.csv")
 b = pd.read_csv("/kaggle/input/titanic/test.csv" )<prepare_x_and_y>
y_pred = model.predict(x_test)
 y_class = np.argmax(y_pred, axis = 1)
 y_check = np.argmax(y_test, axis = 1)
 cmatrix = confusion_matrix(y_check, y_class)
 print(cmatrix )
<count_missing_values><EOS> 
newtestimages=newtestimages/255
prediction = model.predict(newtestimages)
 pred = np.argmax(prediction,axis=1)
 predStr = labels.classes_[pred]
result = {'file':tests,'species':predStr}
result = pd.DataFrame(result)
 result.to_csv("Prediction.csv",index=False )