BiedronkApp/Biedap/igiveup.ipynb

28 KiB
Raw Blame History

import numpy as np 
import pandas as pd 
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Dropout, Activation, Conv2D, MaxPooling2D

# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

import os
print(os.listdir("Biedap/input"))

import zipfile

with zipfile.ZipFile("Biedap/input/train.zip","r") as z:
    z.extractall(".")
    
with zipfile.ZipFile("Biedap/input/test1.zip","r") as z:
    z.extractall(".")

# Any results you write to the current directory are saved as output.
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
Input In [1], in <cell line: 4>()
      2 import pandas as pd 
      3 import cv2
----> 4 import matplotlib.pyplot as plt
      5 import tensorflow as tf
      6 from tensorflow.keras.models import Sequential

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/pyplot.py:49, in <module>
     47 from cycler import cycler
     48 import matplotlib
---> 49 import matplotlib.colorbar
     50 import matplotlib.image
     51 from matplotlib import _api

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/colorbar.py:21, in <module>
     18 import numpy as np
     20 import matplotlib as mpl
---> 21 from matplotlib import _api, collections, cm, colors, contour, ticker
     22 import matplotlib.artist as martist
     23 import matplotlib.patches as mpatches

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/contour.py:13, in <module>
     11 import matplotlib as mpl
     12 from matplotlib import _api, docstring
---> 13 from matplotlib.backend_bases import MouseButton
     14 import matplotlib.path as mpath
     15 import matplotlib.ticker as ticker

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/backend_bases.py:46, in <module>
     43 import numpy as np
     45 import matplotlib as mpl
---> 46 from matplotlib import (
     47     _api, backend_tools as tools, cbook, colors, docstring, textpath,
     48     tight_bbox, transforms, widgets, get_backend, is_interactive, rcParams)
     49 from matplotlib._pylab_helpers import Gcf
     50 from matplotlib.backend_managers import ToolManager

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/widgets.py:22, in <module>
     20 from . import _api, backend_tools, cbook, colors, ticker
     21 from .lines import Line2D
---> 22 from .patches import Circle, Rectangle, Ellipse
     23 from .transforms import TransformedPatchPath
     26 class LockDraw:

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/patches.py:4143, in <module>
   4138         """Return the `.Bbox`."""
   4139         return transforms.Bbox.from_bounds(self._x, self._y,
   4140                                            self._width, self._height)
-> 4143 class FancyArrowPatch(Patch):
   4144     """
   4145     A fancy arrow patch. It draws an arrow using the `ArrowStyle`.
   4146 
   (...)
   4149     does not change when the axis is moved or zoomed.
   4150     """
   4151     _edge_default = True

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/artist.py:119, in Artist.__init_subclass__(cls)
    117 cls.set.__name__ = "set"
    118 cls.set.__qualname__ = f"{cls.__qualname__}.set"
--> 119 cls._update_set_signature_and_docstring()

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/artist.py:147, in Artist._update_set_signature_and_docstring(cls)
    137 cls.set.__signature__ = Signature(
    138     [Parameter("self", Parameter.POSITIONAL_OR_KEYWORD),
    139      *[Parameter(prop, Parameter.KEYWORD_ONLY, default=_UNSET)
    140        for prop in ArtistInspector(cls).get_setters()
    141        if prop not in Artist._PROPERTIES_EXCLUDED_FROM_SET]])
    142 cls.set._autogenerated_signature = True
    144 cls.set.__doc__ = (
    145     "Set multiple properties at once.\n\n"
    146     "Supported properties are\n\n"
--> 147     + kwdoc(cls))

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/artist.py:1749, in kwdoc(artist)
   1731 r"""
   1732 Inspect an `~matplotlib.artist.Artist` class (using `.ArtistInspector`) and
   1733 return information about its settable properties and their current values.
   (...)
   1744     use in Sphinx) if it is True.
   1745 """
   1746 ai = ArtistInspector(artist)
   1747 return ('\n'.join(ai.pprint_setters_rest(leadingspace=4))
   1748         if mpl.rcParams['docstring.hardcopy'] else
-> 1749         'Properties:\n' + '\n'.join(ai.pprint_setters(leadingspace=4)))

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/artist.py:1509, in ArtistInspector.pprint_setters(self, prop, leadingspace)
   1506     return '%s%s: %s' % (pad, prop, accepts)
   1508 lines = []
-> 1509 for prop in sorted(self.get_setters()):
   1510     accepts = self.get_valid_values(prop)
   1511     name = self.aliased_name(prop)

File ~/anaconda3/lib/python3.9/site-packages/matplotlib/artist.py:1435, in ArtistInspector.get_setters(self)
   1432     continue
   1433 func = getattr(self.o, name)
   1434 if (not callable(func)
-> 1435         or len(inspect.signature(func).parameters) < 2
   1436         or self.is_alias(func)):
   1437     continue
   1438 setters.append(name[4:])

