# 如何在colab中释放内存？

Reghunaath AA

``````import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import regularizers
from tensorflow.keras.layers import Dense,Activation,Flatten,Conv2D,MaxPooling2D,Dropout
import os
import cv2
import random
import pickle
import time
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.python.framework import ops
p1=open("/content/tfds.pickle","rb")
def prepare_ds():
dir="drive//My Drive//dataset//"
cat=os.listdir(dir)
i=1
td=[]
for x in cat:
d=dir+x
y1=cat.index(x)
for img in os.listdir(d):
print(i)
i=i+1
im=cv2.resize(im,(200,200))
td.append([im,y1])
##      im[:,:,0],im[:,:,2]=im[:,:,2],im[:,:,0].copy()
##      plt.imshow(im)
##      plt.show()
random.shuffle(td)
X=[]
Y=[]
for a1,a2 in td:
X.append(a1)
Y.append(a2)
X=np.array(X).reshape(-1,200,200,3)
Y=np.array(Y).reshape(-1,1)
pickle.dump([X,Y],p1)
##prepare_ds()
X=X/255.0
def learn():
model=tf.keras.models.Sequential()

for l in range(cli-1):

for l in range(dli):

model.fit(X,Y,batch_size=16,validation_split=0.1,epochs=3,verbose=2,callbacks=[tb])
model.save('tm1.h5')
ops.reset_default_graph()

dl=[0,1,2]
ls=[32,64,128]
cl=[1,2,3]
for dli in dl:
for lsi in ls:
for cli in cl:
ops.reset_default_graph()
NAME = "{}-conv-{}-nodes-{}-dense".format(cli, lsi, dli)
tb=TensorBoard(log_dir="logs//{}".format(NAME))
print(NAME)
learn()

p1.close()
!zip -r /content/file.zip /content/logs
!cp file.zip "/content/drive/My Drive/"
``````

``````# Garbage Collector - use it like gc.collect()
import gc

# Custom Callback To Include in Callbacks List At Training Time
class GarbageCollectorCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
gc.collect()
``````

0 条评论