簡體   English   中英

如何在來自 a.csv 文件的數據集上訓練我的 CNN model?

[英]how can i train my CNN model on dataset from a .csv file?

hi guys i'm a Python beginner and i'm using google Colab to train my first CNN model, i'm blocked on the training part, i know i have to use model.fit() to train the model, but i have不知道 model.fit() 里面有什么,另外我不確定從 a.csv 文件中拆分我的數據集的部分。 這是我的代碼:

from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import to_categorical
from keras.preprocessing import image
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from sklearn.metrics import accuracy_score
from tqdm import tqdm
from numpy.random import RandomState
import csv

df = pd.read_csv('classes.csv')
print(df.head(3500))
#splitting the dataset in training and testing sets.
rng = RandomState()

train = df.sample(frac=0.7, random_state=rng)
test = df.loc[~df.index.isin(train.index)]



#model's structure

model = Sequential()
#convolutional layer
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=(28,28,1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
#flatten output of conv
model.add(Flatten())
#hidden layer
model.add(Dense(128, activation='relu')) 
#output layer
model.add(Dense(10, activation='softmax')) 
#compiling sequential model
model.compile(loss='categorical_crossentropy',optimizer='Adam',metrics=['accuracy'])
model.summary()
#training the model
model.fit()


好的,如果我們能提供幫助,讓我們開始吧。 首先是關於拆分數據框。 最好將其拆分為訓練集、驗證集和測試集。 最好的方法是使用 sklearn 的 train, test, split。 文檔是 [here.][1] 使用下面的代碼將數據 Trame 分成 3 組

from sklearn.model_selection import train_test_split
train_split=.8  # percentage of df to use for training
test_split = .05 # percentage of df to use for test
# note valid_split=1- train_split = test_ split in this case .15
train_df, dummy_df= train_test_split(df, train_split=train_split, shuffle=True, random_state=123)
dummy_split=test_split/(1.0 - train_split)
test_df, valid_df=train_test_split(dummy_df, train_split=dummy_split) # note dummy_df is 20% of df

現在您需要創建訓練、測試和驗證生成器。 我假設您有圖像輸入。 使用 ImageDataGenerator.flow_from_dataframe() 創建您的生成器。 相關文檔是 [here.][2] 通常在 0 到 1 或 -1 到 +1 范圍內縮放像素圖像。 我更喜歡后者。 下面是生成器的代碼

def scalar(img):
       return img/127.5 -1
x_col='Filename' # set this to point to the df column that holds the full path to the image file
y_col- 'Label' # set this to the df column that holds the class labels
batch_size = 32 # set this to the batch size
class_mode='categorical'
image_shape=(64,64) # set this to desired image size
tgen=tf.keras.preprocessing.image.ImageDataGenerator(preprocessing_function=scalar, horizontal_flip=True)
gen= tf.keras.preprocessing.image.ImageDataGenerator(preprocessing_function=scalar)
train_gen=tgen.flow_from_dataframe(train_df, x_col=x_col, 
                                   y_col=y_col,target_size=image_shape,
                                   class_mode=class_mode, batch_size=batch_size, 
                                    shuffle=True, random_state=123)                                   
test_gen=tgen.flow_from_dataframe(test_df, x_col= x_col, y_col=y_col 
                                   class_mode=class_mode, 
                                   batch_size=batch_size, shuffle=False)                                        
valid_gen=tgen.flow_from_dataframe(valid_df, x_col=x_col, shuffle=False,
                                   y_col=y_col,batch_size=batch_size 
                                   class_mode=class_mode , target_size=image_shape)

現在是時候使用 model.fit 訓練您的 model。 文檔在[這里][3]

epochs = 15 # set this to the number of epochs to run
history=model.fit(train_gen, epochs=epochs, validation_data= valid_gen, verbose=1)

當 model 完成訓練后,您想看看它在測試集上的表現如何。 你這樣做 model.evaluate 如下所示

accuracy = model.evaluate(test_gen, verbose=1)[1]
print (accuracy)

您可以使用 model 使用 model.predict 進行預測

preds=model.predict(test_gen, verbose=1)

preds 是一個矩陣,其行數等於測試集中的樣本數,列數等於您擁有的類數。 每個條目是圖像在該 class 中的概率值。 您想要 select 具有最高概率值的列。 使用 np.argmax 查找具有最高概率值的列(類)。 您可以使用 labels-test_gen.labels 獲取 test_set 標簽。 代碼如下

correct_preds=0
for i in range (len(preds):
    index=np.argmax(preds[i]) # column with highest probability
    label=test_gen.labels[i] # true class of image
    if index == label:
        correct_preds +=1
pred_accuracy= correct_preds/ len(preds)
print ( pred_accuracy)
    
                                
 


  [1]: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
  [2]: https://keras.io/api/preprocessing/image/
  [3]: https://www.tensorflow.org/api_docs/python/tf/keras/Model

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM