NodeJS 如何在js文件创建的python shell上安装sklearn?

bvjveswy  于 2023-04-11  发布在  Node.js
关注(0)|答案(1)|浏览(122)

我试图从一个js文件运行一个用python编写的情绪分析脚本。python脚本在我的终端上运行得很好,但是当我从js文件运行它时,它抛出一个错误说

Traceback (most recent call last):
  File "~/ml_models/sentiment_analysis_script.py", line 6, in <module>
    model = pickle.load(f)
ModuleNotFoundError: No module named 'sklearn'

我已经尝试在根文件夹中安装sklearn,但它仍然不工作。这是我目前为我的js文件所拥有的代码

let runPy = new Promise(function(success, nosuccess) {

  const { spawn } = require('child_process');
  const pyprog = spawn('/usr/bin/python3', ['sentiment_analysis_script.py', "my new puppy is so cute"]);

  pyprog.stderr.on('data', (data) => {
    console.log("no success");
      nosuccess(data.toString());
  });

  pyprog.stdout.on('data', function(data) {
      console.log("success");
      success(data.toString());
  });
});

runPy.then(function(fromRunpy) {
  console.log(fromRunpy);
}).catch(function(err) {
  console.error(err);
});

我的python脚本中的代码

import pickle
import sys

# load the saved model and vectorizer from disk
with open('note_sentiment_analysis.pkl', 'rb') as f:
    model = pickle.load(f)

with open('note_vectorizer.pkl', 'rb') as f:
    vectorizer = pickle.load(f)

# Get text input from the user
text = sys.argv[1]

# Preprocess the data
text = text.lower()
text = text.replace('[^\w\s]','')
text = text.replace('\d+','')
text = text.replace('\n',' ')
text = text.replace('\t',' ')

# Vectorize the text
vectorized_text = vectorizer.transform([text])

# Predict the sentiment using the model
prediction = model.predict(vectorized_text)[0]

# Get the probability estimates for each class
proba = model.predict_proba(vectorized_text)[0]

# Print the prediction and probability estimates
if prediction == 0:
    print("Negative sentiment with probability {:.2f}%".format(proba[0]*100))
else:
    print("Positive sentiment with probability {:.2f}%".format(proba[1]*100))

如果有任何帮助,可以让我运行这个python脚本,并从js文件中收集它的输出,我将非常感激!

zujrkrfu

zujrkrfu1#

错误消息表明,用于执行脚本的Python环境中未安装“sklearn”模块。要安装“sklearn”,您可以在Python脚本的末尾添加以下代码:

import subprocess
subprocess.check_call(["pip", "install", "scikit-learn"])

您可以在运行JavaScript文件之前在Python环境中手动完成。打开终端,在包含'sentiment_analysis_scripy.py'的目录中运行pip install scikit-learn。

相关问题