Variable
import tensorflow as tf
import numpy as np
Variable(변수)
- 미지수, 가중치를 정의할 때 사용
- 직접 사용할 일이 많지는 않음
- 변수 정의는 변수 생성 + 초기화
tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
arr = np.array([[1, 2], [3, 4]])
li = [[1, 2], [3, 4]]
te_var = tf.Variable(tensor)
arr_var = tf.Variable(arr)
li_var = tf.Variable(li)
print(te_var)
print(arr_var)
print(li_var)
<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=
array([[1., 2.],
[3., 4.]], dtype=float32)>
<tf.Variable 'Variable:0' shape=(2, 2) dtype=int32, numpy=
array([[1, 2],
[3, 4]])>
<tf.Variable 'Variable:0' shape=(2, 2) dtype=int32, numpy=
array([[1, 2],
[3, 4]])>
print('Shape: ', te_var.shape)
print('DType: ', te_var.dtype)
print('As NumPy: ', te_var.numpy())
Shape: (2, 2)
DType: <dtype: 'float32'>
As NumPy: [[1. 2.]
[3. 4.]]
변수는 기존 텐서의 메모리를 재사용하여 텐서를 재할당 할 수 있다.
a = tf.Variable([2.0, 3.0])
print('First : ', a, '\n')
a.assign([1, 2])
print('Second : ', a, '\n')
First : <tf.Variable 'Variable:0' shape=(2,) dtype=float32, numpy=array([2., 3.], dtype=float32)>
Second : <tf.Variable 'Variable:0' shape=(2,) dtype=float32, numpy=array([1., 2.], dtype=float32)>
a.assign([1.0, 2.0, 3.0])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-3250ace3a972> in <module>
1 # 기존 메모리의 크기와 다르면 할당 할 수 없음!
----> 2 a.assign([1.0, 2.0, 3.0])
c:\Users\theo\miniconda3\envs\ds_study\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py in assign(self, value, use_locking, name, read_value)
909 else:
910 tensor_name = " " + str(self.name)
--> 911 raise ValueError(
912 (f"Cannot assign value to variable '{tensor_name}': Shape mismatch."
913 f"The variable shape {self._shape}, and the "
ValueError: Cannot assign value to variable ' Variable:0': Shape mismatch.The variable shape (2,), and the assigned value shape (3,) are incompatible.