[go: up one dir, main page]

0% found this document useful (0 votes)
28 views5 pages

Jaycolpdf 1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 5

7/27/23, 11:10 PM Untitled1.

ipynb - Colaboratory

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

from tensorflow.keras.datasets import mnist


(x_train, y_train), (x_test, y_test) = mnist.load_data()

print(x_train.shape)
print(len(y_train))
print(x_test.shape)
print(len(y_test))

Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz


11490434/11490434 [==============================] - 0s 0us/step
(60000, 28, 28)
60000
(10000, 28, 28)
10000

plt.figure()
plt.imshow(x_train [7], cmap='binary')
plt.colorbar ()
plt.grid(False)
plt.show()

y_train[0]

print(set(y_train))

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

from tensorflow.keras.utils import to_categorical

y_train_encoded=to_categorical(y_train)
y_test_encoded=to_categorical(y_test)

y_train_encoded.shape, y_test_encoded.shape

((60000, 10), (10000, 10))

y_train_encoded[0]

array([0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], dtype=float32)

plt.figure(figsize=(30,30))
for i in range(30):
plt.subplot(5,6,i+1)
plt.xticks([])
plt.yticks([])
plt.imshow(x_train[i], cmap=plt.cm.binary)
plt.xlabel(y_train[i])

https://colab.research.google.com/drive/1Q5Afyp2LRwHLhyCkEWSAf4clY_yL31c4#printMode=true 1/5
7/27/23, 11:10 PM Untitled1.ipynb - Colaboratory

x_train_reshaped=np.reshape(x_train, (60000,784))
x_test_reshaped=np.reshape(x_test, (10000,784))
print("x_train_reshaped: \n",x_train_reshaped.shape)
print("x_test_reshaped: \n",x_test_reshaped.shape)

x_train_reshaped:
(60000, 784)
x_test_reshaped:
(10000, 784)

print(set(x_train_reshaped[0]))

{0, 1, 2, 3, 9, 11, 14, 16, 18, 23, 24, 25, 26, 27, 30, 35, 36, 39, 43, 45, 46, 49, 55, 56, 64, 66, 70, 78, 80, 81, 82, 90, 93, 94,

x_mean=np.mean(x_train_reshaped)
x_std=np.std (x_train_reshaped)
eps = 1.0

https://colab.research.google.com/drive/1Q5Afyp2LRwHLhyCkEWSAf4clY_yL31c4#printMode=true 2/5
7/27/23, 11:10 PM Untitled1.ipynb - Colaboratory
while eps + 1 > 1:
eps /= 2
eps*=2
x_train_norm=(x_train_reshaped-x_mean)/(x_std+eps)
x_test_norm=(x_test_reshaped-x_mean)/(x_std+eps)

print(set(x_train_norm[0]))

{-0.3858901621553201, 1.3069219669849146, 1.1796428595307615, 1.8033104860561113, 1.6887592893473735, 2.821543345689335, 2.71972005

model = tf.keras.Sequential ([
tf.keras.layers. Flatten (input_shape=(28, 28)),
tf.keras.layers. Dense (128, activation='relu'),
tf.keras.layers. Dense (128, activation='relu'),
tf.keras.layers. Dense (10, activation='softmax')
])

model.compile(optimizer='sgd',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()

Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
flatten (Flatten) (None, 784) 0

dense (Dense) (None, 128) 100480

dense_1 (Dense) (None, 128) 16512

dense_2 (Dense) (None, 10) 1290

=================================================================
Total params: 118,282
Trainable params: 118,282
Non-trainable params: 0
_________________________________________________________________

x_train_norm = x_train_reshaped.reshape(-1,784)
x_test_norm = x_test_reshaped.reshape(-1,784)
model.fit(x_train_norm, y_train_encoded, epochs=4)

Epoch 1/4
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-27-051bf10f64af> in <cell line: 3>()
1 x_train_norm = x_train_reshaped.reshape(-1,784)
2 x_test_norm = x_test_reshaped.reshape(-1,784)
----> 3 model.fit(x_train_norm, y_train_encoded, epochs=4)

1 frames
/usr/local/lib/python3.10/dist-
packages/tensorflow/python/eager/polymorphic_function/polymorphic_function.py in
_call(self, *args, **kwds)
924 # In this case we have created variables on the first call, so we run
the
925 # defunned version which is guaranteed to never create variables.
--> 926 return self._no_variable_creation_fn(*args, **kwds) # pylint:
disable=not-callable
927 elif self._variable_creation_fn is not None:
928 # Release the lock early so that multiple threads can perform the call

loss, accuracy = model.evaluate(x_test_norm, y_test_encoded)


print('\nTest accuracy:', accuracy)

https://colab.research.google.com/drive/1Q5Afyp2LRwHLhyCkEWSAf4clY_yL31c4#printMode=true 3/5
7/27/23, 11:10 PM Untitled1.ipynb - Colaboratory

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-21-c91df46ddfc0> in <cell line: 1>()
----> 1 loss, accuracy = model.evaluate(x_test_norm, y_test_encoded)
2 print('\nTest accuracy:', accuracy)

1 frames
/usr/local/lib/python3.10/dist-packages/keras/engine/training.py in
tf__test_function(iterator)
13 try:
14 do_return = True
---> 15 retval_ = ag__.converted_call(ag__.ld(step_function),
(ag__.ld(self), ag__.ld(iterator)), None, fscope)
16 except:
17 do_return = False

ValueError: in user code:

File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line


predictions
1852, in= model.predict(x_test_norm)
test_function *
return
print('shape of step_function(self,
prediction', iterator)
predictions.shape)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line
1836, in step_function **
---------------------------------------------------------------------------
outputs = model.distribute_strategy.run(run_step,
ValueError Traceback (most args=(data,))
recent call last)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py",
<ipython-input-22-1cdf1a9755fc> in <cell line: 1>() line
1824,
----> in run_step **
1 predictions = model.predict(x_test_norm)
2 outputs = model.test_step(data)
print('shape of prediction', predictions.shape)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line
1788, in test_step 1 frames
y_pred = self(x, training=False)
/usr/local/lib/python3.10/dist-packages/keras/engine/training.py in
File "/usr/local/lib/python3.10/dist-packages/keras/utils/traceback_utils.py",
tf__predict_function(iterator)
line 70, in error_handler
13 try:
raise e.with_traceback(filtered_tb) from None
14 do_return = True
---> 15 retval_ = ag__.converted_call(ag__.ld(step_function),
(ag__.ld(self), ag__.ld(iterator)), None, fscope)
16 except:
17 do_return = False

ValueError: in user code:

File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line


2169, in predict_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line
2155, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line
2143, in run_step **
outputs = model.predict_step(data)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line
2111, in predict_step
return self(x, training=False)
File "/usr/local/lib/python3.10/dist-packages/keras/utils/traceback_utils.py",
line 70, in error_handler
raise e.with_traceback(filtered_tb) from None

plt.figure(figsize=(5,5))
start_index=0
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
prediction=np.argmax (predictions[start_index+i])
gt=y_test[start_index+i]
col='g'
if prediction!=gt:
col='r'
plt.xlabel('i={}, prediction={}, gt={}'.format(star_index+i, prediction, gt), color=col)
plt.imshow(x_test[star_index+i], cmap='binary')
plt.show()

https://colab.research.google.com/drive/1Q5Afyp2LRwHLhyCkEWSAf4clY_yL31c4#printMode=true 4/5
7/27/23, 11:10 PM Untitled1.ipynb - Colaboratory

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-26-03c8a2238fcd> in <cell line: 3>()
plt.plot(predictions[8])
5 plt.xticks([])
plt.show() 6 plt.yticks([])
----> 7 prediction=np.argmax (predictions[start_index+i])
---------------------------------------------------------------------------
8 gt=y_test[start_index+i]
NameError
9 col='g' Traceback (most recent call last)
<ipython-input-24-07edd7ca3a95> in <cell line: 1>()
----> 1 plt.plot(predictions[8])
NameError: name 'predictions' is not defined
2 plt.show()
SEARCH STACK OVERFLOW
NameError: name 'predictions' is not defined

SEARCH STACK OVERFLOW

Colab paid products - Cancel contracts here

https://colab.research.google.com/drive/1Q5Afyp2LRwHLhyCkEWSAf4clY_yL31c4#printMode=true 5/5

You might also like