0

When I run this code:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(-1, 784).astype("float32") / 255.0
x_test = x_test.reshape(-1, 784).astype("float32") / 255.0

model = keras.Sequential(
    [
        layers.Dense(512, activation='relu'),
        layers.Dense(256, activation='relu'),
        layers.Dense(10),
    ]
)

model.compile(
    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer=keras.optimizers.Adam(lr=0.001),
    metrics=["accuracy"],

The error ModuleNotFoundError: No module named 'keras' occures due to line model = keras.Sequential..., however I think that line loss=keras.losses.SparseCategoricalCrossentropy would give an error too.

eresque-
  • 67
  • 8
  • Please check if the virtual environment you are trying to execute this code from has Keras installed in it (pip show keras). – Anshuman Tiwari Oct 06 '22 at 10:14
  • You might have issues with conda and pip see https://stackoverflow.com/questions/73867809/python-modulenotfounderror-no-module-named-patsy-when-using-ggplot/73867933#73867933 – Ftagliacarne Oct 06 '22 at 10:16
  • Also, check the TensorFlow version you are using. IIRC, Keras was incorporated into TensorFlow after version 2.0. – lpounng Oct 06 '22 at 10:41
  • Ok, so i kinda soleved my problem BUT I still can't undestand something. If I do`from tensorflow import keras` then tis code doesn't work `keras.Sequential` but if I do `from tensorflow.keras import models` then `models.Sequential` works. So I thought, what if I need to `from tensorflow import keras` and then use `keras.models.Sequential`, but this doesn't work either! At this point I'm a bit lost – eresque- Oct 06 '22 at 11:04

1 Answers1

0

Do from tensorflow import keras and try to run print(keras.__version__). If it doesn't work, you should probably uninstall both Keras and TensorFlow, then reinstall an updated version of both libraries.