Kaggle competition: Plant Seedlings Classification
<SOS> metric: MeanFScore Kaggle data source: plant-seedlings-classification<predict_on_test>
scale = 70
seed = 7
model_lgb.fit(train, y_train)
 lgb_train_pred = model_lgb.predict(train)
 lgb_pred = np.expm1(model_lgb.predict(test.values))
print(rmsle(y_train, lgb_train_pred))<compute_test_metric>
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 )
print('RMSLE score on train data:')
 print(rmsle(y_train,stacked_train_pred*0.5 +
xgb_train_pred*0.1 + lgb_train_pred*0.4))<define_variables>
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("Number of classes: " + str(classes))
traininglabels[0].value_counts().plot(kind='pie' )
ensemble = stacked_pred*0.5 + xgb_pred*0.1 + lgb_pred*0.4<save_to_csv>
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)
 print('Train Shape: {}'.format(x_train.shape))
sub = pd.DataFrame()
sub['Id'] = test_ID
sub['SalePrice'] = ensemble
sub.to_csv('submission.csv',index=False )<import_modules>
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 )
print("pandas version: {}".format(pd.__version__))
print("NumPy version: {}".format(np.__version__))
print("matplotlib version: {}".format(matplotlib.__version__))
print("seaborn version: {}".format(sns.__version__))
print("scikit-learn version: {}".format(sklearn.__version__))
print("statsmodels version: {}".format(statsmodels.__version__))
print("SciPy version: {}".format(sp.__version__))<import_modules>
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()
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn import feature_selection
from sklearn import model_selection
from sklearn import metrics
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import seaborn as sns<load_from_csv>
lrr = ReduceLROnPlateau(monitor='val_acc',
patience=3,
verbose=1,
factor=0.4,
min_lr=0.00001)
 filepath='weights.best_{epoch:02d}-{val_acc:.2f}.h5'
checkpoints = ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=True, mode='max')
 filepath='weights.last_auto4.h5'
checkpoints_full = ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=False, mode='max')
 callbacks_list = [checkpoints, lrr, checkpoints_full]
model.load_weights(".. /input/weights/weights.best_17-0.96.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))
<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)
 print('Prediction result saved as Prediction.csv' )