解决显存不足的方式
解決顯存不足的方式
自己也是剛接觸深度學習,由于畢業壓力大和條件比較高,在學習方面表現得比較急躁。所以很多事情都沒有做好。自己也知道欲速則不達的道理,但很多時候都沒有聽進去。因此寫寫文章,記錄一下自己的學習過程。
之前利用深度學習,進行實驗時,發現數據集過大,總是會超出顯存容量。自己也看了很多CSDN上面的文章,也實驗過,但很多都會有各種各樣的錯誤,實在是難以接受。因此,在別人的代碼里面學習到了一段很好的代碼來生成數據,能夠很好的解決顯存不足的問題。
class DataGenerator(tf.keras.utils.Sequence): #可以看到定義了一個類別,繼承于Sequencedef __init__(self, mains,batch_size, shuffle=False): #該部分定義了,初始數據,主要是整個訓練集,batch_size、shuffle等參數。self.mains = mainsself.batch_size = batch_sizeself.indices = np.arange(len(self.mains))#該部分是產生對應的索引,比如你有1w張圖片進行訓練,那么你的索引位置就應該變成1wself.shuffle = shuffleif self.shuffle:np.random.shuffle(self.indices) #該部分主要是在訓練集中,將數據的索引打亂,這樣能夠起到每個eopch的step訓練數據不一樣。print(self.indices)def __len__(self):return np.ceil(len(self.indices) / self.batch_size).astype(int) #得到能夠每一個epoch能夠產生多少stepdef __getitem__(self, idx): #該部分是迭代器的主體,輸出為mains_batch --> shape = [batch_size * * ]mains_batch = []if idx == self.__len__() - 1:inds = self.indices[idx * self.batch_size:]else:inds = self.indices[idx * self.batch_size: (idx + 1) * self.batch_size]for i in inds:main_sample = self.mains[i:i + self.window_size]mains_batch.append(main_sample)mains_batch_np = np.array(mains_batch)mains_batch_np = np.reshape(mains_batch_np, (mains_batch_np.shape[0], mains_batch_np.shape[1], 1))#這里需要進行reshape操作,這里的shape形狀要根據自己的網絡輸入定,#但第一個shape[0]肯定是mains_batch_np.shape[0],而不能是self.batch_size,#因為如果總的訓練數據不能被batch_size整除的話,最后一個step的batch_size肯定#是小于self.batch_size的。否則將會報錯。總結
- 上一篇: Cuda out of memory显存
- 下一篇: data parallel, model