Loading

Lidar Car Detection

Solution for submission 156597

A detailed solution for submission 156597 submitted for challenge Lidar Car Detection

konstantin_diachkov

Starter Code for Lidar Car Detection

What we are going to Learn

  • Learning about how lidar works
  • Using scikit-learn for binary classification.

Note : Create a copy of the notebook and use the copy for submission. Go to File > Save a Copy in Drive to create a new copy

Downloading Dataset

Installing aicrowd-cli

In [4]:
!pip install aicrowd-cli
%load_ext aicrowd.magic
Requirement already satisfied: aicrowd-cli in /usr/local/lib/python3.7/dist-packages (0.1.10)
Requirement already satisfied: toml<1,>=0.10.2 in /usr/local/lib/python3.7/dist-packages (from aicrowd-cli) (0.10.2)
Requirement already satisfied: pyzmq==22.1.0 in /usr/local/lib/python3.7/dist-packages (from aicrowd-cli) (22.1.0)
Requirement already satisfied: tqdm<5,>=4.56.0 in /usr/local/lib/python3.7/dist-packages (from aicrowd-cli) (4.62.0)
Requirement already satisfied: rich<11,>=10.0.0 in /usr/local/lib/python3.7/dist-packages (from aicrowd-cli) (10.9.0)
Requirement already satisfied: click<8,>=7.1.2 in /usr/local/lib/python3.7/dist-packages (from aicrowd-cli) (7.1.2)
Requirement already satisfied: requests<3,>=2.25.1 in /usr/local/lib/python3.7/dist-packages (from aicrowd-cli) (2.26.0)
Requirement already satisfied: requests-toolbelt<1,>=0.9.1 in /usr/local/lib/python3.7/dist-packages (from aicrowd-cli) (0.9.1)
Requirement already satisfied: GitPython==3.1.18 in /usr/local/lib/python3.7/dist-packages (from aicrowd-cli) (3.1.18)
Requirement already satisfied: gitdb<5,>=4.0.1 in /usr/local/lib/python3.7/dist-packages (from GitPython==3.1.18->aicrowd-cli) (4.0.7)
Requirement already satisfied: typing-extensions>=3.7.4.0 in /usr/local/lib/python3.7/dist-packages (from GitPython==3.1.18->aicrowd-cli) (3.7.4.3)
Requirement already satisfied: smmap<5,>=3.0.1 in /usr/local/lib/python3.7/dist-packages (from gitdb<5,>=4.0.1->GitPython==3.1.18->aicrowd-cli) (4.0.0)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.25.1->aicrowd-cli) (2.10)
Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.25.1->aicrowd-cli) (2.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.25.1->aicrowd-cli) (2021.5.30)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.25.1->aicrowd-cli) (1.24.3)
Requirement already satisfied: commonmark<0.10.0,>=0.9.0 in /usr/local/lib/python3.7/dist-packages (from rich<11,>=10.0.0->aicrowd-cli) (0.9.1)
Requirement already satisfied: colorama<0.5.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from rich<11,>=10.0.0->aicrowd-cli) (0.4.4)
Requirement already satisfied: pygments<3.0.0,>=2.6.0 in /usr/local/lib/python3.7/dist-packages (from rich<11,>=10.0.0->aicrowd-cli) (2.6.1)
The aicrowd.magic extension is already loaded. To reload it, use:
  %reload_ext aicrowd.magic
In [5]:
%aicrowd login
Please login here: https://api.aicrowd.com/auth/EL7jnc8ngWqyOdFXFMksgnQsIoC_JvmH9eKdolWQF8Y
API Key valid
Saved API Key successfully!
In [3]:
!rm -rf data
!mkdir data
%aicrowd ds dl -c lidar-car-detection -o data

Importing Libraries

In [6]:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
import os
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import random

%matplotlib notebook
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
import tensorflow.keras.backend as K
In [ ]:
# !pip install catboost

Reading the dataset

In [ ]:
# Reading the training dataset
# Reading the training dataset
train_data = np.load("data/train.npz", allow_pickle=True)
test_data = np.load("data/test.npz", allow_pickle=True)
train_data = train_data['train']
test_data = test_data['test']

train_data.shape, test_data.shape
Out[ ]:
((400, 2), (601,))

Visualizing the dataset

In this section, we will be visualizing a sample 3D lidar data

In [ ]:
# Getting a random 3D lidar sample data
INDEX = random.randint(0, train_data.shape[0] - 1)

# Getting the individual x, y and z points.
x = train_data[INDEX][0][:, 0].tolist()
y = train_data[INDEX][0][:, 1].tolist()
z = train_data[INDEX][0][:, 2].tolist()

# Label for the corrosponding sample ( no. of cars )
label  = train_data[INDEX][1]

# Generating the 3D graph
fig = go.Figure(data=[go.Scatter3d(x=x, y=y, z=z,
                                   mode='markers',
                                   marker=dict(
                                   size=1,       
                                   colorscale='Viridis',
                                   opacity=0.8))])
print("No. of cars : ", label)
fig.show()
No. of cars :  4

Can you try finding cars in this 3d data ?

In [ ]:
print(train_data[:, 1].max())
plt.figure()
plt.hist(train_data[:, 1])
plt.show()
7
In [ ]:
X = np.array([sample for sample in train_data[:, 0].tolist()])
Y = to_categorical(np.array(train_data[:, 1], dtype=np.int), num_classes=8)
X_test = np.array([sample for sample in test_data.tolist()])

m,n,r = X.shape
out_arr = np.column_stack((np.repeat(np.arange(m),n), X.reshape(m*n,-1)))
df = pd.DataFrame(out_arr)
df.columns = ["idx", "x", "y", "z"]

m,n,r = X_test.shape
out_arr = np.column_stack((np.repeat(np.arange(m),n), X_test.reshape(m*n,-1)))
df_test = pd.DataFrame(out_arr)
df_test.columns = ["idx", "x", "y", "z"]
In [ ]:
X.shape, X_test.shape, Y.shape
Out[ ]:
((400, 38793, 3), (601, 38793, 3), (400, 8))
In [ ]:
# Normalize
df["x"] = df["x"] / 60 + 0.5
df["y"] = df["y"] / 60 + 0.5
df["z"] = df["z"] / 16 + 0.2

df_test["x"] = df_test["x"] / 60 + 0.5
df_test["y"] = df_test["y"] / 60 + 0.5
df_test["z"] = df_test["z"] / 16 + 0.2
In [ ]:
# Drop low / high z values rows
df = df.drop(df[(df["z"] > 0.22) | (df["z"] < 0.10)].index).reset_index()
df = df.drop(["z",], axis=1).reset_index()

df_test = df_test.drop(df_test[(df_test["z"] > 0.22) | (df_test["z"] < 0.10)].index).reset_index()
df_test = df_test.drop(["z",], axis=1).reset_index()
In [ ]:
# Turn 3D points cloud to flat images
img_size = 128

images = np.zeros((int(df["idx"].max()+1), img_size, img_size, 1))
images_test = np.zeros((int(df_test["idx"].max()+1), img_size, img_size, 1))

def make_img(points, images):
    for i, r in points.iterrows():
        images[int(r["idx"])][int(r["x"]*img_size)][int(r["y"]*img_size)] = [1]

df.groupby("idx").apply(lambda x: make_img(x, images))
df_test.groupby("idx").apply(lambda x: make_img(x, images_test))
Out[ ]:
In [ ]:
plt.figure()
plt.imshow(images[INDEX].squeeze(), cmap="gray")
plt.show()
In [ ]:
# Data augmentation (horizontal flip)
augmented_images = np.vstack((np.rot90(images, axes=(1, 2)), images))
augmented_images = np.vstack((np.rot90(images, k=2, axes=(1, 2)), augmented_images))
augmented_images = np.vstack((np.rot90(images, k=3, axes=(1, 2)), augmented_images))
augmented_Y = np.hstack((Y, Y, Y, Y))
In [ ]:
augmented_images.shape, augmented_Y.shape
Out[ ]:
((1600, 128, 128, 1), (400, 32))
In [ ]:

Splitting the dataset

In [ ]:
# Getting the 3d points and flattening the points into 1d array ( using only 100 training samples for faster training )
X = train_data[:, 0]
X = [i.flatten() for i in X]

# labels
y = train_data[:, 1]
In [ ]:
# Splitting the dataset into training and testing
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2)

Training the model

In [ ]:
model = RandomForestRegressor(verbose=True, n_jobs=-1, n_estimators=70)
In [ ]:
# from catboost import CatBoostRegressor

