Перейти к содержимому

Как установить tensorflow в jupiter notebook

  • автор:

В Jupyter Notebook ошибка импорта tensorflow

Изначально код работал, но при повторном его перезапуске в блокноте (Restart&Run All) получаю ошибку импорта ImportError для tensorflow следующего содержания: cannot import name ‘export_saved_model’ from ‘tensorflow.python.keras.saving.saved_model’ Как возможное решение проблемы, деинсталировать в командной строке библиотеку с тем, чтобы заново ее установить. Попытка сделать это через conda результата не дала (застревал на этапе solving environment: указатель вращался, но затем ничего не происходило). Решения добился с помощью pip. И получил вторую ошибку — теперь с другим импортом: cannot import name ‘tf2’ from ‘tensorflow.python’ (unknown location) Как быть?

Отслеживать
Alex_Kazantsev
задан 28 авг 2021 в 13:09
Alex_Kazantsev Alex_Kazantsev
617 1 1 золотой знак 7 7 серебряных знаков 19 19 бронзовых знаков

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

Собственно, сначала «ругался» tensorflow, после его «починки» — keras, но в итоге помогло последовательное выполнение команд pip uninstall tensorflow , pip uninstall keras и после них — повторная установка модулей. Были эксперименты с виртуальным окружением, но эти решения оказались лишними

Отслеживать
ответ дан 2 сен 2021 в 17:12
Alex_Kazantsev Alex_Kazantsev
617 1 1 золотой знак 7 7 серебряных знаков 19 19 бронзовых знаков

  • tensorflow
  • keras
  • импорт
  • командная-строка
    Важное на Мете
Похожие

Подписаться на ленту

Лента вопроса

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

Дизайн сайта / логотип © 2024 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2024.1.26.3951

Python-bloggers

Data science news and tutorials — contributed by Python bloggers

Installing Python and Tensorflow with Jupyter Notebook Configurations

Posted on March 5, 2022 by Sang-Heon Lee in Data science | 0 Comments

This article was first published on K & L Fintech Modeling , and kindly contributed to python-bloggers. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

For a machine or deep learning modeling, Python is widely used with Tensorflow. This post explains the an installation of Python, Tensorflow and configuration of Jupyter notebook as a kickstart towards ML/DL modeling.

Python, Tensorflow, Jupyter Notebook

It is common to use Anaconda for installing Python since a variety of packages (i.e. sklearn, pandas and so on) are installed automatically. Without Anaconda, we need to install Python and lots of package manually.

After installing Anaconda, Tensorflow is installed since Anaconda does not contain Tensorflow. Next we modify the default directory for Jupyter Notebook for our working directory.

Tensorflow is of two kinds : CPU and GPU version. This post only deal with CPU version since my laptop does not have GPU and I can’t test it. Instead, I use Google Colab when GPU Tensorflow is necessary.

Python programming is usually done with user-defined virtual environments which are constructed with some specific version of Python or Tensorflow. This approach helps you avoid version conflicts. But, for the time being, it is not necessary. This will be covered when it is necessary.

A whole process of installing Python is as follows.

Install Python

Download the recent Anaconda (Python 3.9 • 64-Bit Graphical Installer for Windows) at https://www.anaconda.com/products/individual and install it (Anaconda3-2021.11-Windows-x86_64.exe). Follow the instructions below with default settings (Yes or Next).

When installation is finished, we can find the new menu items like the above figure.

To check for whether Python is installed correctly, let’s run a sample Python code. To this end, click Spyder (anaconda3) or Anaconda Navigator (anaconda3) ➜ Spyder button and run the next sample code for a testing purpose.

Spyder is an IDE tool like R studio. PyCharm or Visual Studio Code is widely used also. You can select a favorite tool which fit you.

How to Install TensorFlow in Jupyter Notebook

As a data scientist, you may have heard about the powerful machine learning framework called TensorFlow. TensorFlow is an open-source software library developed by Google that allows you to build and train machine learning models. In this blog post, we will show you how to install TensorFlow in Jupyter Notebook, a popular web-based interactive development environment for data science.

Tired of the complexities of installing TensorFlow in Jupyter Notebook? Try Saturn Cloud for free and to set up your data science environment effortlessly!

Step 1: Install Jupyter Notebook

