Tensorflow on macOS Apple M1 - macos

I am trying to install tensor flow on my macOS M1.
As per chip compatibility I know that not all the pip images of tensor flow works or are even compatible. But I found this repository
https://github.com/apple/tensorflow_macos
Which is supposed to be working on Apple M1.
After the installation, I downgraded my python to version 3.8 and start the installation, everything went just fine without any issue.
just for testing purpose, I found this script online.
#!/usr/bin/env python
# coding: utf-8
# ## Sentiment Analysis on US Airline Reviews
# In[1]:
import pandas as pd
import matplotlib.pyplot as plt
from tensorflow.python.compiler.mlcompute import mlcompute
mlcompute.set_mlc_device(device_name='cpu')
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM,Dense, Dropout, SpatialDropout1D
from tensorflow.keras.layers import Embedding
df = pd.read_csv("./Tweets.csv")
# In[2]:
df.head()
# In[23]:
df.columns
# In[4]:
tweet_df = df[['text','airline_sentiment']]
print(tweet_df.shape)
tweet_df.head(5)
# In[22]:
tweet_df = tweet_df[tweet_df['airline_sentiment'] != 'neutral']
print(tweet_df.shape)
tweet_df.head(5)
# In[21]:
tweet_df["airline_sentiment"].value_counts()
# In[6]:
sentiment_label = tweet_df.airline_sentiment.factorize()
sentiment_label
# In[7]:
tweet = tweet_df.text.values
tokenizer = Tokenizer(num_words=5000)
tokenizer.fit_on_texts(tweet)
vocab_size = len(tokenizer.word_index) + 1
encoded_docs = tokenizer.texts_to_sequences(tweet)
padded_sequence = pad_sequences(encoded_docs, maxlen=200)
# In[8]:
print(tokenizer.word_index)
# In[9]:
print(tweet[0])
print(encoded_docs[0])
# In[10]:
print(padded_sequence[0])
# In[11]:
embedding_vector_length = 32
model = Sequential()
model.add(Embedding(vocab_size, embedding_vector_length, input_length=200) )
model.add(SpatialDropout1D(0.25))
model.add(LSTM(50, dropout=0.5, recurrent_dropout=0.5))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',optimizer='adam', metrics=['accuracy'])
print(model.summary())
# In[12]:
history = model.fit(padded_sequence,sentiment_label[0],validation_split=0.2, epochs=5, batch_size=32)
# In[16]:
plt.plot(history.history['accuracy'], label='acc')
plt.plot(history.history['val_accuracy'], label='val_acc')
plt.legend()
plt.show()
plt.savefig("Accuracy plot.jpg")
# In[25]:
plt.plot(history.history['loss'], label='loss')
plt.plot(history.history['val_loss'], label='val_loss')
plt.legend()
plt.show()
plt.savefig("Loss plot.jpg")
# In[18]:
def predict_sentiment(text):
tw = tokenizer.texts_to_sequences([text])
tw = pad_sequences(tw,maxlen=200)
prediction = int(model.predict(tw).round().item())
print("Predicted label: ", sentiment_label[1][prediction])
# In[19]:
test_sentence1 = "I enjoyed my journey on this flight."
predict_sentiment(test_sentence1)
test_sentence2 = "This is the worst flight experience of my life!"
predict_sentiment(test_sentence2)
But when I run it,
I get this error
Traceback (most recent call last):
File "/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/pywrap_tensorflow.py", line 64, in <module>
from tensorflow.python._pywrap_tensorflow_internal import *
ImportError: dlopen(/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 6): no suitable image found. Did find:
/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so: mach-o, but wrong architecture
/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so: mach-o, but wrong architecture
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Sentiment Analysis.py", line 13, in <module>
from tensorflow.python.compiler.mlcompute import mlcompute
File "/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/__init__.py", line 41, in <module>
from tensorflow.python.tools import module_util as _module_util
File "/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/__init__.py", line 39, in <module>
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
File "/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/pywrap_tensorflow.py", line 83, in <module>
raise ImportError(msg)
ImportError: Traceback (most recent call last):
File "/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/pywrap_tensorflow.py", line 64, in <module>
from tensorflow.python._pywrap_tensorflow_internal import *
ImportError: dlopen(/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 6): no suitable image found. Did find:
/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so: mach-o, but wrong architecture
/Users/user/Desktop/MachineLearning/env/lib/python3.8/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so: mach-o, but wrong architecture
Failed to load the native TensorFlow runtime.
See https://www.tensorflow.org/install/errors
for some common reasons and solutions. Include the entire stack trace
above this error message when asking for help.
The error is about the architecture but I have no idea how to fix. Did anyone found a solution to this problem?
Thank you so much for any help you can provide.

Things should work better now.
As of Oct. 25, 2021 macOS 12 Monterey is generally available.
Upgrade your machine to Monterey or newer OS if you haven't already.
If you have conda installed, I would probably uninstall it. You can have multiple conda versions installed but things can get tricky.
Then follow the instructions from Apple here. I cleaned them up a bit below:
Download and install Conda from Miniforge:
chmod +x ~/Downloads/Miniforge3-MacOSX-arm64.sh
sh ~/Downloads/Miniforge3-MacOSX-arm64.sh
source ~/miniforge3/bin/activate
In an active conda environment, install the TensorFlow dependencies, base TensorFlow, and TensorFlow metal:
conda install -c apple tensorflow-deps
pip install tensorflow-macos
pip install tensorflow-metal
You should be good to go with fast training speeds.

Related

Error importing pandas through the bash envrionment

I've attempted to resolve this with answers to similar issues in the forum but was unsuccessful. Any help would be much appreciated as I've been stuck for a while.
I have downloaded Python through the Anaconda distribution.
When I attempt to import pandas by running a script (forum.py) in GITBASH I get the following error:
$ python forum.py
Traceback (most recent call last): File "forum.py", line 1, in
import pandas as pd File "C:\Users\jimen\Anaconda3\lib\site-packages\pandas__init__.py", line
42, in
from pandas.core.api import * File "C:\Users\jimen\Anaconda3\lib\site-packages\pandas\core\api.py", line
10, in
from pandas.core.groupby import Grouper File "C:\Users\jimen\Anaconda3\lib\site-packages\pandas\core\groupby.py",
line 50, in
from pandas.core.frame import DataFrame File "C:\Users\jimen\Anaconda3\lib\site-packages\pandas\core\frame.py",
line 77, in
from pandas.core.series import Series File "C:\Users\jimen\Anaconda3\lib\site-packages\pandas\core\series.py",
line 81, in
import pandas.plotting._core as gfx File "C:\Users\jimen\Anaconda3\lib\site-packages\pandas\plotting__init__.py",
line 15, in
from pandas.plotting._converter import \ File "C:\Users\jimen\Anaconda3\lib\site-packages\pandas\plotting_converter.py",
line 8, in
import matplotlib.units as units File "C:\Users\jimen\Anaconda3\lib\site-packages\matplotlib__init__.py",
line 1111, in
rcParamsOrig = RcParams(rcParams.copy()) File "C:\Users\jimen\Anaconda3\lib\site-packages\matplotlib__init__.py",
line 891, in getitem
from matplotlib import pyplot as plt File "C:\Users\jimen\Anaconda3\lib\site-packages\matplotlib\pyplot.py",
line 32, in
import matplotlib.colorbar File "C:\Users\jimen\Anaconda3\lib\site-packages\matplotlib\colorbar.py",
line 28, in
import matplotlib.artist as martist AttributeError: module 'matplotlib' has no attribute 'artist'
I'm not sure what to do and how to resolve this so any help would be much appreciated.
Thanks !

Python virtual Env, Py2app build, error with wxpython

