Question

I have some images of cats dogs and brids data set that I want to use...

I have some images of cats dogs and brids data set that I want to use to train a code using machine learning to distenguish new images by the whether they pictures od dogs, birds or cats. can you show how to do it in an example. please write the code.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:

import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
import matplotlib.pyplot as plt


datagen = ImageDataGenerator(rescale=1/255)#The ImageDataGenerator class has two methods flow() and flow_from_directory() to read the images from a big numpy array and folders containing images.
train_generator = datagen.flow_from_directory(
directory='Path of your training data set',
target_size=(30, 30),
color_mode="grayscale",
batch_size=5,
class_mode="categorical",
shuffle=True,
seed=42)

valid_generator = datagen.flow_from_directory(
directory='Pat of your validation data set',
target_size=(30, 30),
color_mode="grayscale",
batch_size=5,
class_mode="categorical",
shuffle=True,
seed=42
)

test_generator = datagen.flow_from_directory(
directory='Path of your training data set',
target_size=(30, 30),
color_mode="grayscale",
batch_size=5,
class_mode=None,
shuffle=False,
seed=42
)


# 7. Define model architecture
from keras import backend as K
K.set_image_dim_ordering('th')
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(1,30,30)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(79, activation='softmax'))

# 8. Compile model
x=model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])
#..................................................................................................
#Fitting/Training the model
STEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size
STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size
from keras.callbacks import History
history = History()
hist=model.fit_generator(generator=train_generator,
steps_per_epoch=STEP_SIZE_TRAIN,
validation_data=valid_generator,
validation_steps=STEP_SIZE_VALID,
epochs=10
)

train_loss=hist.history['loss']
val_loss=hist.history['val_loss']
train_acc=hist.history['acc']
val_acc=hist.history['val_acc']
xc=range(10)

plt.figure(1,figsize=(7,5))
plt.plot(xc,train_loss)
plt.plot(xc,val_loss)
plt.plot(xc,train_acc)
plt.plot(xc,val_acc)
plt.grid(True)
plt.xlabel('num of Epochs')
plt.ylabel('loss/accuracy')
plt.legend(['train_loss','val_loss','train_accu','val_accu'],loc=3)
plt.style.use(['classic'])

#Evaluate the model
model.evaluate_generator(generator=valid_generator)

#creating dataframe of train_loss,val_loss,train_acc,val_acc and saving it
dataframe1=pd.DataFrame({'train_loss':train_loss,
'val_loss':val_loss,
'train_acc':train_acc,
'val_acc':val_acc})
dataframe1.to_csv("values.csv",index=True)

#Predict the output
test_generator.reset()
pred=model.predict_generator(test_generator,verbose=1)

predicted_class_indices=np.argmax(pred,axis=1)
labels = (train_generator.class_indices)
labels = dict((v,k) for k,v in labels.items())
predictions = [labels[k] for k in predicted_class_indices]

#Finally save the result to CSV file
filenames=test_generator.filenames
results=pd.DataFrame({"Filename":filenames,
"Predictions":predictions})
results.to_csv("results.csv",index=True)

Add a comment
Know the answer?
Add Answer to:
I have some images of cats dogs and brids data set that I want to use...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Giving genetic (DNA) data from a person, predict the odds of him/her developing a given type...

    Giving genetic (DNA) data from a person, predict the odds of him/her developing a given type of cancer over the next 10 years. This is which type of machine learning problem? A. Regression B. Classification C. Clustering D. Natural language processing E. Computer vision Which of the following is the top reason of IS threat or data leakage since 2002? A. Internet vulnerabilities B. Wireless security weakness C. Software problems D. Hardware problems E. Internal employees If we have some...

  • We have to write some code to simulate rabbits population growth in Australia. We have determined...

    We have to write some code to simulate rabbits population growth in Australia. We have determined that the rabbit population doubles every month. For example month 1- 2 rabbits, month 2 –4 rabbits, month 3 – 8 rabbits … We also have some dingo dogs who eat rabbits and who also increases in population. Each dingo dog eats 4 rabbits each month. The dingo population doubles every 6 months. (assume no deaths in dingoes, no one eats a dingo dog)...

  • Hi I need some help with this I just need the code and the collection name...

    Hi I need some help with this I just need the code and the collection name is research only the code I dont need any screenshots of the output. it should be for companies.json using the research collection as like this db.research.aggregate({}) but I don't know how to do the rest. This is the database but it is hard to paste it all so I will paste some and it should be create. Please I need this to be done...

  • I want to use a stepping motor to control the number of steps it moves. I set the “step revolution” to 60 and I set the...

    I want to use a stepping motor to control the number of steps it moves. I set the “step revolution” to 60 and I set the number of steps to 1. But it hasn’t stopped for a long time and has been walking. I am using a Arduino IDE to make a writing machine (X-Y Plotter) It would be better if you could give me the code and explain it.

  • MATLAB question: I have some data on excell and I have to write a code that...

    MATLAB question: I have some data on excell and I have to write a code that does the following: Please use dummy data for your convenience. Thank you in advance for your help! Read from Data_all.xlsx Sheet “Wave_data", your specific Wave Height (WH) measurements and using a "for loop" and "if-elseif-else" command, count the number of measurement in the following ranges: a. WH= 0 or 1 m b. WH=2 or 3 m c. WH=4 or 5 m d. WH=6 or...

  • I have a data set called ACS that I set my_data <- read.csv('acs_ny_CSV.csv'). One of the...

    I have a data set called ACS that I set my_data <- read.csv('acs_ny_CSV.csv'). One of the values in the data set here is FamilyIncome having a value from 50 to 1 mill plus FamilyIncome Min. : 50 1st Qu.: 52540 Median : 87000 Mean : 110281 3rd Qu.: 133800 Max. :1605000 I need to convert this value to a 0 and 1 as I need to "Make a binary variable with value TRUE for income above $150,000 and FALSE for...

  • #PYTHON# In this exercise you will write code which loads a collection of images (which are...

    #PYTHON# In this exercise you will write code which loads a collection of images (which are all the same size), computes a pixelwise average of the images, and displays the resulting average. The images below give some examples that were generated by averaging "100 unique commemorative photographs culled from the internet" by Jason Salavon. Your program will do something similar. Write a function in the cell below that loads in one of the sets of images and computes their average....

  • I have some questions related to machine learning course : how can I use k-NN classification...

    I have some questions related to machine learning course : how can I use k-NN classification with Olivetti Faces dataset ?

  • I have a text file with some quotes and I want to use php or laravel...

    I have a text file with some quotes and I want to use php or laravel to pull one quote at a time and display it to my website upon every page refresh. How do I use PHP or Laravel to pull one quote at a time from the text file (saved in my project as quotes.txt) and display it on my webpage? I am also open to using ajax and/or javascript.

  • Write a thesis and use supporting claims to complete the working thesis rking thesis: Breed-speeific regulations...

    Write a thesis and use supporting claims to complete the working thesis rking thesis: Breed-speeific regulations on dogs are a bad idea, and people should be allowed to own whatever kind of dog they want. Many states have breed-specific regulations outlawing owning certain breeds of dogs as pets. Breed-specific bans are based on the assumption that some breeds of dogs are more dangerous than others. Studies show that even breeds of dog considered "aggressive" can be trained to be safe...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT