{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":77803,"databundleVersionId":8545958,"sourceType":"competition"}],"dockerImageVersionId":30699,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-14T18:00:10.459050Z","iopub.execute_input":"2024-05-14T18:00:10.459890Z","iopub.status.idle":"2024-05-14T18:00:12.349717Z","shell.execute_reply.started":"2024-05-14T18:00:10.459855Z","shell.execute_reply":"2024-05-14T18:00:12.348832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom pathlib import Path\nimport pandas as pd\n\n# Define directories\ntrain_dir = '/kaggle/input/brainstorming-competition-ai-mode-sports-balls/train'  # Update with the correct path to the train directory\ntest_dir = '/kaggle/input/brainstorming-competition-ai-mode-sports-balls/test/test'  # Update with the correct path to the test directory\n\n# Image data generator for training and validation with 20% validation split\ndatagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest',\n    validation_split=0.2  # 20% validation split\n)\n\n# Load training data\ntrain_generator = datagen.flow_from_directory(\n    train_dir,\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='categorical',\n    subset='training'\n)\n\n# Load validation data\nvalidation_generator = datagen.flow_from_directory(\n    train_dir,\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='categorical',\n    subset='validation'\n)\n\n# Define a simple CNN model\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),\n    MaxPooling2D((2, 2)),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Conv2D(128, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Flatten(),\n    Dense(512, activation='relu'),\n    Dropout(0.5),\n    Dense(len(train_generator.class_indices), activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=train_generator.samples // train_generator.batch_size,\n    validation_data=validation_generator,\n    validation_steps=validation_generator.samples // validation_generator.batch_size,\n    epochs=10\n)\n\n# Load and preprocess test images\ndef load_and_preprocess_image(img_path, target_size=(150, 150)):\n    img = load_img(img_path, target_size=target_size)\n    img_array = img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array = img_array / 255.0  # Rescale\n    return img_array\n\n# Get list of test images\ntest_images = list(Path(test_dir).glob('*.jpg'))\ntest_data = np.vstack([load_and_preprocess_image(str(img_path)) for img_path in test_images])\n\n# Predict on test data\npredictions = model.predict(test_data)\npredicted_classes = np.argmax(predictions, axis=1)\n\n# Create a submission file\nsubmission = pd.DataFrame({\n    'filename': [img_path.name for img_path in test_images],\n    'predicted_class': [list(train_generator.class_indices.keys())[pred_class] for pred_class in predicted_classes]\n})\nsubmission.to_csv('submission.csv', index=False)\nprint(submission.head())\n\n# Save the model\nmodel.save('simple_cnn_model.h5')\n","metadata":{"execution":{"iopub.status.busy":"2024-05-14T18:01:55.376092Z","iopub.execute_input":"2024-05-14T18:01:55.376854Z","iopub.status.idle":"2024-05-14T18:07:35.781697Z","shell.execute_reply.started":"2024-05-14T18:01:55.376824Z","shell.execute_reply":"2024-05-14T18:07:35.780900Z"},"trusted":true},"execution_count":null,"outputs":[]}]}