簡體   English   中英

macOS Apple M1 上的 TensorFlow

[英]Tensorflow on macOS Apple M1

我正在嘗試在我的 macOS M1 上安裝張量流。 根據芯片兼容性,我知道並非所有張量流的 pip 圖像都有效甚至兼容。 但我找到了這個存儲庫

https://github.com/apple/tensorflow_macos

這應該適用於Apple M1。

安裝后,我將 python 降級到 3.8 版並開始安裝,一切正常,沒有任何問題。

只是為了測試目的,我在網上找到了這個腳本。

#!/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)

但是當我運行它時,

我收到這個錯誤

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.

錯誤與架構有關,但我不知道如何修復。 有沒有人找到解決這個問題的方法?

非常感謝您提供的任何幫助。

現在事情應該會更好。

自 2021 年 10 月 25 日起,macOS 12 Monterey 正式發布

如果您還沒有,請將您的機器升級到 Monterey 或更新的操作系統。

如果你安裝了 conda,我可能會卸載它。 您可以安裝多個 conda 版本,但事情可能會變得棘手。

然后按照 Apple此處的說明進行操作。 我在下面清理了它們:

從 Miniforge 下載並安裝 Conda:

chmod +x ~/Downloads/Miniforge3-MacOSX-arm64.sh
sh ~/Downloads/Miniforge3-MacOSX-arm64.sh
source ~/miniforge3/bin/activate

在活動的 conda 環境中,安裝 TensorFlow 依賴項、基本 TensorFlow 和 TensorFlow metal:

conda install -c apple tensorflow-deps
pip install tensorflow-macos
pip install tensorflow-metal

你應該很好地進行快速訓練。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM