model_SVC = SVC(C=1000,gamma=0.1, kernel='rbf')
model_SVC.fit(X_train,Y_train) #CASIA2
predictions=model_SVC.predict(X_test)
print(accuracy_score(Y_test,predictions))
print(confusion_matrix(Y_test,predictions))
print(classification_report(Y_test,predictions))
I need help in creating a confusion matrix using seaborn and a code to predict the image.
Can someone help me with this?
I have used your code along with some random code to generate data and ConfusionMatrixDisplay to generate the confusion matrix. You can change the parameters as required to suit your needs.
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.datasets import make_classification
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X, y = make_classification(random_state=0)
X_train, X_test, Y_train, Y_test = train_test_split(X, y, random_state=0)
model_SVC = SVC(C=1000,gamma=0.1, kernel='rbf')
model_SVC.fit(X_train,Y_train) #CASIA2
predictions=model_SVC.predict(X_test)
#print(accuracy_score(Y_test,predictions))
cm = confusion_matrix(Y_test,predictions)
#print(classification_report(Y_test,predictions))
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=model_SVC.classes_)
font={'size':'14'}
plt.rc('font',**font)
plt.rcParams['figure.figsize']=[6,6]
disp.plot(cmap='Blues',values_format='0.2f')
#plt.colorbar(im,fraction=0.046, pad=0.04)
plt.show()
Plot
Related
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 16 18:17:32 2023
#author: avnth
"""
import seaborn as sb
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from sklearn.metrics import silhouette_score
from sklearn.metrics import davies_bouldin_score
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler as sc
from mpl_toolkits import mplot3d
import plotly.express as px
dta=pd.read_csv("D:/XLRI/Term-4/ML/Assignment-2/Prpd_2.csv")
dta.head()
dta1=dta.drop("Cid",axis=1,inplace=False)
#dta1=dta1.iloc[:,1:4]
dta1=pd.DataFrame(dta1)
dta1.head()
dta1.describe()
dta1=pd.DataFrame(dta1)
dta1.describe()
ncl=[]
for i in range(1,15):
kn=KMeans(n_clusters=i)
kn.fit(dta1)
ncl.append(kn.inertia_)
plt.plot(range(1,15),ncl)
#silhoute method
sil = []
for n in range(2,15):
kn1=KMeans(n_clusters = n)
kn1.fit(dta1)
# labels = kn1.labels_
sil.append(silhouette_score(dta1,kn1.labels_, metric = 'euclidean'))
plt.plot(range(2,15),sil)
#Davies Bouldin Index method
db = []
K1 = range(2,8)
for l in K1:
kn2 = (KMeans(n_clusters = l) )
kn2.fit(dta1)
db.append(davies_bouldin_score(dta1,kn2.labels_))
plt.plot(range(2,8),db)
sa=sc()
sa.fit(dta1)
tdta1=sa.transform(dta1)
tdta1=pd.DataFrame(tdta1)
kmc=KMeans(n_clusters=6)
kmc.fit(tdta1)
clus=kmc.predict(tdta1)
dta["clus"]=clus
dta.head()
clus4=dta[dta.clus==4]
clus4.describe()
clus0=dta[dta.clus==0]
clus0.describe()
clus5=dta[dta.clus==5]
clus5.describe()
clus3=dta[dta.clus==3]
clus3.describe()
sb.scatterplot("Recency","Frequency",data=dta,hue="clus")
sb.scatterplot("Frequency","Money",data=dta,hue="clus")
# Creating dataset
z = dta.Recency
x = dta.Frequency
y = dta.Money
z.head()
x.head()
y.head()
# Creating figure
#fig = plt.figure()
#ax = fig.add_subplot(111,projection ="3d")
#dta=pd.DataFrame(dta)
#dta.head()
#for a in range(0,5):
# ax.scatter(dta.Frequency[dta.clus==a],dta.Recency[dta.clus==a],dta.Money[dta.clus==a],label=a,hue="clus")
#ax.legend()
#plt.title("simple 3D scatter plot")
#plt.show()
#df = px.data.iris()
#fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',color='petal_length',symbol='species')
#fig=plt.figure()
Hello Frieds,
I am newbie to python. Just learning. I have taken a dataset and clustered it. Now, I want to plot it in 3d scatter plot with a 4th dimension that is my cluster as color. For each cluster no new color should appear. So a data point will be plotted as x,y,z attribute but it will have color based on 4th column that is my cluster number. I know how to do it in 2d with hue. But I am unable to find similar thing in 3d plot. Any help will be appreicated. Atatching my code too.
I tried many libraries from online tutorial but I am not egtting exactly what I am looking for. I have attached a sample for how I want it to be plotted. Sample taken from plotly.com This is just replication how I want to plot.
enter image description here
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(z,x,y, marker=".", c=dta["clus"], s=50, cmap="RdBu")
plt.legend(clus)
plt.title("4D scatterplot")
ax.set_xlabel("Recency")
ax.set_ylabel("Frequency")
ax.set_zlabel("Money")
plt.show()
When I was trying to resize an image set, it was only resizing the first image.How to resize all images? This is my code:
import numpy as np
import os
import cv2
pic_num = 1
img = cv2.imread("E:\ele/"+str(pic_num)+'.jpg',cv2.IMREAD_GRAYSCALE)
resized_image = cv2.resize(img,(100,100))
cv2.imwrite("E:\eye/"+str(pic_num)+'.jpg',resized_image)
pic_num += 1
If you are just looping through files and change it, and don't worried about time.
then you can just use for loop in python
For example you have pics from 1 too 100
Then you can just do following:
import numpy as np
import os
import cv2
for pic_num in range(1,100):
img = cv2.imread("E:\ele/"+str(pic_num)+'.jpg',cv2.IMREAD_GRAYSCALE)
resized_image = cv2.resize(img,(100,100))
cv2.imwrite("E:\eye/"+str(pic_num)+'.jpg',resized_image)
Using python code we are able to create image segments as shown in the screenshot. our requirement is how to select specific segment in the image and apply different color to it ?
The following is our python snippet
from skimage.segmentation import felzenszwalb, slic,quickshift
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float
import matplotlib.pyplot as plt
from skimage import measure
from skimage import restoration
from skimage import img_as_float
image = img_as_float(io.imread("leaf.jpg"))
segments = quickshift(image, ratio=1.0, kernel_size=20, max_dist=10,return_tree=False, sigma=0, convert2lab=True, random_seed=42)
fig = plt.figure("Superpixels -- %d segments" % (500))
ax = fig.add_subplot(1, 1, 1)
ax.imshow(mark_boundaries(image, segments))
plt.axis("off")
plt.show()
do this:
seg_num = 64 # desired segment to be colored
color = float64([1,0,0]) # red color
image[segments == 64] = color # assign color to the segment
You can use OpenCV python module - example:
I am writing the following code for display image in my window but image is not displayed. Only blank window appearing.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from Tkinter import *
import matplotlib, sys
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib import pylab as plt
root=Tk()
fr=Frame(root)
fr.pack()
image = mpimg.imread("C:\Users\Public\Pictures\SamplePictures\Koala.jpg")
f = Figure(figsize=(5,5), dpi=100)
im=plt.imshow(image)
canvas = FigureCanvasTkAgg(f, fr)
canvas.show()
canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
root.mainloop()
Above question have solution to display image in canvas. we need to replace
f= Figure(figsize=(5,5), dpi=100) into f=plt.figure(figsize=(5,5), dpi=100) this line
I am trying to display a wxpython screen shot in pyplot but I dont want to save the image.
this is what I have
import wx
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
thisApp = wx.App( redirect=False )
def saveSnapshot(dcSource): #takes arg dcSource
# based largely on code posted to wxpython-users by Andrea Gavana 2006-11-08
size = dcSource.Size
bmp = wx.EmptyBitmap(size.width, size.height)
memDC = wx.MemoryDC()
memDC.SelectObject(bmp)
memDC.Blit( 0, 0, size.width, size.height, dcSource, 0, 0)
memDC.SelectObject(wx.NullBitmap)
img = bmp.ConvertToImage()
img.SaveFile('saved.png', wx.BITMAP_TYPE_PNG)
img = mpimg.imread('saved.png')
plt.imshow(img)
plt.show()
saveSnapshot(wx.ScreenDC())
this is something like what I want, basically not to save the file just display it.
img = bmp.ConvertToImage()
plt.imshow(img)
plt.show()
You can use a BytesIO object. A possible solution would be:
import wx
from matplotlib import pyplot as plt
from io import BytesIO
thisApp = wx.App(redirect=False)
def saveSnapshot(dcSource):
size = dcSource.Size
bmp = wx.EmptyBitmap(size.width, size.height)
memDC = wx.MemoryDC()
memDC.SelectObject(bmp)
memDC.Blit( 0, 0, size.width, size.height, dcSource, 0, 0)
memDC.SelectObject(wx.NullBitmap)
img = bmp.ConvertToImage()
bio = BytesIO()
bs = wx.OutputStream(bio)
img.SaveStream(bs, wx.BITMAP_TYPE_PNG)
bio.seek(0) #rewind stream
plt.imshow(plt.imread(bio))
plt.show()
saveSnapshot(wx.ScreenDC())
I found some ideas for this approach here.
Update:
A slightly different approach using pyscreenshot could look like:
import matplotlib.pyplot as plt
import pyscreenshot as ImageGrab
def saveSnapshot():
im = ImageGrab.grab()
plt.imshow(im)
plt.show()