Tensorflow on macOS Apple M1
Asked Answered
B

1

3

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.

Binni answered 16/9, 2021 at 21:59 Comment(1)
Did you tried suggestions discussed here, here?Terse
I
2

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.

Interval answered 29/10, 2021 at 18:53 Comment(2)
"If you have conda installed, uninstall it." - that's a bit much. I'm a Miniforge/Mambaforge fan, but uprooting an existing installation is unnecessary.Colorado
To clarify, I am not recommending multiple installations. One can toggle an installation between architectures by setting the subdir configuration value (osx-64 vs osx-arm64). This can even be done on a per environment basis.Colorado

© 2022 - 2024 — McMap. All rights reserved.