SlideShare a Scribd company logo
1 of 7
When running the code below I am getting some errors (see image). The line, in the code below,
that the error is coming from will be highlighted in bold . Any help fixing it would be
appreciated.
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
#1) Generate the synthetic data using the following Python code snippet.
# Generate synthetic data
N = 100
# Zeros form a Gaussian centered at (-1, -1)
x_zeros = np.random.multivariate_normal(mean=np.array((-1, -1)), cov=.1*np.eye(2),
size=(N//2,))
y_zeros = np.zeros((N//2,))
# Ones form a Gaussian centered at (1, 1)
x_ones = np.random.multivariate_normal(mean=np.array((1, 1)), cov=.1*np.eye(2),
size=(N//2,))
y_ones = np.ones((N//2,))
x_np = np.vstack([x_zeros, x_ones])
y_np = np.concatenate([y_zeros, y_ones])
# Plot x_zeros and x_ones on the same graph
plt.scatter(x_zeros[:,0], x_zeros[:,1], label='class 0')
plt.scatter(x_ones[:,0], x_ones[:,1], label='class 1')
plt.legend()
plt.show()
#3) Generate a TensorFlow graph.
with tf.name_scope("placeholders"):
x = tf.constant(x_np, dtype=tf.float32)
y = tf.constant(y_np, dtype=tf.float32)
with tf.name_scope("weights"):
W = tf.Variable(tf.random.normal((2, 1)))
b = tf.Variable(tf.random.normal((1,)))
with tf.name_scope("prediction"):
y_logit = tf.squeeze(tf.matmul(x, W) + b)
# the sigmoid gives the class probability of 1
y_one_prob = tf.sigmoid(y_logit)
# Rounding P(y=1) will give the correct prediction.
y_pred = tf.round(y_one_prob)
with tf.name_scope("loss"):
# Compute the cross-entropy term for each datapoint
entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=y_logit, labels=y)
# Sum all contributions
l = tf.reduce_sum(entropy)
with tf.name_scope("optim"):
train_op = tf.compat.v1.train.AdamOptimizer(.01).minimize(l)
with tf.name_scope("summaries"):
tf.compat.v1.summary.scalar("loss", l)
merged = tf.compat.v1.summary.merge_all()
train_writer = tf.compat.v1.summary.FileWriter('logistic-train',
tf.compat.v1.get_default_graph())
#4) Train the model, get the weights, and make predictions.
with tf.compat.v1.Session() as sess:
# Initialize all variables
sess.run(tf.compat.v1.global_variables_initializer())
# Train the model for 100 epochs
for epoch in range(100):
# Run the train_op
_, summary, loss = sess.run([train_op, merged, l])
print("Epoch:", epoch, "Loss:", loss)
# Write the summary for TensorBoard
train_writer.add_summary(summary, epoch)
# Get the weights and biases
W_final, b_final = sess.run([W, b])
# Get the predictions
y_pred_np = sess.run(y_pred)
#5) Plot the predicted outputs on top of the data.
plt.scatter(x_np[y_pred_np==0,0], x_np[y_pred_np==0,1], label='class 0')
plt.scatter(x_np[y_pred_np==1,0], x_np[y_pred_np==1,1], label='class 1')
plt.legend()
plt.show()
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
#1) Generate the synthetic data using the following Python code snippet.
# Generate synthetic data
N = 100
# Zeros form a Gaussian centered at (-1, -1)
x_zeros = np.random.multivariate_normal(mean=np.array((-1, -1)),
cov=.1*np.eye(2), size=(N//2,))
y_zeros = np.zeros((N//2,))
# Ones form a Gaussian centered at (1, 1)
x_ones = np.random.multivariate_normal(mean=np.array((1, 1)),
cov=.1*np.eye(2), size=(N//2,))
y_ones = np.ones((N//2,))
x_np = np.vstack([x_zeros, x_ones])
y_np = np.concatenate([y_zeros, y_ones])
# Plot x_zeros and x_ones on the same graph
plt.scatter(x_zeros[:,0], x_zeros[:,1], label='class 0')
plt.scatter(x_ones[:,0], x_ones[:,1], label='class 1')
plt.legend()
plt.show()
#3) Generate a TensorFlow graph.
with tf.name_scope("placeholders"):
x = tf.constant(x_np, dtype=tf.float32)
y = tf.constant(y_np, dtype=tf.float32)
with tf.name_scope("weights"):
W = tf.Variable(tf.random.normal((2, 1)))
b = tf.Variable(tf.random.normal((1,)))
with tf.name_scope("prediction"):
y_logit = tf.squeeze(tf.matmul(x, W) + b)
# the sigmoid gives the class probability of 1
y_one_prob = tf.sigmoid(y_logit)
# Rounding P(y=1) will give the correct prediction.
y_pred = tf.round(y_one_prob)
with tf.name_scope("loss"):
# Compute the cross-entropy term for each datapoint
entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=y_logit, labels=y)
# Sum all contributions
l = tf.reduce_sum(entropy)
with tf.name_scope("optim"):
train_op = tf.compat.v1.train.AdamOptimizer(.01).minimize(l)
with tf.name_scope("summaries"):
tf.compat.v1.summary.scalar("loss", l)
merged = tf.compat.v1.summary.merge_all()
train_writer = tf.compat.v1.summary.FileWriter('logistic-train',
tf.compat.v1.get_default_graph())
#4) Train the model, get the weights, and make predictions.
with tf.compat.v1.Session() as sess:
# Initialize all variables
sess.run(tf.compat.v1.global_variables_initializer())
# Train the model for 100 epochs
for epoch in range(100):
# Run the train_op
_, summary, loss = sess.run([train_op, merged, l])
print("Epoch:", epoch, "Loss:", loss)
# Write the summary for TensorBoard
train_writer.add_summary(summary, epoch)
# Get the weights and biases
W_final, b_final = sess.run([W, b])
# Get the predictions
y_pred_np = sess.run(y_pred)
#5) Plot the predicted outputs on top of the data.
plt.scatter(x_np[y_pred_np==0,0], x_np[y_pred_np==0,1], label='class 0')
plt.scatter(x_np[y_pred_np==1,0], x_np[y_pred_np==1,1], label='class 1')
plt.legend()
plt.show()
When running the code below I am getting some errors (see image)- The.docx

More Related Content

Similar to When running the code below I am getting some errors (see image)- The.docx

goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
ANJALIENTERPRISES1
 
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
Blake0FxCampbelld
 
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
DineshThallapelly
 
1- please please please don't send me an incomplete program this code.docx
1- please please please don't send me an incomplete program this code.docx1- please please please don't send me an incomplete program this code.docx
1- please please please don't send me an incomplete program this code.docx
EvandWyBurgesss
 

Similar to When running the code below I am getting some errors (see image)- The.docx (20)

Py lecture5 python plots
Py lecture5 python plotsPy lecture5 python plots
Py lecture5 python plots
 
Python programing
Python programingPython programing
Python programing
 
Kalman filter
Kalman filterKalman filter
Kalman filter
 
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
 
MatplotLib.pptx
MatplotLib.pptxMatplotLib.pptx
MatplotLib.pptx
 
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
 
[신경망기초] 합성곱신경망
[신경망기초] 합성곱신경망[신경망기초] 합성곱신경망
[신경망기초] 합성곱신경망
 
Practicle 1.docx
Practicle 1.docxPracticle 1.docx
Practicle 1.docx
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & Matplotlib
 
The TensorFlow dance craze
The TensorFlow dance crazeThe TensorFlow dance craze
The TensorFlow dance craze
 
Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화
 
DeepStochLog: Neural Stochastic Logic Programming
DeepStochLog: Neural Stochastic Logic ProgrammingDeepStochLog: Neural Stochastic Logic Programming
DeepStochLog: Neural Stochastic Logic Programming
 
Codecomparaison
CodecomparaisonCodecomparaison
Codecomparaison
 
NUMPY-2.pptx
NUMPY-2.pptxNUMPY-2.pptx
NUMPY-2.pptx
 
About RNN
About RNNAbout RNN
About RNN
 
About RNN
About RNNAbout RNN
About RNN
 
Essential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdfEssential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdf
 
Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report
 
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
 
1- please please please don't send me an incomplete program this code.docx
1- please please please don't send me an incomplete program this code.docx1- please please please don't send me an incomplete program this code.docx
1- please please please don't send me an incomplete program this code.docx
 

More from maximapikvu8

More from maximapikvu8 (20)

Wings of birds and wings of insects are---It is a 12 letter word in a.docx
Wings of birds and wings of insects are---It is a 12 letter word in a.docxWings of birds and wings of insects are---It is a 12 letter word in a.docx
Wings of birds and wings of insects are---It is a 12 letter word in a.docx
 
Windows provides a very simple mechanism for sharing files among users.docx
Windows provides a very simple mechanism for sharing files among users.docxWindows provides a very simple mechanism for sharing files among users.docx
Windows provides a very simple mechanism for sharing files among users.docx
 
Why was Pericles an important figure- in the City of Athens- 2- Clearl.docx
Why was Pericles an important figure- in the City of Athens- 2- Clearl.docxWhy was Pericles an important figure- in the City of Athens- 2- Clearl.docx
Why was Pericles an important figure- in the City of Athens- 2- Clearl.docx
 
why is this error showing what have i done wrong Declunilearetant v.docx
why is this error showing what have i done wrong    Declunilearetant v.docxwhy is this error showing what have i done wrong    Declunilearetant v.docx
why is this error showing what have i done wrong Declunilearetant v.docx
 
Why is this error showing NewAge2-java-17- error- cannot find symbol n.docx
Why is this error showing NewAge2-java-17- error- cannot find symbol n.docxWhy is this error showing NewAge2-java-17- error- cannot find symbol n.docx
Why is this error showing NewAge2-java-17- error- cannot find symbol n.docx
 
Why is it important to reduce disulfide linkages prior to SDS electrop.docx
Why is it important to reduce disulfide linkages prior to SDS electrop.docxWhy is it important to reduce disulfide linkages prior to SDS electrop.docx
Why is it important to reduce disulfide linkages prior to SDS electrop.docx
 
Why do statisticians prefer to select samples by a random process- Que.docx
Why do statisticians prefer to select samples by a random process- Que.docxWhy do statisticians prefer to select samples by a random process- Que.docx
Why do statisticians prefer to select samples by a random process- Que.docx
 
Why do employers ask for demographic information- (select all that app.docx
Why do employers ask for demographic information- (select all that app.docxWhy do employers ask for demographic information- (select all that app.docx
Why do employers ask for demographic information- (select all that app.docx
 
Why can bio-prospecting be controversial- Species are frequently drive.docx
Why can bio-prospecting be controversial- Species are frequently drive.docxWhy can bio-prospecting be controversial- Species are frequently drive.docx
Why can bio-prospecting be controversial- Species are frequently drive.docx
 
Why did Malthus's predictions was not realized for most of the develop.docx
Why did Malthus's predictions was not realized for most of the develop.docxWhy did Malthus's predictions was not realized for most of the develop.docx
Why did Malthus's predictions was not realized for most of the develop.docx
 
Why are accessory pigments important- A- They are a rich source of ele.docx
Why are accessory pigments important- A- They are a rich source of ele.docxWhy are accessory pigments important- A- They are a rich source of ele.docx
Why are accessory pigments important- A- They are a rich source of ele.docx
 
Which xml tag defines global parameters available to all servlets in t.docx
Which xml tag defines global parameters available to all servlets in t.docxWhich xml tag defines global parameters available to all servlets in t.docx
Which xml tag defines global parameters available to all servlets in t.docx
 
While using K-means clustering- we scale the variables before we do cl.docx
While using K-means clustering- we scale the variables before we do cl.docxWhile using K-means clustering- we scale the variables before we do cl.docx
While using K-means clustering- we scale the variables before we do cl.docx
 
Which statements about chromosomal organization are true and which are.docx
Which statements about chromosomal organization are true and which are.docxWhich statements about chromosomal organization are true and which are.docx
Which statements about chromosomal organization are true and which are.docx
 
Which statement below best compares the lithosphere to the crust accor.docx
Which statement below best compares the lithosphere to the crust accor.docxWhich statement below best compares the lithosphere to the crust accor.docx
Which statement below best compares the lithosphere to the crust accor.docx
 
Which statement about education as a demographic factor is accurate- M.docx
Which statement about education as a demographic factor is accurate- M.docxWhich statement about education as a demographic factor is accurate- M.docx
Which statement about education as a demographic factor is accurate- M.docx
 
Which pairing of microorganism and bioremediation application is NOT c.docx
Which pairing of microorganism and bioremediation application is NOT c.docxWhich pairing of microorganism and bioremediation application is NOT c.docx
Which pairing of microorganism and bioremediation application is NOT c.docx
 
Which scenario is most likely to maintain trait variation in a populat.docx
Which scenario is most likely to maintain trait variation in a populat.docxWhich scenario is most likely to maintain trait variation in a populat.docx
Which scenario is most likely to maintain trait variation in a populat.docx
 
Which research finding best indicates that a moderator variable was op.docx
Which research finding best indicates that a moderator variable was op.docxWhich research finding best indicates that a moderator variable was op.docx
Which research finding best indicates that a moderator variable was op.docx
 
Which organelles originated from the engulfment of ancestral prokaryti.docx
Which organelles originated from the engulfment of ancestral prokaryti.docxWhich organelles originated from the engulfment of ancestral prokaryti.docx
Which organelles originated from the engulfment of ancestral prokaryti.docx
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

When running the code below I am getting some errors (see image)- The.docx

  • 1. When running the code below I am getting some errors (see image). The line, in the code below, that the error is coming from will be highlighted in bold . Any help fixing it would be appreciated. import numpy as np import tensorflow as tf import matplotlib.pyplot as plt #1) Generate the synthetic data using the following Python code snippet. # Generate synthetic data N = 100 # Zeros form a Gaussian centered at (-1, -1) x_zeros = np.random.multivariate_normal(mean=np.array((-1, -1)), cov=.1*np.eye(2), size=(N//2,)) y_zeros = np.zeros((N//2,)) # Ones form a Gaussian centered at (1, 1) x_ones = np.random.multivariate_normal(mean=np.array((1, 1)), cov=.1*np.eye(2), size=(N//2,)) y_ones = np.ones((N//2,)) x_np = np.vstack([x_zeros, x_ones]) y_np = np.concatenate([y_zeros, y_ones]) # Plot x_zeros and x_ones on the same graph plt.scatter(x_zeros[:,0], x_zeros[:,1], label='class 0') plt.scatter(x_ones[:,0], x_ones[:,1], label='class 1') plt.legend() plt.show()
  • 2. #3) Generate a TensorFlow graph. with tf.name_scope("placeholders"): x = tf.constant(x_np, dtype=tf.float32) y = tf.constant(y_np, dtype=tf.float32) with tf.name_scope("weights"): W = tf.Variable(tf.random.normal((2, 1))) b = tf.Variable(tf.random.normal((1,))) with tf.name_scope("prediction"): y_logit = tf.squeeze(tf.matmul(x, W) + b) # the sigmoid gives the class probability of 1 y_one_prob = tf.sigmoid(y_logit) # Rounding P(y=1) will give the correct prediction. y_pred = tf.round(y_one_prob) with tf.name_scope("loss"): # Compute the cross-entropy term for each datapoint entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=y_logit, labels=y) # Sum all contributions l = tf.reduce_sum(entropy) with tf.name_scope("optim"): train_op = tf.compat.v1.train.AdamOptimizer(.01).minimize(l) with tf.name_scope("summaries"): tf.compat.v1.summary.scalar("loss", l) merged = tf.compat.v1.summary.merge_all()
  • 3. train_writer = tf.compat.v1.summary.FileWriter('logistic-train', tf.compat.v1.get_default_graph()) #4) Train the model, get the weights, and make predictions. with tf.compat.v1.Session() as sess: # Initialize all variables sess.run(tf.compat.v1.global_variables_initializer()) # Train the model for 100 epochs for epoch in range(100): # Run the train_op _, summary, loss = sess.run([train_op, merged, l]) print("Epoch:", epoch, "Loss:", loss) # Write the summary for TensorBoard train_writer.add_summary(summary, epoch) # Get the weights and biases W_final, b_final = sess.run([W, b]) # Get the predictions y_pred_np = sess.run(y_pred) #5) Plot the predicted outputs on top of the data. plt.scatter(x_np[y_pred_np==0,0], x_np[y_pred_np==0,1], label='class 0') plt.scatter(x_np[y_pred_np==1,0], x_np[y_pred_np==1,1], label='class 1') plt.legend() plt.show() import numpy as np
  • 4. import tensorflow as tf import matplotlib.pyplot as plt #1) Generate the synthetic data using the following Python code snippet. # Generate synthetic data N = 100 # Zeros form a Gaussian centered at (-1, -1) x_zeros = np.random.multivariate_normal(mean=np.array((-1, -1)), cov=.1*np.eye(2), size=(N//2,)) y_zeros = np.zeros((N//2,)) # Ones form a Gaussian centered at (1, 1) x_ones = np.random.multivariate_normal(mean=np.array((1, 1)), cov=.1*np.eye(2), size=(N//2,)) y_ones = np.ones((N//2,)) x_np = np.vstack([x_zeros, x_ones]) y_np = np.concatenate([y_zeros, y_ones]) # Plot x_zeros and x_ones on the same graph plt.scatter(x_zeros[:,0], x_zeros[:,1], label='class 0') plt.scatter(x_ones[:,0], x_ones[:,1], label='class 1') plt.legend() plt.show() #3) Generate a TensorFlow graph. with tf.name_scope("placeholders"): x = tf.constant(x_np, dtype=tf.float32)
  • 5. y = tf.constant(y_np, dtype=tf.float32) with tf.name_scope("weights"): W = tf.Variable(tf.random.normal((2, 1))) b = tf.Variable(tf.random.normal((1,))) with tf.name_scope("prediction"): y_logit = tf.squeeze(tf.matmul(x, W) + b) # the sigmoid gives the class probability of 1 y_one_prob = tf.sigmoid(y_logit) # Rounding P(y=1) will give the correct prediction. y_pred = tf.round(y_one_prob) with tf.name_scope("loss"): # Compute the cross-entropy term for each datapoint entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=y_logit, labels=y) # Sum all contributions l = tf.reduce_sum(entropy) with tf.name_scope("optim"): train_op = tf.compat.v1.train.AdamOptimizer(.01).minimize(l) with tf.name_scope("summaries"): tf.compat.v1.summary.scalar("loss", l) merged = tf.compat.v1.summary.merge_all() train_writer = tf.compat.v1.summary.FileWriter('logistic-train', tf.compat.v1.get_default_graph()) #4) Train the model, get the weights, and make predictions.
  • 6. with tf.compat.v1.Session() as sess: # Initialize all variables sess.run(tf.compat.v1.global_variables_initializer()) # Train the model for 100 epochs for epoch in range(100): # Run the train_op _, summary, loss = sess.run([train_op, merged, l]) print("Epoch:", epoch, "Loss:", loss) # Write the summary for TensorBoard train_writer.add_summary(summary, epoch) # Get the weights and biases W_final, b_final = sess.run([W, b]) # Get the predictions y_pred_np = sess.run(y_pred) #5) Plot the predicted outputs on top of the data. plt.scatter(x_np[y_pred_np==0,0], x_np[y_pred_np==0,1], label='class 0') plt.scatter(x_np[y_pred_np==1,0], x_np[y_pred_np==1,1], label='class 1') plt.legend() plt.show()