Python 错误:没有名为';树,树 导入系统 从操作系统导入列表目录,九月 将numpy作为np导入 进口泡菜 从PIL导入图像 进口cv2 从sklearn.employ导入随机林分类器 将numpy作为np导入 从PIL导入图像 默认图像大小=(45,45) 分割点系数=0.8 类预测服务: 定义初始化(自): #self.dataset=datasetDIR #self.testImage=testImage 通过 def getImageVector(自身,图像): 尝试: #注:来自文档 #将彩色图像转换为黑白(模式“L”)时,库使用ITU-R 601-2 luma变换: #L=R*299/1000+G*587/1000+B*114/1000 imageGrayscale=Image.open(Image.convert('L')) #将图像大小调整为默认图像大小-45 x 45 imageGrayscale=imageGrayscale.resize(默认的图像大小,图像.ANTIALIAS) # imageNP=np.数组(imageGrayscale) imgList=[] 对于imageNP中的行: 对于行中的值: imgList.append(值) #imgList是一个长向量 返回imgList 例外情况除外,如e: 打印(“错误:{}”。格式(e)) 一无所获 def addImagesToSet(self、rootPath、imageList、label、completeImageList=[],labelList=[]): 破折号=['-'、'/'、'-'、'\\'] 计数器=0 对于imageList中的图像: 打印(“[{}]图像加载…”。格式(破折号[计数器]) 计数器=(计数器+1)%len(破折号) completeImageList.append(self.getImageVector(根路径+图像)) labelList.append(标签) def getTrainingAndTestData(自身,目录路径): dirList=listdir(directoryPath) xTrain、yTrain、xTest、yTest=[]、[]、[]、[]、[] 尝试: 如果len(dirList)检查更新->选项”将在下方右侧弹出更新选项,将您的pycharm更新至其最新版本2020.1.5? import sys from os import listdir, sep import numpy as np import pickle from PIL import Image import cv2 from sklearn.ensemble import RandomForestClassifier import numpy as np from PIL import Image DEFAULT_IMAGE_SIZE = (45,45) SPLIT_POINT_COEFF = 0.8 class PredictionService: def __init__(self): #self.dataset = datasetDIR #self.testImage = testImage pass def getImageVector(self, image): try: #NOTE:from docs #When translating a color image to black and white (mode “L”), the library uses the ITU-R 601-2 luma transform: #L = R * 299/1000 + G * 587/1000 + B * 114/1000 imageGrayscale = Image.open(image).convert('L') #resize image to default image size - 45 x 45 imageGrayscale = imageGrayscale.resize(DEFAULT_IMAGE_SIZE, Image.ANTIALIAS) # imageNP = np.array(imageGrayscale) imgList = [] for line in imageNP: for value in line: imgList.append(value) #imgList is 2025 long vector return imgList except Exception as e: print("Error : {}".format(e)) return None def addImagesToSet(self, rootPath, imageList, label, completeImageList = [], labelList = []): dashes = ['-','/','-','\\'] counter = 0 for image in imageList: print('[{}] Images loading...'.format(dashes[counter])) counter = (counter + 1) % len(dashes) completeImageList.append(self.getImageVector(rootPath + image)) labelList.append(label) def getTrainingAndTestData(self, directoryPath): dirList = listdir(directoryPath) xTrain, yTrain, xTest, yTest = [], [], [], [] try: if len(dirList) < 1: return None imageDirPath = None counter = 1 for directory in dirList: imageDir = listdir('{}/{}'.format(directoryPath, directory)) splitPoint = int(SPLIT_POINT_COEFF * len(imageDir)) print('[{}] Loading dataset - {} images'.format(counter, directory)) counter += 1 trainImages, testImages = imageDir[:splitPoint], imageDir[splitPoint:] imageDirPath = directoryPath + sep + directory + sep self.addImagesToSet(imageDirPath, trainImages, directory, xTrain, yTrain) self.addImagesToSet(imageDirPath, testImages, directory, xTest, yTest) except Exception as e: print('Error: {}'.format(e)) return [],[],[],[] return xTrain, yTrain, xTest, yTest def trainModel(self, trainDatasetDir): train_dataset_dir = ('C:/Users/MUTHU/Documents/GitHub/Handwritten-math-symbols-recognition/Dataset') print('Training.....') xTrain, yTrain, xTest , yTest = self.getTrainingAndTestData(trainDatasetDir) if [] not in (xTrain, yTrain, xTest , yTest): randomForestClassifier = RandomForestClassifier() randomForestClassifier.fit(xTrain,yTrain) accuracyScore = randomForestClassifier.score(xTrain,yTrain) # save classifier pickle.dump(randomForestClassifier,open("Model/math_recognition_model.pkl",'wb')) print("Model Accuracy Score : {}".format(accuracyScore)) testAccuracyScore = randomForestClassifier.score(xTest,yTest) print("Model Accuracy Score (Test) : {}".format(testAccuracyScore)) else : print("An error occurred.") def predict(self, imagePath): try: image = [self.getImageVector(imagePath)] # load saved model try: decisionTreeClassifierModel= pickle.load(open("Model/random_forest_classifier.pkl",'rb')) modelPrediction = decisionTreeClassifierModel.predict(image) print(modelPrediction) print("Recognized expression:" + str(modelPrediction[0])) except FileNotFoundError as modelFileError: print("Error : {}".format(modelFileError)) self.trainModel(datasetDir) self.predict(imagePath) except FileNotFoundError as fileError: print("Error : {}".format(fileError)) except Exception as e: print("Error : {}".format(e))
请帮助我使用pycharam对这个问题进行排序。您需要在项目中单独导入它。为此,您可以参考以下链接:Python 错误:没有名为';树,树 导入系统 从操作系统导入列表目录,九月 将numpy作为np导入 进口泡菜 从PIL导入图像 进口cv2 从sklearn.employ导入随机林分类器 将numpy作为np导入 从PIL导入图像 默认图像大小=(45,45) 分割点系数=0.8 类预测服务: 定义初始化(自): #self.dataset=datasetDIR #self.testImage=testImage 通过 def getImageVector(自身,图像): 尝试: #注:来自文档 #将彩色图像转换为黑白(模式“L”)时,库使用ITU-R 601-2 luma变换: #L=R*299/1000+G*587/1000+B*114/1000 imageGrayscale=Image.open(Image.convert('L')) #将图像大小调整为默认图像大小-45 x 45 imageGrayscale=imageGrayscale.resize(默认的图像大小,图像.ANTIALIAS) # imageNP=np.数组(imageGrayscale) imgList=[] 对于imageNP中的行: 对于行中的值: imgList.append(值) #imgList是一个长向量 返回imgList 例外情况除外,如e: 打印(“错误:{}”。格式(e)) 一无所获 def addImagesToSet(self、rootPath、imageList、label、completeImageList=[],labelList=[]): 破折号=['-'、'/'、'-'、'\\'] 计数器=0 对于imageList中的图像: 打印(“[{}]图像加载…”。格式(破折号[计数器]) 计数器=(计数器+1)%len(破折号) completeImageList.append(self.getImageVector(根路径+图像)) labelList.append(标签) def getTrainingAndTestData(自身,目录路径): dirList=listdir(directoryPath) xTrain、yTrain、xTest、yTest=[]、[]、[]、[]、[] 尝试: 如果len(dirList)检查更新->选项”将在下方右侧弹出更新选项,将您的pycharm更新至其最新版本2020.1.5? import sys from os import listdir, sep import numpy as np import pickle from PIL import Image import cv2 from sklearn.ensemble import RandomForestClassifier import numpy as np from PIL import Image DEFAULT_IMAGE_SIZE = (45,45) SPLIT_POINT_COEFF = 0.8 class PredictionService: def __init__(self): #self.dataset = datasetDIR #self.testImage = testImage pass def getImageVector(self, image): try: #NOTE:from docs #When translating a color image to black and white (mode “L”), the library uses the ITU-R 601-2 luma transform: #L = R * 299/1000 + G * 587/1000 + B * 114/1000 imageGrayscale = Image.open(image).convert('L') #resize image to default image size - 45 x 45 imageGrayscale = imageGrayscale.resize(DEFAULT_IMAGE_SIZE, Image.ANTIALIAS) # imageNP = np.array(imageGrayscale) imgList = [] for line in imageNP: for value in line: imgList.append(value) #imgList is 2025 long vector return imgList except Exception as e: print("Error : {}".format(e)) return None def addImagesToSet(self, rootPath, imageList, label, completeImageList = [], labelList = []): dashes = ['-','/','-','\\'] counter = 0 for image in imageList: print('[{}] Images loading...'.format(dashes[counter])) counter = (counter + 1) % len(dashes) completeImageList.append(self.getImageVector(rootPath + image)) labelList.append(label) def getTrainingAndTestData(self, directoryPath): dirList = listdir(directoryPath) xTrain, yTrain, xTest, yTest = [], [], [], [] try: if len(dirList) < 1: return None imageDirPath = None counter = 1 for directory in dirList: imageDir = listdir('{}/{}'.format(directoryPath, directory)) splitPoint = int(SPLIT_POINT_COEFF * len(imageDir)) print('[{}] Loading dataset - {} images'.format(counter, directory)) counter += 1 trainImages, testImages = imageDir[:splitPoint], imageDir[splitPoint:] imageDirPath = directoryPath + sep + directory + sep self.addImagesToSet(imageDirPath, trainImages, directory, xTrain, yTrain) self.addImagesToSet(imageDirPath, testImages, directory, xTest, yTest) except Exception as e: print('Error: {}'.format(e)) return [],[],[],[] return xTrain, yTrain, xTest, yTest def trainModel(self, trainDatasetDir): train_dataset_dir = ('C:/Users/MUTHU/Documents/GitHub/Handwritten-math-symbols-recognition/Dataset') print('Training.....') xTrain, yTrain, xTest , yTest = self.getTrainingAndTestData(trainDatasetDir) if [] not in (xTrain, yTrain, xTest , yTest): randomForestClassifier = RandomForestClassifier() randomForestClassifier.fit(xTrain,yTrain) accuracyScore = randomForestClassifier.score(xTrain,yTrain) # save classifier pickle.dump(randomForestClassifier,open("Model/math_recognition_model.pkl",'wb')) print("Model Accuracy Score : {}".format(accuracyScore)) testAccuracyScore = randomForestClassifier.score(xTest,yTest) print("Model Accuracy Score (Test) : {}".format(testAccuracyScore)) else : print("An error occurred.") def predict(self, imagePath): try: image = [self.getImageVector(imagePath)] # load saved model try: decisionTreeClassifierModel= pickle.load(open("Model/random_forest_classifier.pkl",'rb')) modelPrediction = decisionTreeClassifierModel.predict(image) print(modelPrediction) print("Recognized expression:" + str(modelPrediction[0])) except FileNotFoundError as modelFileError: print("Error : {}".format(modelFileError)) self.trainModel(datasetDir) self.predict(imagePath) except FileNotFoundError as fileError: print("Error : {}".format(fileError)) except Exception as e: print("Error : {}".format(e)),python,scikit-learn,ensembles,Python,Scikit Learn,Ensembles,请帮助我使用pycharam对这个问题进行排序。您需要在项目中单独导入它。为此,您可以参考以下链接: 同时,从菜单选项“转到帮助->检查更新->选项”将在下方右侧弹出更新选项,将您的pycharm更新至其最新版本2020.1.5? import sys from os import listdir, sep import numpy as np import pickle from PIL import Image import cv2 from sklearn.ensemble import
同时,从菜单选项“转到帮助->检查更新->选项”将在下方右侧弹出更新选项,将您的pycharm更新至其最新版本2020.1.5?
import sys
from os import listdir, sep
import numpy as np
import pickle
from PIL import Image
import cv2
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from PIL import Image
DEFAULT_IMAGE_SIZE = (45,45)
SPLIT_POINT_COEFF = 0.8
class PredictionService:
def __init__(self):
#self.dataset = datasetDIR
#self.testImage = testImage
pass
def getImageVector(self, image):
try:
#NOTE:from docs
#When translating a color image to black and white (mode “L”), the library uses the ITU-R 601-2 luma transform:
#L = R * 299/1000 + G * 587/1000 + B * 114/1000
imageGrayscale = Image.open(image).convert('L')
#resize image to default image size - 45 x 45
imageGrayscale = imageGrayscale.resize(DEFAULT_IMAGE_SIZE, Image.ANTIALIAS)
#
imageNP = np.array(imageGrayscale)
imgList = []
for line in imageNP:
for value in line:
imgList.append(value)
#imgList is 2025 long vector
return imgList
except Exception as e:
print("Error : {}".format(e))
return None
def addImagesToSet(self, rootPath, imageList, label, completeImageList = [], labelList = []):
dashes = ['-','/','-','\\']
counter = 0
for image in imageList:
print('[{}] Images loading...'.format(dashes[counter]))
counter = (counter + 1) % len(dashes)
completeImageList.append(self.getImageVector(rootPath + image))
labelList.append(label)
def getTrainingAndTestData(self, directoryPath):
dirList = listdir(directoryPath)
xTrain, yTrain, xTest, yTest = [], [], [], []
try:
if len(dirList) < 1:
return None
imageDirPath = None
counter = 1
for directory in dirList:
imageDir = listdir('{}/{}'.format(directoryPath, directory))
splitPoint = int(SPLIT_POINT_COEFF * len(imageDir))
print('[{}] Loading dataset - {} images'.format(counter, directory))
counter += 1
trainImages, testImages = imageDir[:splitPoint], imageDir[splitPoint:]
imageDirPath = directoryPath + sep + directory + sep
self.addImagesToSet(imageDirPath, trainImages, directory, xTrain, yTrain)
self.addImagesToSet(imageDirPath, testImages, directory, xTest, yTest)
except Exception as e:
print('Error: {}'.format(e))
return [],[],[],[]
return xTrain, yTrain, xTest, yTest
def trainModel(self, trainDatasetDir):
train_dataset_dir = ('C:/Users/MUTHU/Documents/GitHub/Handwritten-math-symbols-recognition/Dataset')
print('Training.....')
xTrain, yTrain, xTest , yTest = self.getTrainingAndTestData(trainDatasetDir)
if [] not in (xTrain, yTrain, xTest , yTest):
randomForestClassifier = RandomForestClassifier()
randomForestClassifier.fit(xTrain,yTrain)
accuracyScore = randomForestClassifier.score(xTrain,yTrain)
# save classifier
pickle.dump(randomForestClassifier,open("Model/math_recognition_model.pkl",'wb'))
print("Model Accuracy Score : {}".format(accuracyScore))
testAccuracyScore = randomForestClassifier.score(xTest,yTest)
print("Model Accuracy Score (Test) : {}".format(testAccuracyScore))
else :
print("An error occurred.")
def predict(self, imagePath):
try:
image = [self.getImageVector(imagePath)]
# load saved model
try:
decisionTreeClassifierModel= pickle.load(open("Model/random_forest_classifier.pkl",'rb'))
modelPrediction = decisionTreeClassifierModel.predict(image)
print(modelPrediction)
print("Recognized expression:" + str(modelPrediction[0]))
except FileNotFoundError as modelFileError:
print("Error : {}".format(modelFileError))
self.trainModel(datasetDir)
self.predict(imagePath)
except FileNotFoundError as fileError:
print("Error : {}".format(fileError))
except Exception as e:
print("Error : {}".format(e))