File ~/anaconda3/lib/python3.9/inspect.py:3113, in signature(obj, follow_wrapped)
   3111 def signature(obj, *, follow_wrapped=True):
   3112     """Get a signature object for the passed callable."""
-> 3113     return Signature.from_callable(obj, follow_wrapped=follow_wrapped)

File ~/anaconda3/lib/python3.9/inspect.py:2862, in Signature.from_callable(cls, obj, follow_wrapped)
   2859 @classmethod
   2860 def from_callable(cls, obj, *, follow_wrapped=True):
   2861     """Constructs Signature for the given callable object."""
-> 2862     return _signature_from_callable(obj, sigcls=cls,
   2863                                     follow_wrapper_chains=follow_wrapped)

File ~/anaconda3/lib/python3.9/inspect.py:2325, in _signature_from_callable(obj, follow_wrapper_chains, skip_bound_arg, sigcls)
   2320             return sig.replace(parameters=new_params)
   2322 if isfunction(obj) or _signature_is_functionlike(obj):
   2323     # If it's a pure Python function, or an object that is duck type
   2324     # of a Python function (Cython functions, for instance), then:
-> 2325     return _signature_from_function(sigcls, obj,
   2326                                     skip_bound_arg=skip_bound_arg)
   2328 if _signature_is_builtin(obj):
   2329     return _signature_from_builtin(sigcls, obj,
   2330                                    skip_bound_arg=skip_bound_arg)

File ~/anaconda3/lib/python3.9/inspect.py:2196, in _signature_from_function(cls, func, skip_bound_arg)
   2194 kind = _POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD
   2195 annotation = annotations.get(name, _empty)
-> 2196 parameters.append(Parameter(name, annotation=annotation,
   2197                             kind=kind))
   2198 if posonly_left:
   2199     posonly_left -= 1

File ~/anaconda3/lib/python3.9/inspect.py:2518, in Parameter.__init__(self, name, kind, default, annotation)
   2515     msg = 'name must be a str, not a {}'.format(type(name).__name__)
   2516     raise TypeError(msg)
-> 2518 if name[0] == '.' and name[1:].isdigit():
   2519     # These are implicit arguments generated by comprehensions. In
   2520     # order to provide a friendlier interface to users, we recast
   2521     # their name as "implicitN" and treat them as positional-only.
   2522     # See issue 19611.
   2523     if self._kind != _POSITIONAL_OR_KEYWORD:
   2524         msg = (
   2525             'implicit arguments must be passed as '
   2526             'positional or keyword arguments, not {}'
   2527         )

KeyboardInterrupt: 
main_dir = "Biedap"
train_dir = "train"
path = os.path.join(main_dir,train_dir)

for p in os.listdir(path):
    category = p.split(".")[0]
    img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)
    new_img_array = cv2.resize(img_array, dsize=(80, 80))
    plt.imshow(new_img_array,cmap="gray")
    break
X = []
y = []
convert = lambda category : int(category == 'dog')
def create_test_data(path):
    for p in os.listdir(path):
        category = p.split(".")[0]
        category = convert(category)
        img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)
        new_img_array = cv2.resize(img_array, dsize=(80, 80))
        X.append(new_img_array)
        y.append(category)   
create_test_data(path)
X = np.array(X).reshape(-1, 80,80,1)
y = np.array(y)
X = X/255.0
model = Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(Conv2D(64,(3,3), activation = 'relu', input_shape = X.shape[1:]))
model.add(MaxPooling2D(pool_size = (2,2)))
# Add another:
model.add(Conv2D(64,(3,3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Flatten())
model.add(Dense(64, activation='relu'))
# Add a softmax layer with 10 output units:
model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer="adam",
              loss='binary_crossentropy',
              metrics=['accuracy'])
model.fit(X, y, epochs=10, batch_size=32, validation_split=0.2)
train_dir = "test1"
path = os.path.join(main_dir,train_dir)
#os.listdir(path)

X_test = []
id_line = []
def create_test1_data(path):
    for p in os.listdir(path):
        id_line.append(p.split(".")[0])
        img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)
        new_img_array = cv2.resize(img_array, dsize=(80, 80))
        X_test.append(new_img_array)
create_test1_data(path)
X_test = np.array(X_test).reshape(-1,80,80,1)
X_test = X_test/255
predictions = model.predict(X_test)
predicted_val = [int(round(p[0])) for p in predictions]
submission_df = pd.DataFrame({'id':id_line, 'label':predicted_val})
submission_df.to_csv("submission.csv", index=False)