{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"toc":{"base_numbering":1,"nav_menu":{},"number_sections":true,"sideBar":true,"skip_h1_title":false,"title_cell":"案例目录","title_sidebar":"案例目录","toc_cell":false,"toc_position":{},"toc_section_display":true,"toc_window_display":false},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":10418,"databundleVersionId":862236,"sourceType":"competition"},{"sourceId":4326674,"sourceType":"datasetVersion","datasetId":2547995}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# 计时程序开始运行的时间\nimport datetime\nstarttime = datetime.datetime.now()","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:01.153983Z","iopub.execute_input":"2024-11-22T10:17:01.154404Z","iopub.status.idle":"2024-11-22T10:17:01.185161Z","shell.execute_reply.started":"2024-11-22T10:17:01.154353Z","shell.execute_reply":"2024-11-22T10:17:01.183964Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.1 库导入\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport imageio\nfrom os import listdir\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:01.187098Z","iopub.execute_input":"2024-11-22T10:17:01.187978Z","iopub.status.idle":"2024-11-22T10:17:02.484712Z","shell.execute_reply.started":"2024-11-22T10:17:01.18794Z","shell.execute_reply":"2024-11-22T10:17:02.483493Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys\n\npath = '../input/mlcoursechapter2/chapter2'\ndata_path = '../input/human-protein-atlas-image-classification'\nsys.path.append(path)","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:02.486524Z","iopub.execute_input":"2024-11-22T10:17:02.487197Z","iopub.status.idle":"2024-11-22T10:17:02.49321Z","shell.execute_reply.started":"2024-11-22T10:17:02.487145Z","shell.execute_reply":"2024-11-22T10:17:02.492001Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.2 读入train.csv,观察训练集\ntrain = pd.read_csv(f\"{data_path}/train.csv\")\nprint('训练集维度：{0}'.format(train.shape))\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:02.49602Z","iopub.execute_input":"2024-11-22T10:17:02.496382Z","iopub.status.idle":"2024-11-22T10:17:02.582033Z","shell.execute_reply.started":"2024-11-22T10:17:02.49635Z","shell.execute_reply":"2024-11-22T10:17:02.580963Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.3 的运行时间\nstarttime1 = datetime.datetime.now()","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:02.58334Z","iopub.execute_input":"2024-11-22T10:17:02.583696Z","iopub.status.idle":"2024-11-22T10:17:02.588776Z","shell.execute_reply.started":"2024-11-22T10:17:02.583664Z","shell.execute_reply":"2024-11-22T10:17:02.587524Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.3 train文件夹图像文件名称(目录检索可能需要2分钟时间)\nfiles = listdir(f\"{data_path}/train\")\nprint('train目录下共有 {0} 个图像文件'.format(len(files)))\nfor n in range(8):\n    print(files[n])","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:02.590224Z","iopub.execute_input":"2024-11-22T10:17:02.590636Z","iopub.status.idle":"2024-11-22T10:17:04.264136Z","shell.execute_reply.started":"2024-11-22T10:17:02.59059Z","shell.execute_reply":"2024-11-22T10:17:04.263079Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.3 运行时间\nendtime = datetime.datetime.now()\nprint('# P2.3 运行时长为：{0}秒'.format((endtime - starttime1).seconds))","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:04.265549Z","iopub.execute_input":"2024-11-22T10:17:04.265866Z","iopub.status.idle":"2024-11-22T10:17:04.271277Z","shell.execute_reply.started":"2024-11-22T10:17:04.265833Z","shell.execute_reply":"2024-11-22T10:17:04.270181Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.4 显示指定Id对应的图像\ndef load_image(basepath, image_id):\n    images = np.zeros(shape=(4,512,512))\n    images[0,:,:] = imageio.imread(basepath + image_id + \"_green\" + \".png\")\n    images[1,:,:] = imageio.imread(basepath + image_id + \"_blue\" + \".png\")\n    images[2,:,:] = imageio.imread(basepath + image_id + \"_red\" + \".png\")\n    images[3,:,:] = imageio.imread(basepath + image_id + \"_yellow\" + \".png\")\n    return images\nfig, ax = plt.subplots(1,4,figsize=(20,10))\nimages = load_image(f\"{data_path}/train/\", train['Id'][1])\nax[0].imshow(images[0], cmap=\"Greens\")\nax[1].imshow(images[1], cmap=\"Blues\")\nax[2].imshow(images[2], cmap=\"Reds\")\nax[3].imshow(images[3], cmap=\"Oranges\")","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:04.272529Z","iopub.execute_input":"2024-11-22T10:17:04.272866Z","iopub.status.idle":"2024-11-22T10:17:05.348103Z","shell.execute_reply.started":"2024-11-22T10:17:04.272815Z","shell.execute_reply":"2024-11-22T10:17:05.346707Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"type(train[\"Target\"][0])","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:05.349432Z","iopub.execute_input":"2024-11-22T10:17:05.349754Z","iopub.status.idle":"2024-11-22T10:17:05.356683Z","shell.execute_reply.started":"2024-11-22T10:17:05.349721Z","shell.execute_reply":"2024-11-22T10:17:05.355625Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:05.359296Z","iopub.execute_input":"2024-11-22T10:17:05.359647Z","iopub.status.idle":"2024-11-22T10:17:05.374599Z","shell.execute_reply.started":"2024-11-22T10:17:05.359615Z","shell.execute_reply":"2024-11-22T10:17:05.373312Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"a =5\nnp.array([a]).ndim","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-22T10:17:05.375947Z","iopub.execute_input":"2024-11-22T10:17:05.376343Z","iopub.status.idle":"2024-11-22T10:17:05.388025Z","shell.execute_reply.started":"2024-11-22T10:17:05.37631Z","shell.execute_reply":"2024-11-22T10:17:05.386933Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.5 训练集标签的向量化\nlabel_names = {\n    0:  \"Nucleoplasm\",  \n    1:  \"Nuclear membrane\",   \n    2:  \"Nucleoli\",   \n    3:  \"Nucleoli fibrillar center\",   \n    4:  \"Nuclear speckles\",\n    5:  \"Nuclear bodies\",   \n    6:  \"Endoplasmic reticulum\",   \n    7:  \"Golgi apparatus\",   \n    8:  \"Peroxisomes\",   \n    9:  \"Endosomes\",   \n    10:  \"Lysosomes\",   \n    11:  \"Intermediate filaments\",   \n    12:  \"Actin filaments\",   \n    13:  \"Focal adhesion sites\",   \n    14:  \"Microtubules\",   \n    15:  \"Microtubule ends\",   \n    16:  \"Cytokinetic bridge\",   \n    17:  \"Mitotic spindle\",   \n    18:  \"Microtubule organizing center\",   \n    19:  \"Centrosome\",   \n    20:  \"Lipid droplets\",   \n    21:  \"Plasma membrane\",   \n    22:  \"Cell junctions\",   \n    23:  \"Mitochondria\",   \n    24:  \"Aggresome\",   \n    25:  \"Cytosol\",   \n    26:  \"Cytoplasmic bodies\",   \n    27:  \"Rods & rings\"\n}\ndef fill_targets(row):\n#     print('row\\n ',row)\n    Target = np.array(row.Target.split(\" \")).astype(int)\n\n    # if row.Target.ndim == 0:  # If it's a scalar (0-d array)\n    # if len(row.Target.shape) == 0:\n    #     row.Target = [row.Target]    \n    # print(row.Target)\n    for num in Target:\n        name = label_names[int(num)]\n        row.loc[name] = 1\n    return row\nfor key in label_names.keys():\n    train[label_names[key]] = 0\ntrain = train.apply(fill_targets, axis=1)\ntrain.head(2)","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:31.506527Z","iopub.execute_input":"2024-11-22T10:17:31.506927Z","iopub.status.idle":"2024-11-22T10:17:36.547201Z","shell.execute_reply.started":"2024-11-22T10:17:31.506892Z","shell.execute_reply":"2024-11-22T10:17:36.546022Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.6 测试集标签的向量化\ntest = pd.read_csv(f\"{path}/dataset/test.csv\")\n# test = pd.read_csv(f\"{data_path}/sample_submission.csv\")\nprint('测试集扩增列之前的维度：{0}'.format(test.shape))\nfor col in train.columns.values:\n    if col != \"Id\" and col != \"Target\":\n        test[col] = 0\ntest.head(2)","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:44.714472Z","iopub.execute_input":"2024-11-22T10:17:44.714859Z","iopub.status.idle":"2024-11-22T10:17:44.766137Z","shell.execute_reply.started":"2024-11-22T10:17:44.714827Z","shell.execute_reply":"2024-11-22T10:17:44.764962Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.7 训练集标签样本的分布\ntarget_total = train.drop([\"Id\", \"Target\"],axis=1).sum(axis=0).sort_values(ascending=False)\nplt.figure(figsize = (8,6))\nsns.barplot(x=target_total.values,y=target_total.index.values,order=target_total.index)","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:48.765075Z","iopub.execute_input":"2024-11-22T10:17:48.765447Z","iopub.status.idle":"2024-11-22T10:17:49.247775Z","shell.execute_reply.started":"2024-11-22T10:17:48.765412Z","shell.execute_reply":"2024-11-22T10:17:49.246694Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.8 筛选标签集\nfilter_target = pd.DataFrame(target_total)\nfilter_target.rename(columns = {0:'counts'}, inplace=True)\nfilter_target = filter_target[filter_target.counts.between(1000,1500)]\nfilter_target","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:51.98269Z","iopub.execute_input":"2024-11-22T10:17:51.983114Z","iopub.status.idle":"2024-11-22T10:17:51.994706Z","shell.execute_reply.started":"2024-11-22T10:17:51.983075Z","shell.execute_reply":"2024-11-22T10:17:51.993593Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.9 训练集筛选重构\nfilter_columns = filter_target.index.insert(0,'Id')\nfilter_columns = filter_columns.insert(1,'Target')\nfilter_train = train[train[filter_target.index].sum(axis=1)>0][filter_columns]\nprint('筛选训练集的维数为：{0}'.format(filter_train.shape))\nfilter_train.head(3)","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:17:56.399241Z","iopub.execute_input":"2024-11-22T10:17:56.39976Z","iopub.status.idle":"2024-11-22T10:17:56.42998Z","shell.execute_reply.started":"2024-11-22T10:17:56.399706Z","shell.execute_reply":"2024-11-22T10:17:56.428671Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"filter_train['target_count'] = filter_train[filter_target.index].sum(axis=1)\ncount_percent = np.round(100 * filter_train[\"target_count\"].value_counts() / filter_train.shape[0], 2)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-22T10:18:00.908355Z","iopub.execute_input":"2024-11-22T10:18:00.908727Z","iopub.status.idle":"2024-11-22T10:18:00.922429Z","shell.execute_reply.started":"2024-11-22T10:18:00.908696Z","shell.execute_reply":"2024-11-22T10:18:00.92125Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index,row in pd.DataFrame(count_percent).iterrows():\n    print(row['count'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-22T10:54:49.461481Z","iopub.execute_input":"2024-11-22T10:54:49.461892Z","iopub.status.idle":"2024-11-22T10:54:49.468291Z","shell.execute_reply.started":"2024-11-22T10:54:49.461854Z","shell.execute_reply":"2024-11-22T10:54:49.467139Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.10 新训练集的标签数量分类统计\nplt.figure(figsize=(6,4))\ng = sns.barplot(x=count_percent.index.values, y=count_percent.values, palette=\"Reds\")\nplt.ylabel(\"% of train data\")\nfor index,row in pd.DataFrame(count_percent).iterrows():\n    g.text(row.name-1,row['count']/2+5,row['count'],color=\"black\",ha=\"center\")","metadata":{"execution":{"iopub.status.busy":"2024-11-22T10:54:32.714135Z","iopub.execute_input":"2024-11-22T10:54:32.714493Z","iopub.status.idle":"2024-11-22T10:54:32.856724Z","shell.execute_reply.started":"2024-11-22T10:54:32.714463Z","shell.execute_reply":"2024-11-22T10:54:32.855575Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.11 删除含有两种标签的样本\nfilter_train = filter_train[filter_train['target_count'] < 2]\nfilter_train.reset_index(drop=True,inplace=True)\nfilter_train.drop(['Target','target_count'],axis=1,inplace=True)\nprint(filter_train.shape)\nfilter_train.head(3)","metadata":{"scrolled":true,"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"filter_train.columns","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.12 创建特征矩阵 X 和标签矩阵 Y\nX = filter_train['Id'].values.reshape(-1,1)\nY = filter_train[filter_target.index].values\nprint(X.shape)\nprint(Y.shape)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"filter_target.index","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.13 训练集划分为训练与验证两部分\nfrom sklearn.model_selection import train_test_split\nx_train, x_val, Y_train, Y_val = train_test_split(X, Y, test_size = .33, random_state=0, stratify=Y)\nprint('训练集的特征维度：{0}，标签维度：{1}'.format(x_train.shape,Y_train.shape))\nprint('验证集的特征维度：{0}，标签维度：{1}'.format(x_val.shape,Y_val.shape))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.14 加载并显示绿色通道的图片\ndef load_green_image(basepath, image_id):\n    image = np.zeros(shape=(512,512))\n    image[:,:] = imageio.imread(basepath + image_id + \"_green\" + \".png\")\n    return image\nfig = plt.figure()\nimage = load_green_image(f\"{data_path}/train/\", x_train[0][0])\nplt.imshow(image, cmap='gray')\nprint(image.shape)\nx = image[:,:,np.newaxis]\nprint(x.shape)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.15 的启动时间\nstarttime2 = datetime.datetime.now()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.15 创建训练集的特征矩阵X_train\nm = x_train.shape[0]\nX_train = np.zeros((m,x.shape[0],x.shape[1],x.shape[2]))\nfor i in range(m):\n    image = load_green_image(f\"{data_path}/train/\", x_train[i][0])\n    image = image[:,:,np.newaxis]\n    X_train[i][:][:][:] = image\nprint(X_train.shape)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.15 结束时间\nendtime = datetime.datetime.now()\nprint('# P2.15 运行时长为：{0}秒'.format((endtime - starttime2).seconds))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.16 的启动时间\nstarttime3 = datetime.datetime.now()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.16 创建验证集的特征矩阵X_val\nm = x_val.shape[0]\nX_val = np.zeros((m,x.shape[0],x.shape[1],x.shape[2]))\nfor i in range(m):\n    image = load_green_image(f\"{data_path}/train/\", x_val[i][0])\n    image = image[:,:,np.newaxis]\n    X_val[i][:][:][:] = image\nprint(X_val.shape)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.16 结束时间\nendtime = datetime.datetime.now()\nprint('# P2.16 运行时长为：{0}秒'.format((endtime - starttime3).seconds))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.17 启动时间\nstarttime4 = datetime.datetime.now()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.17 特征矩阵的标准化\nX_train = X_train / 255.\nX_val = X_val / 255.\nprint(X_train.shape)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.17 结束时间\nendtime = datetime.datetime.now()\nprint('# P2.17 运行时长为：{0}秒'.format((endtime - starttime4).seconds))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"###### P2.18 自定义CNN模型\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\n# 自定义 CNN 模型\nmodel = Sequential(name=\"Protein_Model\")\n# Layer1：卷积\nmodel.add(Conv2D(16, (3, 3), padding='same', activation='relu', input_shape=(512, 512, 1)))\n# 最大池化\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# Layer2：卷积\nmodel.add(Conv2D(32, (3, 3), padding='same', activation='relu'))\n# 最大池化\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# Layer3：卷积\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\n# 最大池化\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# Layer4：卷积\nmodel.add(Conv2D(96, (3, 3), padding='same', activation='relu'))\n# 最大池化\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# Layer5：卷积\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\n# 最大池化\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# Layer6：卷积\nmodel.add(Conv2D(160, (3, 3), padding='same', activation='relu'))\n# 最大池化\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# Layer7：卷积\nmodel.add(Conv2D(192, (3, 3), padding='same', activation='relu'))\n# 最大池化\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# 展开为向量\nmodel.add(Flatten())\n# Layer8：全连接\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dropout(0.25))\n# Layer9：全连接\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dropout(0.25))\n# Layer10：Softmax 分类\nmodel.add(Dense(5, activation='softmax'))\nmodel.summary()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.19 模型编译\nmodel.compile(optimizer='rmsprop',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.20 启动时间\nstarttime5 = datetime.datetime.now()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.20 模型训练\nepochs = 10\nbatch_size = 32\nhistory = model.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, \n                    validation_data=(X_val,Y_val))\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.20 结束时间\nendtime = datetime.datetime.now()\nprint('# P2.20 运行时长为：{0}秒'.format((endtime - starttime5).seconds))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.21 训练集和验证集上的趋势对比\nx = range(1, len(history.history['accuracy'])+1)\nplt.plot(x, history.history['accuracy'])\nplt.plot(x, history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.xticks(x)\nplt.legend(['Train', 'Val'], loc='upper left')\nplt.show()\nplt.plot(x, history.history['loss'])\nplt.plot(x, history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.xticks(x)\nplt.legend(['Train', 'Val'], loc='lower left')\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nsave_dir = os.path.join(os.getcwd(), 'saved_models')\nif not os.path.isdir(save_dir):\n    os.makedirs(save_dir)\nprint(save_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-22T10:56:23.007072Z","iopub.execute_input":"2024-11-22T10:56:23.007449Z","iopub.status.idle":"2024-11-22T10:56:23.014069Z","shell.execute_reply.started":"2024-11-22T10:56:23.007418Z","shell.execute_reply":"2024-11-22T10:56:23.012752Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.22 保存模型\nimport os\nsave_dir = os.path.join(os.getcwd(), 'saved_models')\nif not os.path.isdir(save_dir):\n    os.makedirs(save_dir)\nmodel_path = os.path.join(save_dir, model.name + '.keras')\nmodel.save(model_path)\nprint('训练模型保存到： %s ' % model_path)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# P2.23 加载模型，检验预测效果\nfrom keras.models import load_model\n\nProtein_Model = load_model(f\"{path}/saved_models/Protein_Model\" + '.keras')  #加载模型\n#随机指定一幅测试图像\nimg_path = f\"{data_path}/train/000a6c98-bb9b-11e8-b2b9-ac1f6b6435d0_green.png\"  \nimg = imageio.imread(img_path)\nplt.imshow(img)  #显示原图\ntrain = pd.read_csv(f\"{data_path}/train.csv\")\nindex = train[train.Id == '000a6c98-bb9b-11e8-b2b9-ac1f6b6435d0']['Target'].values\nindex = index[0].split(' ')\nfor i in index:\n    print('真实的标签为：{0}'.format(label_names[int(i)])) \nx = np.expand_dims(img, axis=2)\nx = np.expand_dims(x, axis=0)\npred = Protein_Model.predict(x)  #模型预测\ni = np.argmax(pred)\npred_labels = filter_target.index\nprint('模型预测的标签为：{0}'.format(pred_labels[i]))\ntrain.head()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 整个项目运行时间\nendtime = datetime.datetime.now()\nprint('# 整个项目运行时长为：{0}秒'.format((endtime - starttime).seconds))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}