# model = CatBoostRegressor(loss_function='MAE',verbose=1, depth=3, iterations=300) # task_type="GPU", 
model.fit(X_train, y_train)#, eval_set=(X_val, y_val))
[Parallel(n_jobs=-1)]: Using backend ThreadingBackend with 2 concurrent workers.
[Parallel(n_jobs=-1)]: Done  46 tasks      | elapsed:  5.2min
[Parallel(n_jobs=-1)]: Done  70 out of  70 | elapsed:  8.0min finished
Out[ ]:
RandomForestRegressor(bootstrap=True, ccp_alpha=0.0, criterion='mse',
                      max_depth=None, max_features='auto', max_leaf_nodes=None,
                      max_samples=None, min_impurity_decrease=0.0,
                      min_impurity_split=None, min_samples_leaf=1,
                      min_samples_split=2, min_weight_fraction_leaf=0.0,
                      n_estimators=70, n_jobs=-1, oob_score=False,
                      random_state=None, verbose=True, warm_start=False)

Validation

In [ ]:
model.score(X_val, y_val)
[Parallel(n_jobs=2)]: Using backend ThreadingBackend with 2 concurrent workers.
[Parallel(n_jobs=2)]: Done  46 tasks      | elapsed:    0.0s
[Parallel(n_jobs=2)]: Done  70 out of  70 | elapsed:    0.0s finished
Out[ ]:
0.2422046810389168

Generating the predictions

In [ ]:
# Loading the test data

test_data = np.load("/content/data/test.npz", allow_pickle=True)
test_data = test_data['test']

test_data.shape
Out[ ]:
(601,)
In [ ]:
# flattening the points into 1d array
X_test = X = [i.flatten()    for i in test_data]
In [ ]:
# Generating the predictions
predictions = model.predict(X_test)
predictions.shape
[Parallel(n_jobs=2)]: Using backend ThreadingBackend with 2 concurrent workers.
[Parallel(n_jobs=2)]: Done  46 tasks      | elapsed:    0.0s
[Parallel(n_jobs=2)]: Done 196 tasks      | elapsed:    0.1s
[Parallel(n_jobs=2)]: Done 300 out of 300 | elapsed:    0.1s finished
Out[ ]:
(601,)
In [ ]:
submission = pd.DataFrame({"label":predictions})
submission
Out[ ]:
label
0 2.720000
1 2.803333
2 2.943333
3 3.270000
4 2.073333
... ...
596 2.466667
597 1.863333
598 2.130000
599 2.610000
600 2.773333

601 rows × 1 columns

In [7]:
# Saving the predictions
!rm -rf assets
!mkdir assets
# submission.to_csv(os.path.join("assets", "submission.csv"))

Submitting our Predictions

Note : Please save the notebook before submitting it (Ctrl + S)

In [ ]:

/usr/local/lib/python3.7/dist-packages/aicrowd/notebook/helpers.py:361: UserWarning: `%aicrowd` magic command can be used to save the notebook inside jupyter notebook/jupyterLab environment and also to get the notebook directly from the frontend without mounting the drive in colab environment. You can use magic command to skip mounting the drive and submit using the code below:
 %load_ext aicrowd.magic
%aicrowd notebook submit -c lidar-car-detection -a assets --no-verify
  warnings.warn(description + code)
Using notebook: Lidar Car Prediction for submission...
Removing existing files from submission directory...
Scrubbing API keys from the notebook...
Collecting notebook...
submission.zip ━━━━━━━━━━━━━━━━━━━━━━━━ 100.0%1.2/1.2 MB1.2 MB/s0:00:00
                                                   ╭─────────────────────────╮                                                    
                                                   │ Successfully submitted! │                                                    
                                                   ╰─────────────────────────╯                                                    
                                                         Important links                                                          
┌──────────────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│  This submission │ https://www.aicrowd.com/challenges/ai-blitz-xi/problems/lidar-car-detection/submissions/156308              │
│                  │                                                                                                             │
│  All submissions │ https://www.aicrowd.com/challenges/ai-blitz-xi/problems/lidar-car-detection/submissions?my_submissions=true │
│                  │                                                                                                             │
│      Leaderboard │ https://www.aicrowd.com/challenges/ai-blitz-xi/problems/lidar-car-detection/leaderboards                    │
│                  │                                                                                                             │
│ Discussion forum │ https://discourse.aicrowd.com/c/ai-blitz-xi                                                                 │
│                  │                                                                                                             │
│   Challenge page │ https://www.aicrowd.com/challenges/ai-blitz-xi/problems/lidar-car-detection                                 │
└──────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
In [ ]:


Comments

You must login before you can post a comment.

Execute