Now that we have TensorFlow installed, we need to install Jupyter Notebook so we can start using it. In the same terminal window, type the following command:

conda install jupyter 

This will download and install Jupyter Notebook in your environment.

Step 2: Launch Jupyter Notebook

With TensorFlow and Jupyter Notebook installed, we can now launch Jupyter Notebook. In the same terminal window, type the following command:

jupyter notebook 

This will open Jupyter Notebook in your default web browser. You should see a list of files and folders in your home directory. To create a new notebook, click on the New button in the top right corner and select Python 3 under Notebooks .

Alt text

Step 3: Install TensorFlow

With our new environment created, we can now install TensorFlow. There are two ways to install TensorFlow: using pip or using conda. We recommend using conda as it will automatically install all the necessary dependencies. Create a new cell in your Jupyter notebook and run the command below:

!pip install tensorflow 

This will download and install the latest version of TensorFlow in your environment. If your machine support GPU, make sure to Install the NVIDIA GPU driver if you have not and verify it by nvidia-smi . At the end, you can run the following command:

!pip install tensorflow[and-cuda] 

Step 4: Test TensorFlow

To test if TensorFlow is working correctly, we can create a simple program that adds two numbers using TensorFlow. In your new notebook, type the following code:

import tensorflow as tf a = tf.constant(2) b = tf.constant(3) c = tf.add(a, b) with tf.Session() as sess: result = sess.run(c) print(result) 

This program creates two constants, a and b , and adds them together using TensorFlow’s add function. The result is then printed to the console.

To run the program, click on the Run button in the toolbar or press Shift+Enter . You should see the result, 5 , printed to the console.

Congratulations, you have successfully installed TensorFlow in Jupyter Notebook!

Tired of the complexities of installing TensorFlow in Jupyter Notebook? Try Saturn Cloud for free and to set up your data science environment effortlessly!

Conclusion

In this blog post, we have shown you how to install TensorFlow in Jupyter Notebook using Anaconda. By following these simple steps, you can start building and training machine learning models using TensorFlow in Jupyter Notebook. Remember to create a new environment specifically for TensorFlow to avoid conflicts with other Python packages.

  • Intro to Tensorflow
  • Mastering deep learning with Tensorflow
SHARE:
About Saturn Cloud

Saturn Cloud is your all-in-one solution for data science & ML development, deployment, and data pipelines in the cloud. Spin up a notebook with 4TB of RAM, add a GPU, connect to a distributed cluster of workers, and more. Join today and get 150 hours of free compute per month.

Как установить tensorflow в jupiter notebook

Оптимизируйте свои подборки Сохраняйте и классифицируйте контент в соответствии со своими настройками.

Установите ТензорФлоу 2

TensorFlow протестирован и поддерживается в следующих 64-битных системах:

  • Питон 3.8–3.11
  • Ubuntu 16.04 или новее
  • Windows 7 или более поздняя версия (с распространяемым пакетом C++ )
  • macOS 10.12.6 (Sierra) или новее (без поддержки графического процессора)
  • WSL2 через Windows 10 19044 или выше, включая графические процессоры (экспериментальная версия)
# Requires the latest pip pip install --upgrade pip 
# Current stable release for CPU and GPU pip install tensorflow
# Or try the preview build (unstable) pip install tf-nightly

Скачать пакет

Установите TensorFlow с помощью менеджера пакетов Python pip .

Официальные пакеты доступны для Ubuntu, Windows и macOS.

Прочтите руководство по установке pip

Запустите контейнер TensorFlow

Образы TensorFlow Docker уже настроены для запуска TensorFlow. Контейнер Docker работает в виртуальной среде и является самым простым способом настроить поддержку графического процессора.

docker pull tensorflow/tensorflow:latest # Download latest stable image 
docker run -it -p 8888:8888 tensorflow/tensorflow:latest-jupyter # Start Jupyter server

Google Colab: простой способ изучить и использовать TensorFlow

Установка не требуется — запускайте учебные пособия по TensorFlow прямо в браузере с помощью Colaboratory , исследовательского проекта Google, созданного для распространения образования и исследований в области машинного обучения. Это среда ноутбука Jupyter, которая не требует настройки для использования и полностью работает в облаке. Прочитайте сообщение в блоге .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *