{"id":36441,"date":"2024-11-01T09:48:32","date_gmt":"2024-11-01T09:48:32","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=36441"},"modified":"2024-11-01T11:53:09","modified_gmt":"2024-11-01T11:53:09","slug":"deep-learning-pytorch-course-gru-structure","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/36441\/","title":{"rendered":"Deep Learning PyTorch Course, GRU Structure"},"content":{"rendered":"<p><body><\/p>\n<p>The advancement of deep learning is based on innovations in various network architectures, including Recurrent Neural Networks (RNN). In particular, the Gated Recurrent Unit (GRU) is a simple yet powerful type of RNN that performs exceptionally well in fields like time series data and Natural Language Processing (NLP). In this content, we will take a detailed look at the structure, operation principles, and code examples using PyTorch for GRU.<\/p>\n<h2>1. What is GRU?<\/h2>\n<p>GRU is a variant model of recurrent neural networks proposed by Kyunghyun Cho in 2014, which has many similarities with Long Short-Term Memory (LSTM). However, GRU is composed of a simpler structure, has fewer neurons, and allows for easier computations, leading to faster training speeds. GRU uses two gates to control the flow of information: the update gate and the reset gate.<\/p>\n<h2>2. Structure of GRU<\/h2>\n<p>The structure of GRU is composed as follows:<\/p>\n<ul>\n<li><strong>Input (x)<\/strong>: The input vector at the current time step<\/li>\n<li><strong>State (h)<\/strong>: The state vector from the previous time step<\/li>\n<li><strong>Update Gate (z)<\/strong>: Determines how much of the new information and the existing information to reflect<\/li>\n<li><strong>Reset Gate (r)<\/strong>: Determines how much of the previous state to ignore<\/li>\n<li><strong>Candidate State (h~)<\/strong>: The candidate state for calculating the new state<\/li>\n<\/ul>\n<h2>3. Mathematical Representation of GRU<\/h2>\n<p>The main equations of GRU are as follows:<\/p>\n<pre class=\"code\">\nz_t = \u03c3(W_z * x_t + U_z * h_{t-1})\nr_t = \u03c3(W_r * x_t + U_r * h_{t-1})\nh~_t = tanh(W_h * x_t + U_h * (r_t * h_{t-1}))\nh_t = (1 - z_t) * h_{t-1} + z_t * h~_t\n<\/pre>\n<p>Where:<\/p>\n<ul>\n<li>\u03c3 is the sigmoid function<\/li>\n<li>tanh is the hyperbolic tangent function<\/li>\n<li>W and U represent the weight matrices<\/li>\n<li>t denotes the current time step, and t-1 denotes the previous time step<\/li>\n<\/ul>\n<h2>4. Advantages of GRU<\/h2>\n<p>GRU has the following advantages:<\/p>\n<ul>\n<li>The system is relatively simple, making experimentation and application easy.<\/li>\n<li>It has fewer required parameters and fast computation speeds.<\/li>\n<li>It delivers performance similar to LSTM across various scenarios.<\/li>\n<\/ul>\n<h2>5. Implementing GRU with PyTorch<\/h2>\n<p>Now let&#8217;s implement the GRU model using PyTorch. In the example below, we will create a simple time series prediction model.<\/p>\n<h3>5.1 Data Preparation<\/h3>\n<p>For a quick example, we will use the values of the sine function as time series data. The model will learn to predict the next value based on the previous sequence values.<\/p>\n<pre class=\"code\">\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\n\n# Generate time series data\ndef generate_data(seq_length):\n    x = np.linspace(0, 100, seq_length)\n    y = np.sin(x) + np.random.normal(scale=0.1, size=seq_length)  # Adding noise\n    return y\n\n# Convert data into sequences\ndef create_sequences(data, seq_length):\n    sequences = []\n    labels = []\n    \n    for i in range(len(data) - seq_length):\n        sequences.append(data[i:i + seq_length])\n        labels.append(data[i + seq_length])\n    \n    return np.array(sequences), np.array(labels)\n\n# Generate and prepare data\ndata = generate_data(200)\nseq_length = 10\nX, y = create_sequences(data, seq_length)\n\n# Check the data\nprint(\"X shape:\", X.shape)\nprint(\"y shape:\", y.shape)\n<\/pre>\n<h3>5.2 Defining the GRU Model<\/h3>\n<p>To define the GRU model, we will create a GRU class that inherits from PyTorch&#8217;s nn.Module class.<\/p>\n<pre class=\"code\">\nclass GRUModel(nn.Module):\n    def __init__(self, input_size, hidden_size):\n        super(GRUModel, self).__init__()\n        self.gru = nn.GRU(input_size, hidden_size, batch_first=True)\n        self.fc = nn.Linear(hidden_size, 1)\n    \n    def forward(self, x):\n        out, _ = self.gru(x)\n        out = self.fc(out[:, -1, :])  # Use only the last output\n        return out\n\n# Initialize the model\ninput_size = 1  # Input data dimension\nhidden_size = 16  # Size of the hidden layer in GRU\nmodel = GRUModel(input_size, hidden_size)\n<\/pre>\n<h3>5.3 Model Training<\/h3>\n<p>To train the model, we will define the loss function and optimization algorithm, and implement the training loop.<\/p>\n<pre class=\"code\">\n# Loss function and optimization algorithm\ncriterion = nn.MSELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\n# Convert data to tensor\nX_tensor = torch.FloatTensor(X).unsqueeze(-1)  # (batch_size, seq_length, input_size)\ny_tensor = torch.FloatTensor(y).unsqueeze(-1)  # (batch_size, 1)\n\n# Train the model\nnum_epochs = 200\nfor epoch in range(num_epochs):\n    model.train()\n    \n    optimizer.zero_grad()\n    outputs = model(X_tensor)\n    loss = criterion(outputs, y_tensor)\n    loss.backward()\n    optimizer.step()\n    \n    if (epoch + 1) % 20 == 0:\n        print(f'Epoch [{epoch+1}\/{num_epochs}], Loss: {loss.item():.4f}')\n<\/pre>\n<h3>5.4 Model Evaluation and Prediction<\/h3>\n<p>After training the model, we will visualize the prediction results.<\/p>\n<pre class=\"code\">\n# Evaluate the model\nmodel.eval()\nwith torch.no_grad():\n    predicted = model(X_tensor).numpy()\n    \n# Visualize prediction results\nplt.figure(figsize=(12, 5))\nplt.plot(data, label='Original Data')\nplt.plot(np.arange(seq_length, len(predicted) + seq_length), predicted, label='Predicted', color='red')\nplt.legend()\nplt.show()\n<\/pre>\n<h2>6. Conclusion<\/h2>\n<p>In this tutorial, we explored the basic structure and operational principles of the Gated Recurrent Unit (GRU), and detailed the process of implementing a GRU model using PyTorch. GRU is a model that is simple yet has many potential applications, widely used in areas such as Natural Language Processing and time series prediction.<\/p>\n<p>In the future, we hope to continue research on optimizing deep learning models by utilizing GRU in various ways.<\/p>\n<h2>7. References<\/h2>\n<ul>\n<li>Cho, K., Merrienboer, B., Gulcehre, C., et al. (2014). Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation.<\/li>\n<li>Sutskever, I., Vinyals, O., &amp; Le, Q. V. (2014). Sequence to Sequence Learning with Neural Networks.<\/li>\n<\/ul>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The advancement of deep learning is based on innovations in various network architectures, including Recurrent Neural Networks (RNN). In particular, the Gated Recurrent Unit (GRU) is a simple yet powerful type of RNN that performs exceptionally well in fields like time series data and Natural Language Processing (NLP). In this content, we will take a &hellip; <a href=\"https:\/\/atmokpo.com\/w\/36441\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Deep Learning PyTorch Course, GRU Structure&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[149],"tags":[],"class_list":["post-36441","post","type-post","status-publish","format-standard","hentry","category-pytorch-study"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Deep Learning PyTorch Course, GRU Structure - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/36441\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Deep Learning PyTorch Course, GRU Structure - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"The advancement of deep learning is based on innovations in various network architectures, including Recurrent Neural Networks (RNN). In particular, the Gated Recurrent Unit (GRU) is a simple yet powerful type of RNN that performs exceptionally well in fields like time series data and Natural Language Processing (NLP). In this content, we will take a &hellip; \ub354 \ubcf4\uae30 &quot;Deep Learning PyTorch Course, GRU Structure&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/36441\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:48:32+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:53:09+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/36441\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36441\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Deep Learning PyTorch Course, GRU Structure\",\"datePublished\":\"2024-11-01T09:48:32+00:00\",\"dateModified\":\"2024-11-01T11:53:09+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36441\/\"},\"wordCount\":512,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"PyTorch Study\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/36441\/\",\"url\":\"https:\/\/atmokpo.com\/w\/36441\/\",\"name\":\"Deep Learning PyTorch Course, GRU Structure - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:48:32+00:00\",\"dateModified\":\"2024-11-01T11:53:09+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36441\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/36441\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/36441\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Deep Learning PyTorch Course, GRU Structure\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Deep Learning PyTorch Course, GRU Structure - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/36441\/","og_locale":"ko_KR","og_type":"article","og_title":"Deep Learning PyTorch Course, GRU Structure - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"The advancement of deep learning is based on innovations in various network architectures, including Recurrent Neural Networks (RNN). In particular, the Gated Recurrent Unit (GRU) is a simple yet powerful type of RNN that performs exceptionally well in fields like time series data and Natural Language Processing (NLP). In this content, we will take a &hellip; \ub354 \ubcf4\uae30 \"Deep Learning PyTorch Course, GRU Structure\"","og_url":"https:\/\/atmokpo.com\/w\/36441\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:48:32+00:00","article_modified_time":"2024-11-01T11:53:09+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/36441\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/36441\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Deep Learning PyTorch Course, GRU Structure","datePublished":"2024-11-01T09:48:32+00:00","dateModified":"2024-11-01T11:53:09+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/36441\/"},"wordCount":512,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["PyTorch Study"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/36441\/","url":"https:\/\/atmokpo.com\/w\/36441\/","name":"Deep Learning PyTorch Course, GRU Structure - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:48:32+00:00","dateModified":"2024-11-01T11:53:09+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/36441\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/36441\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/36441\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Deep Learning PyTorch Course, GRU Structure"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36441","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=36441"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36441\/revisions"}],"predecessor-version":[{"id":36442,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36441\/revisions\/36442"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=36441"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=36441"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=36441"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}