텐서의 크기를 매우 크게 늘리고 싶을 때 shape을 사용하면 손쉽게 할 수 있습니다.
t2=tf.ones(shape=(100,))
print(t2)
t3=tf.ones(shape=(100,3,3))
print(t3)
t4=tf.zeros(shape=(100,3,3))
print(t3)
t2와 t3는 1이 채워진 100x1, 100x3x3텐서입니다.
t4는 0이 채워진 100x3x3 텐서입니다.
만약 다른 숫자로 텐서를 채우고 싶다면
t5 = 3*tf.ones(shape=(128,128,3))
ones 앞에 원하는 숫자를 곱해주면 됩니다.
t5는 3이 채워져 있는 128x128x3 텐서입니다.
test_list2=[[1,2,3],[4,5,6]]
t1=tf.Variable(test_list2)
print(t1)
t2 = tf.ones_like(t1)
print(t2)
t3=tf.zeros_like(t1)
print(t3)
ones_like, zero_like는 이미 만들어져 있는 텐서의 shape대로 행렬을 만들어줍니다.
데이터를 만들 때는 random을 자주 사용합니다.
#randonm effect를 줄이고 같은 결과를 사용하고 싶을 때 seed 사용
np.random.seed(0)
tf.random.set_seed(0)
t1=tf.random.normal(shape=(10,10))
random으로 데이터를 만들 때, 평균과 분산을 정해서 분포를 그려보겠습니다.
import matplotlib.pyplot as plt
t2=tf.random.normal(mean=3,stddev= 1,shape=(1000,1))
fig, ax = plt.subplots(figsize=(5,5))
ax.hist(t2.numpy(), bins=30)
t2=tf.random.uniform(shape=(10000,),minval=-10,maxval=10)
fig, ax = plt.subplots(figsize=(5,5))
ax.hist(t2.numpy(), bins=30)
t2=tf.random.poisson(shape=(100000,),lam=5)
fig, ax = plt.subplots(figsize=(5,5))
ax.hist(t2.numpy(), bins=30)
만들어진 텐서의 shape 정보와 type 정보를 알아보겠습니다.
t1=tf.random.normal(shape=(128,128,3))
print("t1.shape: ", t1.shape)
print("t1.dtype: ",t1.dtype)
t1.shape: (128, 128, 3)
t1.dtype: <dtype: 'float32'>
numpy에서 int형으로 random하게 만드는 ranint를 사용하면 int형 행렬이 만들어집니다. 이 행렬을 텐서로 바꿔도 int형입니다. 따라서 텐서플로우에서 잘 실행이 되지 않을 수 있습니다.
텐서의 타입을 바꿔주려면 dtype을 설정하면 됩니다.
test_np=np.random.randint(-10,10,size=(100,))
print(test_np.dtype) #int형
t1= tf.constant(test_np)
print(t1.dtype) #int형 -> tesnsorflow에서 실행이 잘 안될수도 있음
t1= tf.constant(test_np,dtype=tf.float32)
print(t1.dtype)
int64
<dtype: 'int64'>
<dtype: 'float32'>
'AI > Tensorflow' 카테고리의 다른 글
3. Tensor Operations (0) | 2022.05.06 |
---|---|
1.Constant Tensor & Variable Tensor (0) | 2022.04.27 |