2.
import tensorflow as tf
print(tf.__version__)
a = tf.constant(2.0)
print(a)


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)

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())


3.
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)


4.
import tensorflow as tf
import numpy as np
from sklearn.datasets import load_iris

data = load_iris()
iris_data = np.float32(data.data)
iris_target = data.target
iris_target = tf.keras.utils.to_categorical(iris_target,num_classes=3)
train_data = tf.data.Dataset.from_tensor_slices((iris_data,iris_target)).batch(128)
inputs = tf.keras.layers.Input(shape=(4,))
x = tf.keras.layers.Dense(32,activation='relu')(inputs)
x = tf.keras.layers.Dense(64,activation='relu')(x)
outputs = tf.keras.layers.Dense(3,activation='softmax')(x)

model = tf.keras.Model(inputs=inputs,outputs=outputs)
model.compile(optimizer=tf.optimizers.Adam(lr=1e-3),loss=tf.losses.categorical_crossentropy,metrics=['accuracy'])
model.fit(train_data,epochs=500)
score = model.evaluate(iris_data,iris_target)
print("last score:",score)