100*100层MLPClassifier神经网络AI算法分析图片标签
?
?
?
?
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier
from sklearn.feature_selection import SelectPercentile
from sklearn.decomposition import PCA
import numpy as np
from PIL import Image
import os
basedir=os.path.abspath('.')
X=[]
y=[]
target=["cat","dog"]
for i in os.listdir("img"):
f=os.path.join(basedir+"/img",i)
image=Image.open(f).convert('F')
image=image.resize((100,100))
data=np.array(image).astype(dtype=float)
data=np.array(data).flatten()
X.append(data)
y.append(0 if i[0]=='c' else 1)
clf=MLPClassifier(hidden_layer_sizes=(100,100))
dec=PCA(whiten=True)
X=np.array(X)
# dec.fit(X)
# X=dec.transform(X)
# X=fs.fit_transform(X,y)
clf.fit(X,y)
fig=plt.figure(figsize=(12,3))
# fig,ax=plt.subplots(2,4,figsize=(12,6))
a=1
for i in os.listdir("predict"):
f=os.path.join(basedir+"/predict",i)
image=Image.open(f).convert('F')
image=image.resize((100,100))
data=np.array(image).astype(dtype=float)
data = np.array(data).flatten()
# data=dec.transform(np.array([data]))
# data = fs.fit_transform(data)
p=clf.predict([data])
print("%s:%s" % (f,target[p[0]]))
ax=fig.add_subplot(1,4,a)
ax.set_xticks([]); ax.set_yticks([])
a+=1
ax.imshow(image)
ax.set_title("%s" % target[p[0]])
plt.show()
|