<jupyter_start><jupyter_text>**`Introduction to TensorFlow 2.0 - Tensors, AutoGraph, Decorator and Keras API `**<jupyter_code># 1-D Tensor Object of integer type from a python list.
import tensorflow as tf
tf.constant([10, 22, 43, 34,6],dtype=tf.int32)
# 2-D Tensor Object of float type from a python list.
tf.constant([[10, 22, 43, 34,6], [23,10,34,55,8]],dtype=tf.float32)
import tensorflow as tf
#print current version of TensorFlow
print("Running Version-",tf.__version__)
#TensorFlow 1.x version for Hello World
var=tf.constant("Hello, World")
mysession = tf.Session()
print(mysession.run(var)) 
!pip install --upgrade tensorflow
import tensorflow as tf
#print current version of TensorFlow
print("Running Version-",tf.__version__)
#TensorFlow 2.x version for Hello World
var=tf.constant("Hello, World")
tf.print(var)
from math import pi
import tensorflow as tf
@tf.function
def getarea(rad):
  area=pi*rad** 2
  return area
tf.print("Area of Circle=",getarea(3)) 
import tensorflow as tf
@tf.function
def gettableof(num):
  for i in range(1,11):
   tf.print(i*num, end=" ")

gettableof(2) 
import tensorflow as tf
#function-declaration
@tf.function
def evenodd(num):
  if num%2==0:
     tf.print("Its Even Number")
  else:
     tf.print("Its Odd Number")
#call-to-function
evenodd(17)
import tensorflow as tf
#function-declaration
@tf.function
def evenodd(num):
    if num%2==0:
       tf.print("Its Even Number")
    else:
       tf.print("Its Odd Number")
#call-to-function
evenodd(17)
# AutoGraph- Normal python to graph code generation
print(tf.autograph.to_code(evenodd.python_function))<jupyter_output>Its Odd Number
def tf__evenodd(num):
  with ag__.FunctionScope('evenodd', 'fscope', ag__.ConversionOptions(recursive=True, user_requested=True, optional_features=(), internal_convert_user_code=True)) as fscope:

    def get_state():
      return ()

    def set_state(_):
      pass

    def if_true():
      ag__.converted_call(tf.print, ('Its Even Number',), None, fscope)
      return ag__.match_staging_level(1, cond)

    def if_false():
      ag__.converted_call(tf.print, ('Its Odd Number',), None, fscope)
      return ag__.match_staging_level(1, cond)
    cond = num % 2 == 0
    ag__.if_stmt(cond, if_true, if_false, get_state, set_state, (), ())<jupyter_text>**Practical Implementation of Artificial Neural Network with TensorFlow 2.0**<jupyter_code>import tensorflow as tf
print(tf.__version__)
import tensorflow as tf
auto_dataset = tf.keras.utils.get_file("uci-mileage.data","http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data")
print(auto_dataset)
import pandas as pd
attribute_names = ['MPG','Cylinders','Displacement','Horsepower','Weight','Acceleration', 'Model Year', 'Origin']
first_df = pd.read_csv(auto_dataset, names=attribute_names,delimiter=" ", skipinitialspace=True, comment="\t")

#generate a copy a dataset
working_data = first_df.copy()

#print last 8 records from a dataset - from tail-side
working_data.tail(8)
working_data.isnull().sum()
working_data['Origin'] = working_data['Origin'].map(lambda x:{1: 'USA', 2: 'Europe', 3: 'Japan'}.get(x))
origin_data=pd.get_dummies(working_data.Origin, prefix='',prefix_sep='')
working_data= working_data.drop('Origin', axis=1)
working_data=working_data.join(origin_data)
working_data.tail(8)
working_data.corr()
#correlation heatmap with Seaborn
import seaborn as sns
sns.heatmap(working_data.corr())
working_data=working_data[['MPG','Cylinders','Displacement','Weight']]
print(working_data)

train_data=working_data.sample(frac=0.8,random_state=0)
test_data = working_data.drop(train_data.index)
print(train_data.head())
print(test_data.head())
#summary statistics
train_summary_stats = train_data.describe()
train_summary_stats.pop("MPG")
train_summary_stats=train_summary_stats.transpose()
print(train_summary_stats)
print("Shape of Train Dataset(rows,cols)-",train_data.shape)
print("Shape of Test Dataset(rows,cols)-",test_data.shape)
train_target= train_data.pop('MPG')
test_target = test_data.pop('MPG')
def normalize(t):
  return ((t)-train_summary_stats['mean'])/train_summary_stats['std']
  
normal_train_data=normalize(train_data)
normal_test_data=normalize(test_data)
normal_train_data
normal_test_data
test_data.isna().sum()
import tensorflow as tf
from tensorflow.keras import layers
input_shape_model = len(normal_train_data.keys())
nn_model=tf.keras.Sequential([layers.Dense(64,activation='relu',input_shape=[input_shape_model]),layers.Dense(64, activation='relu'),layers.Dense(1)])
optimizer = tf.keras.optimizers.RMSprop(0.001)
nn_model.compile(loss='mse',optimizer=optimizer,metrics=['mae', 'mse'])

nn_model.summary()
no_epochs = 1000
ready = nn_model.fit(normal_train_data,train_target,epochs=no_epochs, validation_split = 0.2)
ready_log = pd.DataFrame(ready.history)
import matplotlib.pyplot as plt
ready_log['epoch']=ready.epoch
plt.figure()
plt.xlabel('NO_OF_EPOCHS')
plt.ylabel('MEAN ABSOLUTE ERROR [MPG]')
plt.plot(ready_log['epoch'],
ready_log['mae'],label='TRAIN_ERROR')
plt.plot(ready_log['epoch'], ready_log['val_mae'],label = 'VALERROR')
plt.ylim([0,5])
plt.legend()
plt.savefig('Mean Abs Error.png')
plt.figure()
plt.xlabel('NO_OF_EPOCHS')
plt.ylabel('MEAN SQUARED ERROR [$MPG^2$]')
plt.plot(ready_log['epoch'], ready_log['mse'],label='TRAIN_ERROR')
plt.plot(ready_log['epoch'], ready_log['val_mse'],label = 'VALERROR')
plt.ylim([0,20])
plt.legend()
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14640426705903992, 'fraction_numerical': 0.01618539635828582, 'mean_word_length': 6.90406976744186, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '164331', 'license': 'MIT', 'n_tokens_mistral': 2003, 'n_tokens_neox': 1915, 'n_words': 390, 'path': 'Chapter02/NeuralNetworkwithTensorFlow.ipynb', 'repo_name': 'PacktPublishing/neural-network-programming-with-python', 'size': '5437'}