# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# [View in Colaboratory](https://colab.research.google.com/github/findingfoot/ML_practice-codes/blob/master/Linear_Regression_using_Tensorflow_methods.ipynb)

# + id="9Y0k1CJAbFpK" colab_type="code" colab={}
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn import datasets
from tensorflow.python.framework import ops
ops.reset_default_graph()

sess = tf.Session()

# + id="0c6_I_tUbFpN" colab_type="code" colab={}
iris = datasets.load_iris()

# + id="vAAPFXJKbFpQ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="859348fc-e669-49f4-9db9-19f3875abfd8"
'''
iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)]
equation to solve : y = Ax+b
where x is the petal width and y is the sepal length
'''

# + id="jzEri3hPbFpV" colab_type="code" colab={}
x_vals = np.array([x[3] for x in iris.data]) # petal width
y_vals = np.array([x[0] for x in iris.data]) #sepal length


# + id="GrsAG-pRbFpZ" colab_type="code" colab={}
# we need a batch size

batch_size = 25

# + id="L5QCUAB-bFpb" colab_type="code" colab={}
#placeholder for the data and target

x_data = tf.placeholder(shape = [None, 1], dtype=tf.float32)
y_target = tf.placeholder(shape = [None, 1], dtype = tf.float32)

#We also need variables like A and b in our case here

A = tf.Variable(tf.random_normal(shape = [1,1]))
b = tf.Variable(tf.random_normal(shape = [1,1]))


# + id="jm2xMKorbFpe" colab_type="code" colab={}
#Model operations

model_output = tf.add((tf.matmul(x_data, A)), b)

#Loss function

l2_loss = tf.reduce_mean(tf.square(y_target - model_output))

# + id="RlEnBj81bFph" colab_type="code" colab={}
#optimizer

my_opt = tf.train.GradientDescentOptimizer(0.05)
train_step = my_opt.minimize(l2_loss)

#initialize the variables

init = tf.global_variables_initializer()
sess.run(init)


# + id="3Pa_TpOAbFpl" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1361} outputId="4660e9ca-7344-46fc-867b-ead3c7743822"
loss_vector = []

for i in range(1000):
    #sample as per random index
    rand_index = np.random.choice(len(x_vals), size = batch_size)
    rand_x = np.transpose([x_vals[rand_index]])
    rand_y = np.transpose([y_vals[rand_index]])
    sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
    temp_loss = sess.run(l2_loss, feed_dict={x_data: rand_x, y_target: rand_y})
    loss_vector.append(temp_loss)
    
    if (i+1)%25==0:
        print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b)))
        print('Loss = ' + str(temp_loss))
    
    

# + id="AbZIDoqGbFpp" colab_type="code" colab={}
[slope] = sess.run(A)
[intercept] = sess.run(b)

#best fit line
best_fit = []
for i in x_vals:
    best_fit.append(slope*i+intercept)

# + id="IWsyRAmkbQW0" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1179} outputId="42339757-4489-4918-e7b7-1dd2d12684e5"
# !pip install jupyterthemes

# + id="PTyDPjQcbFps" colab_type="code" colab={}
from jupyterthemes import jtplot

jtplot.style()

jtplot.style(theme='solarizedd')

# + id="HMdH6Ga2bFpv" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 389} outputId="6005fd5f-3bef-4ceb-c638-4d493840120a"
plt.plot(x_vals, y_vals, 'r*' , label = 'Data')
plt.plot(x_vals, best_fit, 'go', label = 'Best fit line', linewidth = 3)
plt.legend(loc = 'best')
plt.title('Sepal Length vs petal width')
plt.xlabel('Petal width')
plt.ylabel('Sepal length')
plt.show()

# + id="4pPNnW08bUn9" colab_type="code" colab={}


StarcoderdataJupyterScriptsDedupFiltered