SlideShare a Scribd company logo
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

DOCX
Please help fill in the missing code below in order for it run correct.docx
PDF
Simple Neural Network Python Code
PDF
Numpy - Array.pdf
PDF
Quantum simulation Mathematics and Python examples
PPTX
Introduction to Tensorflow
DOCX
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
PPTX
BASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND ML
PDF
ML with python.pdf
Please help fill in the missing code below in order for it run correct.docx
Simple Neural Network Python Code
Numpy - Array.pdf
Quantum simulation Mathematics and Python examples
Introduction to Tensorflow
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
BASIC OF PYTHON MATPLOTLIB USED IN ARTIFICIAL INTELLIGENCE AND ML
ML with python.pdf

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

PDF
III MCS python lab (1).pdf
PDF
Rcommands-for those who interested in R.
PPTX
matplotlib.pptxdsfdsfdsfdsdsfdsdfdsfsdf cvvf
PDF
Py lecture5 python plots
PPTX
Python programing
PDF
Kalman filter
PDF
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
DOCX
Trabajo de Matemática aplicada de la facultad de ciencias matematicas unidad ...
PPTX
MatplotLib.pptx
PDF
Concept of Data science and Numpy concept
DOCX
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
PPTX
Numpy_Pandas_for beginners_________.pptx
PDF
[신경망기초] 합성곱신경망
PPTX
Introduction to data analyticals123232.pptx
DOCX
Practicle 1.docx
PDF
Class 8b: Numpy & Matplotlib
PDF
The TensorFlow dance craze
PDF
Python과 node.js기반 데이터 분석 및 가시화
PDF
Numpy questions with answers and practice
PDF
DeepStochLog: Neural Stochastic Logic Programming
III MCS python lab (1).pdf
Rcommands-for those who interested in R.
matplotlib.pptxdsfdsfdsfdsdsfdsdfdsfsdf cvvf
Py lecture5 python plots
Python programing
Kalman filter
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
Trabajo de Matemática aplicada de la facultad de ciencias matematicas unidad ...
MatplotLib.pptx
Concept of Data science and Numpy concept
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
Numpy_Pandas_for beginners_________.pptx
[신경망기초] 합성곱신경망
Introduction to data analyticals123232.pptx
Practicle 1.docx
Class 8b: Numpy & Matplotlib
The TensorFlow dance craze
Python과 node.js기반 데이터 분석 및 가시화
Numpy questions with answers and practice
DeepStochLog: Neural Stochastic Logic Programming

More from maximapikvu8 (20)

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

Recently uploaded (20)

PPTX
Pharma ospi slides which help in ospi learning
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Lesson notes of climatology university.
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
01-Introduction-to-Information-Management.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Final Presentation General Medicine 03-08-2024.pptx
Pharma ospi slides which help in ospi learning
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Lesson notes of climatology university.
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Microbial diseases, their pathogenesis and prophylaxis
Chinmaya Tiranga quiz Grand Finale.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Final Presentation General Medicine 03-08-2024.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Complications of Minimal Access Surgery at WLH
01-Introduction-to-Information-Management.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Final Presentation General Medicine 03-08-2024.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()