I have created a virtual env on MacOS 10.14, with python 2.7, pip installed py2app, wxpython, etc, ran the Py2app command:
sudo python setup.py py2app
Upon running the app, I see the below error:
(ENV) kevins-MacBook-Pro:Audio_Export_App kevin$ /Users/kevin/python_scripts/Audio_Export_App/dist/Audio_Export_App_V3.3.app/Contents/MacOS/Audio_Export_App_V3.3
Traceback (most recent call last):
File "/Users/kevin/python_scripts/Audio_Export_App/dist/Audio_Export_App_V3.3.app/Contents/Resources/__boot__.py", line 107, in <module>
_run()
File "/Users/kevin/python_scripts/Audio_Export_App/dist/Audio_Export_App_V3.3.app/Contents/Resources/__boot__.py", line 82, in _run
exec(compile(source, path, 'exec'), globals(), globals())
File "/Users/kevin/python_scripts/Audio_Export_App/dist/Audio_Export_App_V3.3.app/Contents/Resources/Audio_Export_App_V3.3.py", line 1, in <module>
import wx
File "wx/__init__.pyc", line 17, in <module>
File "wx/core.pyc", line 12, in <module>
File "wx/_core.pyc", line 14, in <module>
File "wx/_core.pyc", line 10, in __load
ImportError: dlopen(/Users/kevin/python_scripts/Audio_Export_App/dist/Audio_Export_App_V3.3.app/Contents/Resources/lib/python2.7/lib-dynload/wx/_core.so, 2): Symbol not found: __ZThn1216_N10wxTextCtrl3CutEv
Referenced from: /Users/kevin/python_scripts/Audio_Export_App/dist/Audio_Export_App_V3.3.app/Contents/Resources/lib/python2.7/lib-dynload/wx/_core.so
Expected in: /usr/local/lib/libwx_osx_cocoau_core-3.0.0.4.0.dylib
in /Users/kevin/python_scripts/Audio_Export_App/dist/Audio_Export_App_V3.3.app/Contents/Resources/lib/python2.7/lib-dynload/wx/_core.so
2018-10-17 07:58:27.927 Audio_Export_App_V3.3[10303:567300] Audio_Export_App_V3.3 Error
2018-10-17 07:58:28.070 Audio_Export_App_V3.3[10303:567300] GetInputSourceEnabledPrefs user file path = /Users/kevin/Library/Preferences/com.apple.HIToolbox.plist
2018-10-17 07:58:28.070 Audio_Export_App_V3.3[10303:567300] GetInputSourceEnabledPrefs effective user id path = 501
2018-10-17 07:58:28.070 Audio_Export_App_V3.3[10303:567300] GetInputSourceEnabledPrefs user pref content = <CFBasicHash 0x10017c320 [0x7fff9887c8e0]>{type = immutable dict, count = 0,
entries =>
}
I have searched high and low for a solution, but cannot find one.
Anyone able to shed some light on this issue please?
This is an issue with Py2App. It can be solved by manually specifying the wx package during the build process:
python setup.py py2app --packages=wx
Hope that helps.
Source: https://bitbucket.org/ronaldoussoren/py2app/issues/252/py2app-creates-broken-bundles-with

LazyITKModule' object has no attribute 'AnalyzeImageIO'

from medpy.io import load
import SimpleITK
import vtk
image_data, image_header = load('/Users/N01-T2.mha')
print image_data.shape
And the error is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/wuzhenglin/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
execfile(filename, namespace)
File "/Users/wuzhenglin/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/Users/wuzhenglin/Python_nice/SAL_LUNG/test.py", line 140, in <module>
changeage()
File "/Users/wuzhenglin/Python_nice/SAL_LUNG/test.py", line 42, in changeage
image_data, image_header = load('/Users/wuzhenglin/Python_nice/SAL_BRAIN/brain_healthy_dataset/Normal001-T2.mha')
File "/Users/wuzhenglin/anaconda/lib/python2.7/site-packages/medpy/io/load.py", line 201, in load
raise err
medpy.core.exceptions.ImageLoadingError: Failes to load image /Users/wuzhenglin/Python_nice/SAL_BRAIN/brain_healthy_dataset/Normal001-T2.mha as
Itk/Vtk MetaImage (.mhd, .mha/.raw). Reason signaled by third-party module:
'LazyITKModule' object has no attribute 'AnalyzeImageIO'
I want to deal with .mha image, but it doesn't work.
I have installed medpy, itk and vtk.
I have searched on Google, but there is not related answer to this problem.
Does the same error occur without the import SimpleITK line? I don't think that is relevant to producing this error.
ITK for Python and SimpleITK are two separate Python packages which provide different interfaces to ITK. The error you are seeing is lated to ITK for Python, or the itk package on PyPi. Where did you itk install come from. Can you run a simple program like this, with your install?
#!/usr/bin/env python
import itk
pixelType = itk.UC
imageType = itk.Image[pixelType, 2]
readerType = itk.ImageFileReader[imageType]

iolib import error in python

On Mac OS X Mountain Lion, I try
import numpy as np
import os
import statsmodels.api as sm
I get this error:
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python /Users/idf/PycharmProjects/PyAlgoTrade/GoldvsMiners.py
Traceback (most recent call last):
File "/Users/idf/PycharmProjects/PyAlgoTrade/GoldvsMiners.py", line 9, in <module>
import statsmodels.api as sm
File "/Library/Python/2.7/site-packages/statsmodels-0.0.0-py2.7-macosx-10.8-intel.egg/statsmodels/api.py", line 1, in <module>
import iolib, datasets, tools
ImportError: No module named iolib
If I add
import sys
print("=======")
print sys.path
print("=======")
I get
=======
['/Users/idf/PycharmProjects/PyAlgoTrade', '/Library/Python/2.7/site-packages/pytz-2013b-py2.7.egg', '/Library/Python/2.7/site-packages/statsmodels-0.0.0-py2.7-macosx-10.8-intel.egg', '/Library/Python/2.7/site-packages/pip-1.4-py2.7.egg', '/Users/idf/PycharmProjects/PyAlgoTrade', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages']
=======
I have tried searching the net, but I am stuck on this one. Any ideas?

running package throws ImportError: No module named image

Using cx_freeze under ubuntu 12.04. The generation of the package is
done without any errors but when I try to run the package as a
standalone, I get the following error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/cx_Freeze/initscripts /Console.py",
line 27, in <module>
exec code in m.__dict__
m m File "Setup_cx_freeze.py", line 3, in <module>
File "/usr/local/lib/python2.7/dist-packages/cx_Freeze/__init__.py",
line 4, in <module>
from cx_Freeze.dist import *
File "/usr/local/lib/python2.7/dist-packages/cx_Freeze/dist.py",
line 3, in <module>
import distutils.command.install
File "/usr/lib/python2.7/distutils/command/install.py", line 21, in <module>
from site import USER_BASE
File "/usr/lib/python2.7/site.py", line 562, in <module>
main()
File "/usr/lib/python2.7/site.py", line 540, in main
abs__file__()
File "/usr/lib/python2.7/site.py", line 100, in abs__file__
m.__file__ = os.path.abspath(m.__file__)
File "/usr/lib/python2.7/email/__init__.py", line 79, in __getattr__
__import__(self.__name__)
ImportError: No module named image
I think what to focus on is the last sentence. "ImportError: No module named image."
The application runs without any problems in pure python environment
So why do I get the Error when running it as a "freeze" package? The
fault is somehow introduced when generating the freeze-package.
I ended up fixing this by explicitly including the package "email.mime" in the setup.py script build exe options.
Missing 'image' is just first part of the problem. Try to add this to your code:
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.message import MIMEMessage
This resolved problems with 'image', 'audio' and 'message'.
Resolved this by installing Python Imaging Library: http://www.pythonware.com/products/pil/
1) python setup.py build
2) sudo python setup.py install

Resources