t_1 = tf.constant(2)
t_2 = tf.constant(2)
t_add = tf.add(t_1,t_2)
t_3 = tf.constant([4,3,2])
zeros = tf.zeros(shape=[3,3])
ones = tf.ones(shape=[3,3])

bias1=tf.Variable(2)
bias2=tf.Variable(initial_value=3.)

a = tf.constant([[1.0,2.0],[3.0,4.0]])
print(a.shape)
print(a.dtype)
print(a.numpy())

print(tf.add(1, 2))
print(tf.add([1, 2], [3, 4]))
print(tf.matmul([[1,2,3]],[[4],[5],[6]]))
print(tf.square(5))
print(tf.pow(2,3))
print(tf.square(2) + tf.square(3))
print(tf.reduce_sum([1,2,3]))
print(tf.reduce_mean([1,2,3]))

# ①取最大索引
print(tf.argmax([1,0,0,8,6]))

# ②扩张维度
a=tf.constant([[1,2],[3,4],[5,6]])
b=tf.expand_dims(a,0)
c=tf.expand_dims(a,1)
print(a.shape,b.shape,c.shape)

# ③张量拼接
x=[[1,2,3],[4,5,6],[7,8,9]]
y=[[2,3,4],[5,6,7],[8,9,10]]
z1=tf.concat([x,y],axis=0)
z2=tf.concat([x,y],axis=1)
print(z1,z2)
4.
a = tf.Variable([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
b = tf.reshape(a,[6,2])
print(a.numpy(),'\n',b.numpy())

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

input_x = np.float32(np.linspace(-1,1,100))
input_y = 2*input_x + np.random.randn(*input_x.shape)*0.3

weight = tf.Variable(1.,dtype=tf.float32,name='weight')
bias = tf.Variable(1.,dtype=tf.float32,name='bias')

def model(x):
    pred = tf.multiply(x,weight) + bias
    return pred

opt=tf.optimizers.Adam(1e-1)
step=0
for x,y in zip(input_x,input_y):
    x = np.reshape(x,[1,1])
    y = np.reshape(y,[1,1])
    with tf.GradientTape() as tape:
        loss = tf.losses.MeanSquaredError()(model(x),y)
    grads=tape.gradient(loss,[weight,bias])
    opt.apply_gradients(zip(grads,[weight,bias]))
    step +=1

print("Step:",step,"Traing Loss:",loss.numpy())
plt.plot(input_x,input_y,'ro',label='original data')
plt.plot(input_x,model(input_x),label='predicted value')
plt.plot(input_x,2*input_x,label='y = 2x')
plt.legend()
plt.show()
print(weight)
print(bias)


