File size: 4,780 Bytes
3ff78d4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | {
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "177faf3e-cec4-4a9f-a613-4c8838af30c1",
"metadata": {},
"outputs": [],
"source": [
"#No keras existem os modelos de redes neurais estaticos, funcionais e dinamicmos. Neste notebook lidaresmos com dinamico"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ef8dbd4c-3443-4a5f-b8e1-99b6f0d958b6",
"metadata": {},
"outputs": [],
"source": [
"from sklearn.datasets import fetch_california_housing\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.preprocessing import StandardScaler\n",
"\n",
"import numpy as np\n",
"import tensorflow as tf\n",
"from tensorflow import keras\n",
"import pandas as pd\n",
"import matplotlib\n",
"matplotlib.use(\"TkAgg\")\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "09438fbc-8705-4712-8111-078a22cf8d1d",
"metadata": {},
"outputs": [],
"source": [
"housing = fetch_california_housing()\n",
"x_train_full, x_test, y_train_full, y_test = train_test_split(housing.data,housing.target)\n",
"x_train, x_valid, y_train, y_valid = train_test_split(x_train_full, y_train_full)\n",
"\n",
"scaler=StandardScaler()\n",
"x_train = scaler.fit_transform(x_train)\n",
"x_valid = scaler.transform(x_valid)\n",
"x_test=scaler.transform(x_test)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0e80a374-8f22-40cd-ad12-f15898142f6b",
"metadata": {},
"outputs": [],
"source": [
"class WideAndDeepModel(keras.Model):\n",
" def __init__(self, units=30, activation=\"relu\", **kwargs):\n",
" super().__init__(**kwargs) \n",
" self.hidden1 = keras.layers.Dense(units, activation=activation)\n",
" self.hidden2 = keras.layers.Dense(units, activation=activation)\n",
" self.main_output = keras.layers.Dense(1)\n",
" self.aux_output = keras.layers.Dense(1)\n",
" def call(self, inputs):\n",
" input_A, input_B = inputs\n",
" hidden1 = self.hidden1(input_B)\n",
" hidden2 = self.hidden2(hidden1)\n",
" concat = keras.layers.concatenate([input_A, hidden2])\n",
" main_output = self.main_output(concat)\n",
" aux_output = self.aux_output(hidden2)\n",
" return main_output, aux_output"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3a81c2b8-4e95-453a-8d1a-4ba132bd483b",
"metadata": {},
"outputs": [],
"source": [
"model = WideAndDeepModel()\n",
"\n",
"model.compile(\n",
" loss=[\"mse\", \"mse\"], # uma loss para cada saída\n",
" optimizer=keras.optimizers.SGD(learning_rate=1e-3),\n",
" loss_weights=[0.8, 0.2] # opcional: peso de cada saída\n",
")\n",
"\n",
"# Os targets precisam ser tuplas/listas correspondentes às saídas\n",
"history = model.fit(\n",
" (x_train_A, x_train_B), # entradas\n",
" (y_train, y_train), # targets: main_output e aux_output\n",
" epochs=20,\n",
" validation_data=((x_valid_A, x_valid_B), (y_valid, y_valid))\n",
")\n",
"\n",
"# Avaliar\n",
"mse_test = model.evaluate((x_test_A, x_test_B), (y_test, y_test))\n",
"\n",
"# Predição\n",
"y_pred_main, y_pred_aux = model.predict((x_new_A, x_new_B))\n",
"print(y_pred_main)\n",
"\n",
"model.save(\"my_keras_model.h5\") #Salvando modelo, legal isso"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "044977e1-310c-4f39-9e46-303c86bfbd0f",
"metadata": {},
"outputs": [],
"source": [
"model = keras.models.load_model(\"my_keras_model.h5\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "079566ef-1c0c-400a-aeba-253ba01d1d5c",
"metadata": {},
"outputs": [],
"source": [
"checkpoint_cb = keras.callbacs.ModelCheckpoint(\"my_keras_model.h5\")\n",
"history = model.fit(x_train, y_train, epochs = 10, callbacks = [checkpoint_cb])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8b95335e-9efc-44d9-8b6f-9cf8c6929dc7",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|