gpt4 book ai didi

macos - macOS Apple M1 上的 Tensorflow

转载 作者:行者123 更新时间:2023-12-05 04:45:01 29 4
gpt4 key购买 nike

我正在尝试在我的 macOS M1 上安装 tensorflow 。根据芯片兼容性,我知道并非所有 tensorflow 的 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 为 generally available .

如果您还没有将机器升级到 Monterey 或更新的操作系统。

如果您安装了 conda,我可能会卸载它。您可以安装多个 conda 版本,但事情会变得棘手。

然后按照 Apple 的说明进行操作 here .我在下面对它们进行了一些清理:

从 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

您应该能够以较快的训练速度进行训练。

关于macos - macOS Apple M1 上的 Tensorflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69215644/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com